@aientrophy/sdk 0.2.0 → 0.2.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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Real-time bot detection, macro detection, and CAPTCHA protection for web applications.
4
4
 
5
- Aientrophy SDK monitors browser behavior (mouse movements, keystrokes, device fingerprints) to detect bots, automated tools, and suspicious activity — protecting your site from fraud, abuse, and scraping.
5
+ Aientrophy SDK monitors browser behavior (mouse movements, keystrokes) to detect bots, automated tools, and suspicious activity — protecting your site from fraud, abuse, and scraping.
6
6
 
7
7
  ## Getting Started
8
8
 
@@ -27,7 +27,7 @@ npm install @aientrophy/sdk
27
27
  Or via CDN:
28
28
 
29
29
  ```html
30
- <script src="https://cdn.aientrophy.com/sdk/latest/aientrophy.min.js"></script>
30
+ <script src="https://api.aientrophy.com/sdk/latest/aientrophy.min.js"></script>
31
31
  ```
32
32
 
33
33
  ## Quick Start
@@ -57,7 +57,7 @@ ai.protect();
57
57
  }
58
58
  };
59
59
  </script>
60
- <script src="https://cdn.aientrophy.com/sdk/latest/aientrophy.min.js"></script>
60
+ <script src="https://api.aientrophy.com/sdk/latest/aientrophy.min.js"></script>
61
61
  ```
62
62
 
63
63
  ## Configuration
@@ -123,7 +123,6 @@ ai.off('threat', handler);
123
123
  | `dom_mutation` | External script injection detected | High |
124
124
  | `input_metrics` | Robotic typing pattern | High |
125
125
  | `devtools_open` | Developer tools opened | Medium |
126
- | `environmental_integrity` | WebRTC leak / debugger detected | Medium |
127
126
 
128
127
  ## Callbacks
129
128
 
package/dist/core.js CHANGED
@@ -1 +1 @@
1
- !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).SecuritySDKCore={})}(this,function(t){"use strict";var e=Object.defineProperty,s=(t,s,i)=>((t,s,i)=>s in t?e(t,s,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[s]=i)(t,"symbol"!=typeof s?s+"":s,i);const i="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqbBCvDqyUtfhgI/Lo5pDtn1phwA6qczAyp8N1ZgQ68OTxgbJUGiXV6N67p15bBdME1R4va51P2Czq2IbRby/N+GHTciTaXvmusV8IjnIOGtKlGxWCuKIPrCS+rGjGA2j1irxBbNpqItltFxjhxBGOzsyQAF6LNIz5IKA7sC6cSH8zUyLuFrV96udc801Zc4nCJG64ZljNbDvlVbJJZ6ex5OLLS6AnrVAXpjEDR/MI/I8JvAPe/psHj6EpXgvKrBYMBOH3jzQRzMFoR79jXyGNgPjdy0A+f6RVuEG8H5sUXKeyy+cFvaT+pm6h+t6RPED11tCOwQxYZ2pExhhPxDGeQIDAQAB";class n{static async init(){if(this.sessionKey)return;this.sessionKey=await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]);const t=await this.importPublicKey(i),e=await window.crypto.subtle.exportKey("raw",this.sessionKey),s=await window.crypto.subtle.encrypt({name:"RSA-OAEP"},t,e);this.encryptedSessionKey=this.arrayBufferToBase64(s)}static async encrypt(t){this.sessionKey||await this.init();const e=JSON.stringify(t),s=(new TextEncoder).encode(e),i=window.crypto.getRandomValues(new Uint8Array(12)),n=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:i},this.sessionKey,s),a=new Uint8Array(n),r=a.slice(0,a.length-16),o=a.slice(a.length-16);return{ek:this.encryptedSessionKey,d:this.arrayBufferToBase64(r.buffer),iv:this.arrayBufferToBase64(i.buffer),tag:this.arrayBufferToBase64(o.buffer)}}static async decrypt(t){if(!this.sessionKey)throw new Error("Session key not initialized");const e=this.base64ToArrayBuffer(t.d),s=this.base64ToArrayBuffer(t.iv),i=this.base64ToArrayBuffer(t.tag),n=new Uint8Array(e.byteLength+i.byteLength);n.set(new Uint8Array(e),0),n.set(new Uint8Array(i),e.byteLength);const a=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:s},this.sessionKey,n),r=(new TextDecoder).decode(a);return JSON.parse(r)}static async importPublicKey(t){const e=window.atob(t),s=this.str2ab(e);return await window.crypto.subtle.importKey("spki",s,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"])}static str2ab(t){const e=new ArrayBuffer(t.length),s=new Uint8Array(e);for(let i=0,n=t.length;i<n;i++)s[i]=t.charCodeAt(i);return e}static arrayBufferToBase64(t){let e="";const s=new Uint8Array(t),i=s.byteLength;for(let n=0;n<i;n++)e+=String.fromCharCode(s[n]);return window.btoa(e)}static base64ToArrayBuffer(t){const e=window.atob(t),s=e.length,i=new Uint8Array(s);for(let n=0;n<s;n++)i[n]=e.charCodeAt(n);return i.buffer}}s(n,"sessionKey",null),s(n,"encryptedSessionKey",null);const a=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"]);class r{constructor(){s(this,"handlers",new Map),s(this,"configCallbacks",{})}setConfigCallbacks(t){this.configCallbacks=t}on(t,e){this.addHandler(t,e,!1)}once(t,e){this.addHandler(t,e,!0)}off(t,e){const s=this.handlers.get(t);if(!s)return;const i=s.filter(t=>t.handler!==e);0===i.length?this.handlers.delete(t):this.handlers.set(t,i)}emit(t,...e){this.callHandlers(t,e);const s=t.indexOf(":");if(-1!==s){const i=t.substring(0,s);this.callHandlers(i,e)}this.callConfigCallback(t,e)}emitChallenge(t){return new Promise(e=>{let s=!1;const i=t=>{s||(s=!0,e(t))},n=this.handlers.has("challenge")&&this.handlers.get("challenge").length>0,a=!!this.configCallbacks.onChallenge;n||a?(this.callHandlers("challenge",[t,i]),this.configCallbacks.onChallenge&&this.safeCall(this.configCallbacks.onChallenge,[t,i]),setTimeout(()=>{s||(s=!0,e(!1))},5e3)):e(!1)})}addHandler(t,e,s){this.handlers.has(t)||this.handlers.set(t,[]),this.handlers.get(t).push({handler:e,once:s})}callHandlers(t,e){const s=this.handlers.get(t);if(!s||0===s.length)return;const i=[];for(let n=0;n<s.length;n++)this.safeCall(s[n].handler,e),s[n].once&&i.push(n);for(let n=i.length-1;n>=0;n--)s.splice(i[n],1);0===s.length&&this.handlers.delete(t)}callConfigCallback(t,e){if(t.startsWith("threat:")||"threat"===t)return void(t.startsWith("threat:")&&this.configCallbacks.onThreatDetected&&this.safeCall(this.configCallbacks.onThreatDetected,e));const s={ready:"onReady",error:"onError",block:"onBlock",allow:"onAllow"}[t];s&&this.configCallbacks[s]&&this.safeCall(this.configCallbacks[s],e)}safeCall(t,e){try{t(...e)}catch(s){}}}class o{constructor(){s(this,"endpoint",""),s(this,"clientKey",""),s(this,"encryptionRequired",!1),s(this,"currentNonce",""),s(this,"buffer",[]),s(this,"batchSize",10),s(this,"flushInterval",1e3),s(this,"intervalId"),s(this,"responseHandler",null),s(this,"callbackManager",null),this.startFlushInterval()}setConfig(t){var e,s;this.endpoint=t.endpoint,this.clientKey=t.clientKey,this.encryptionRequired=(null==(e=t.serverConfig)?void 0:e.encryptionRequired)??!1,this.currentNonce=(null==(s=t.serverConfig)?void 0:s.initialNonce)??""}setResponseHandler(t){this.responseHandler=t}setCallbackManager(t){this.callbackManager=t}send(t,e={}){const s=Date.now();if(this.buffer.push({type:t,data:e,timestamp:s}),this.callbackManager)if(a.has(t)){const i={type:t,data:e,timestamp:s};this.callbackManager.emit(`threat:${t}`,i)}else this.callbackManager.emit(`data:${t}`,{type:t,data:e,timestamp:s});this.buffer.length>=this.batchSize&&this.flush()}async flush(){if(0===this.buffer.length||!this.endpoint)return;const t=this.buffer;this.buffer=[];try{let e;if(this.encryptionRequired){const s=await n.encrypt(t);e=JSON.stringify(s)}else e=JSON.stringify(t);const s={"Content-Type":"application/json","x-client-key":this.clientKey};this.currentNonce&&(s["x-request-nonce"]=this.currentNonce,this.currentNonce=""),fetch(this.endpoint,{method:"POST",body:e,headers:s,keepalive:!0}).then(async t=>{if(t.ok&&this.callbackManager&&this.callbackManager.emit("allow",{action:"allow"}),t.ok)try{const e=await t.json();let s=e;this.encryptionRequired&&(s=await n.decrypt(e)),(null==s?void 0:s.nonce)&&(this.currentNonce=s.nonce),this.responseHandler&&this.responseHandler(s)}catch(e){}}).catch(t=>{this.callbackManager&&this.callbackManager.emit("error",{code:"NETWORK_ERROR",message:"Failed to send security events"})})}catch(e){this.callbackManager&&this.callbackManager.emit("error",{code:"PAYLOAD_ERROR",message:"Failed to prepare security payload"})}}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.flush()}startFlushInterval(){this.intervalId=setInterval(()=>{this.flush()},this.flushInterval)}}class l{constructor(t){s(this,"transmitter"),s(this,"listeners",{}),this.transmitter=t}start(){this.attachListeners()}stop(){this.detachListeners()}attachListeners(){this.listeners.mousemove=this.throttle(t=>{const e=t;this.transmitter.send("mousemove",{x:e.clientX,y:e.clientY,timestamp:Date.now()})},100),this.listeners.click=t=>{const e=t;this.transmitter.send("click",{x:e.clientX,y:e.clientY,target:e.target.tagName,timestamp:Date.now()})},this.listeners.keydown=t=>{const e=t;this.transmitter.send("keydown",{key:e.key,timestamp:Date.now()})},window.addEventListener("mousemove",this.listeners.mousemove),window.addEventListener("click",this.listeners.click),window.addEventListener("keydown",this.listeners.keydown)}detachListeners(){this.listeners.mousemove&&window.removeEventListener("mousemove",this.listeners.mousemove),this.listeners.click&&window.removeEventListener("click",this.listeners.click),this.listeners.keydown&&window.removeEventListener("keydown",this.listeners.keydown)}throttle(t,e){let s;return function(...i){s||(t.apply(this,i),s=!0,setTimeout(()=>s=!1,e))}}}class c{constructor(t){s(this,"transmitter"),s(this,"trajectoryBuffer",[]),s(this,"keystrokeBuffer",[]),s(this,"isCollecting",!1),s(this,"flushInterval",3e3),s(this,"flushTimer"),s(this,"lastMouseMoveTime",0),s(this,"onMouseMove",t=>{const e=Date.now();e-this.lastMouseMoveTime>50&&(this.trajectoryBuffer.push({x:t.clientX,y:t.clientY,t:e}),this.lastMouseMoveTime=e)}),s(this,"onKeyDown",t=>{this.keystrokeBuffer.push({code:t.code,t:Date.now(),type:"down"})}),s(this,"onKeyUp",t=>{this.keystrokeBuffer.push({code:t.code,t:Date.now(),type:"up"})}),this.transmitter=t}start(){this.isCollecting||(this.isCollecting=!0,this.attachListeners(),this.startFlushTimer())}stop(){this.isCollecting=!1,this.detachListeners(),this.stopFlushTimer(),this.flush()}attachListeners(){window.addEventListener("mousemove",this.onMouseMove),window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp)}detachListeners(){window.removeEventListener("mousemove",this.onMouseMove),window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp)}startFlushTimer(){this.flushTimer=setInterval(()=>{this.flush()},this.flushInterval)}stopFlushTimer(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}flush(){if(0===this.trajectoryBuffer.length&&0===this.keystrokeBuffer.length)return;const t={trajectory:[...this.trajectoryBuffer],keystrokes:[...this.keystrokeBuffer],url:window.location.href};this.trajectoryBuffer=[],this.keystrokeBuffer=[],this.transmitter.send("behavior_data",t)}}class h{constructor(t){s(this,"transmitter"),s(this,"clickHistory",[]),s(this,"THRESHOLD_COUNT",3),s(this,"THRESHOLD_TIME",500),this.transmitter=t,this.init()}init(){document.addEventListener("click",t=>this.handleClick(t),!0)}handleClick(t){const e=Date.now();if(this.clickHistory.push(e),this.clickHistory=this.clickHistory.filter(t=>e-t<=this.THRESHOLD_TIME),this.clickHistory.length>=this.THRESHOLD_COUNT){const s=t.target,i={tagName:s.tagName,id:s.id,className:s.className,x:t.clientX,y:t.clientY};this.transmitter.send("rapid_click",{count:this.clickHistory.length,duration:this.THRESHOLD_TIME,target:i,timestamp:e}),this.clickHistory=[]}}}class d{constructor(t){s(this,"transmitter"),s(this,"element",null),this.transmitter=t}start(){this.element=document.createElement("input"),this.element.type="text";const t=["website","email_confirm","url","homepage","fax_number","address_line_2"],e=t[Math.floor(Math.random()*t.length)],s=Math.random().toString(36).substr(2,5);this.element.id="hp-"+Math.random().toString(36).substr(2,9),this.element.name=`${e}-${s}`,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 i=t=>{var e;this.transmitter.send("honeypot_triggered",{eventType:t.type,value:null==(e=this.element)?void 0:e.value,timestamp:Date.now()})};this.element.addEventListener("input",i),this.element.addEventListener("focus",i),this.element.addEventListener("click",i),document.body.appendChild(this.element)}stop(){this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element)}}class u{constructor(t,e){s(this,"transmitter"),s(this,"wasmService"),s(this,"buffer",[]),s(this,"BUFFER_SIZE",10),s(this,"SAMPLE_INTERVAL",50),s(this,"lastSampleTime",0),s(this,"handleMouseMove",t=>{const e=Date.now();e-this.lastSampleTime<this.SAMPLE_INTERVAL||(this.lastSampleTime=e,this.buffer.push({x:t.clientX,y:t.clientY,time:e}),this.buffer.length>this.BUFFER_SIZE&&(this.buffer.shift(),this.analyze()))}),this.transmitter=t,this.wasmService=e}start(){"undefined"!=typeof document&&document.addEventListener("mousemove",this.handleMouseMove)}stop(){"undefined"!=typeof document&&document.removeEventListener("mousemove",this.handleMouseMove)}analyze(){if(this.buffer.length<5)return;const t=this.wasmService.calculateEntropy(this.buffer),e=this.calculateSpeedVariance();this.transmitter.send("behavior_metrics",{entropy:t,speedVariance:e,timestamp:Date.now()}),this.buffer=[]}calculateSpeedVariance(){const t=[];for(let s=1;s<this.buffer.length;s++){const e=this.buffer[s-1],i=this.buffer[s],n=Math.sqrt(Math.pow(i.x-e.x,2)+Math.pow(i.y-e.y,2)),a=i.time-e.time;a>0&&t.push(n/a)}if(t.length<2)return 1;const e=t.reduce((t,e)=>t+e,0)/t.length;return t.reduce((t,s)=>t+Math.pow(s-e,2),0)/t.length}}class m{constructor(t){s(this,"lastInteractionTime",0),s(this,"lastInteractionType","none"),s(this,"transmitter"),s(this,"isMobile",!1),s(this,"keyPressTimes",new Map),s(this,"lastKeyUpTime",0),s(this,"flightTimes",[]),s(this,"dwellTimes",[]),s(this,"suspiciousFocusCount",0),s(this,"suspiciousFocusResetTimer",null),this.transmitter=t,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(t=>{document.addEventListener(t,t=>{this.lastInteractionTime=Date.now(),this.lastInteractionType=t.type},{passive:!0,capture:!0})}),document.addEventListener("focus",t=>{const e=t.target;"INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName||(this.checkFocusIntegrity(),this.flightTimes=[],this.dwellTimes=[],this.lastKeyUpTime=0)},{capture:!0}),document.addEventListener("keydown",t=>{const e=t.target;if("INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName)return;const s=Date.now();if(this.keyPressTimes.set(t.code,s),this.lastKeyUpTime>0){const t=s-this.lastKeyUpTime;t<2e3&&this.flightTimes.push(t)}},{passive:!0,capture:!0}),document.addEventListener("keyup",t=>{const e=t.target;if("INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName)return;const s=Date.now();this.lastKeyUpTime=s;const i=this.keyPressTimes.get(t.code);if(i){const e=s-i;this.dwellTimes.push(e),this.keyPressTimes.delete(t.code)}this.flightTimes.length>=10&&this.reportKeystrokeDynamics(e)},{passive:!0,capture:!0}),document.addEventListener("blur",t=>{const e=t.target;("INPUT"===e.tagName||"TEXTAREA"===e.tagName)&&this.flightTimes.length>0&&this.reportKeystrokeDynamics(e)},{capture:!0})}checkFocusIntegrity(){const t=Date.now(),e=t-this.lastInteractionTime;performance.now()<2e3||(e>200?(this.suspiciousFocusCount++,clearTimeout(this.suspiciousFocusResetTimer),this.suspiciousFocusResetTimer=setTimeout(()=>{this.suspiciousFocusCount=0},3e3),this.transmitter.send("behavior_metrics",{type:"suspicious_focus",timeSinceInteraction:e,lastInteraction:this.lastInteractionType,consecutiveCount:this.suspiciousFocusCount,timestamp:t}),this.suspiciousFocusCount>=3&&(this.transmitter.send("integrity_violation",{type:"programmatic_focus",details:`${this.suspiciousFocusCount} consecutive input focuses without click/tab`,consecutiveCount:this.suspiciousFocusCount,timestamp:t}),this.suspiciousFocusCount=0)):this.suspiciousFocusCount=0)}reportKeystrokeDynamics(t){const e=this.average(this.flightTimes),s=this.variance(this.flightTimes,e),i=this.average(this.dwellTimes),n=this.variance(this.dwellTimes,i);this.transmitter.send("input_metrics",{element:t.id||t.tagName,flight:{avg:e,variance:s,samples:this.flightTimes.length},dwell:{avg:i,variance:n},isMobile:this.isMobile,timestamp:Date.now()}),this.flightTimes=[],this.dwellTimes=[]}average(t){return 0===t.length?0:t.reduce((t,e)=>t+e,0)/t.length}variance(t,e){return 0===t.length?0:t.reduce((t,s)=>t+Math.pow(s-e,2),0)/t.length}}class y{constructor(){s(this,"wasmModule",null),s(this,"memory",null),s(this,"instance",null)}async load(t){try{const e=await fetch(`${t}/sdk/core.wasm`);if(!e.ok)throw new Error(`HTTP ${e.status}`);const s={env:{abort:()=>{}}};if(WebAssembly.instantiateStreaming){const t=await WebAssembly.instantiateStreaming(e,s);this.instance=t.instance}else{const t=await e.arrayBuffer(),i=await WebAssembly.instantiate(t,s);this.instance=i.instance}this.wasmModule=this.instance.exports,this.memory=this.wasmModule.memory}catch(e){}}isLoaded(){return!!this.instance}calculateEntropy(t){if(!this.instance||!this.wasmModule)return 0;const e=2*t.length,s=8*e;try{const i=this.wasmModule.__new(s,0),n=new Float64Array(this.memory.buffer,i,e);for(let e=0;e<t.length;e++)n[2*e]=t[e].x,n[2*e+1]=t[e].y;return this.wasmModule.calculateEntropy(i,e)}catch(i){return 0}}simpleHash(t){if(!this.instance||!this.wasmModule)return 0;try{const e=(new TextEncoder).encode(t),s=e.length,i=this.wasmModule.__new(s,0);return new Uint8Array(this.memory.buffer,i,s).set(e),this.wasmModule.simpleHash(i,s)}catch(e){return 0}}}class p{constructor(t,e){s(this,"transmitter"),s(this,"wasmService"),s(this,"hasRun",!1),this.transmitter=t,this.wasmService=e}start(){this.hasRun||"undefined"==typeof document||setTimeout(()=>{const t=this.generateFingerprint();this.transmitter.send("fingerprint_collected",{hash:t}),this.hasRun=!0},500)}generateFingerprint(){try{const t=document.createElement("canvas"),e=t.getContext("2d");if(!e)return"unknown";e.textBaseline="top",e.font='14px "Arial"',e.textBaseline="alphabetic",e.fillStyle="#f60",e.fillRect(125,1,62,20),e.fillStyle="#069",e.fillText("aientrophy Security 😃",2,15),e.fillStyle="rgba(102, 204, 0, 0.7)",e.fillText("aientrophy Security 😃",4,17),e.globalCompositeOperation="multiply",e.fillStyle="rgb(255,0,255)",e.beginPath(),e.arc(50,50,50,0,2*Math.PI,!0),e.closePath(),e.fill(),e.fillStyle="rgb(0,255,255)",e.beginPath(),e.arc(100,50,50,0,2*Math.PI,!0),e.closePath(),e.fill(),e.fillStyle="rgb(255,255,0)",e.beginPath(),e.arc(75,100,50,0,2*Math.PI,!0),e.closePath(),e.fill();const s=t.toDataURL(),i=this.wasmService.simpleHash(s);return Math.abs(i).toString(16)}catch(t){return"error"}}}class f{constructor(t){s(this,"originalFetch"),s(this,"endpoint"),s(this,"callbackManager",null),this.endpoint=t,this.originalFetch=window.fetch.bind(window)}setCallbackManager(t){this.callbackManager=t}start(){window.fetch=async(t,e)=>{var s;const i=await this.originalFetch(t,e);if(403===i.status){const a=i.clone();try{const n=await a.json();if("challenge"===n.action&&"captcha"===(null==(s=n.metadata)?void 0:s.type)){const s={action:"challenge",score:n.score,metadata:n.metadata};if(this.callbackManager){if(await this.callbackManager.emitChallenge(s))return this.originalFetch(t,e)}return await this.showCaptchaModal()?this.originalFetch(t,e):i}"block"===n.action&&this.callbackManager&&this.callbackManager.emit("block",{action:"block",score:n.score,metadata:n.metadata})}catch(n){}}return i}}async showCaptchaModal(){return new Promise(t=>{const e=document.createElement("div");e.id="sec-sdk-challenge-host",e.style.position="fixed",e.style.top="0",e.style.left="0",e.style.width="100vw",e.style.height="100vh",e.style.zIndex="999999",e.style.backgroundColor="rgba(0,0,0,0.5)",e.style.display="flex",e.style.justifyContent="center",e.style.alignItems="center";const s=e.attachShadow({mode:"open"}),i=document.createElement("div");i.style.background="white",i.style.padding="20px",i.style.borderRadius="8px",i.style.boxShadow="0 4px 12px rgba(0,0,0,0.2)",i.style.textAlign="center",i.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 l=document.createElement("button");l.textContent="Verify",l.style.padding="8px 16px",l.style.background="#007bff",l.style.color="white",l.style.border="none",l.style.borderRadius="4px",l.style.cursor="pointer";const c=document.createElement("p");c.style.color="red",c.style.fontSize="12px",c.style.display="none",i.appendChild(n),i.appendChild(a),i.appendChild(r),i.appendChild(o),i.appendChild(l),i.appendChild(c),s.appendChild(i),document.body.appendChild(e);let h="";const d=async()=>{try{const t=await this.originalFetch(`${this.endpoint}/challenge`),e=await t.json();h=e.id,r.innerHTML=e.svg}catch(t){r.textContent="Error loading CAPTCHA"}},u=async()=>{c.style.display="none",l.textContent="Verifying...";try{const s=o.value,i=await this.originalFetch(`${this.endpoint}/challenge/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:h,answer:s})});(await i.json()).success?(document.body.removeChild(e),t(!0)):(c.textContent="Incorrect, try again.",c.style.display="block",l.textContent="Verify",o.value="",d())}catch(s){c.textContent="System error.",c.style.display="block",l.textContent="Verify"}};l.onclick=u,o.onkeydown=t=>{"Enter"===t.key&&u()},d()})}}class g{constructor(t){s(this,"transmitter"),s(this,"eventsToWatch",["click","mousedown","keydown","touchstart","focus"]),s(this,"handleEvent",t=>{const e=t.target;if(!(e&&e instanceof HTMLElement))return;if(e===document.body||e===document.documentElement)return;const s=this.checkVisibility(e,t);if(s){const i=e.getBoundingClientRect();this.transmitter.send("invisible_interaction",{type:t.type,target:e.tagName,id:e.id,reason:s,timestamp:Date.now(),isTrusted:t.isTrusted,coordinates:{x:t instanceof MouseEvent?t.clientX:0,y:t instanceof MouseEvent?t.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:i.top,left:i.left,width:i.width,height:i.height}})}}),this.transmitter=t}start(){this.eventsToWatch.forEach(t=>{document.addEventListener(t,this.handleEvent,{capture:!0,passive:!0})})}stop(){this.eventsToWatch.forEach(t=>{document.removeEventListener(t,this.handleEvent,{capture:!0})})}checkVisibility(t,e){var s,i;const n=window.getComputedStyle(t);if("none"===n.display)return"display:none";if("hidden"===n.visibility)return"visibility:hidden";if("0"===n.opacity)return"opacity:0";const a=t.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(e instanceof MouseEvent||e instanceof TouchEvent){let n,a;if(e instanceof MouseEvent?(n=e.clientX,a=e.clientY):(n=(null==(s=e.touches[0])?void 0:s.clientX)||0,a=(null==(i=e.touches[0])?void 0:i.clientY)||0),n>=0&&n<=window.innerWidth&&a>=0&&a<=window.innerHeight){const s=document.elementFromPoint(n,a);if(s&&s!==t&&!t.contains(s)&&!s.contains(t)&&0===n&&0===a&&e.isTrusted)return null}}return null}}const w=new class{constructor(){s(this,"transmitter"),s(this,"collector"),s(this,"behaviorCollector"),s(this,"rapidClickDetector"),s(this,"honeypot"),s(this,"mouseTracker"),s(this,"canvasFingerprinter"),s(this,"inputTracker"),s(this,"challengeHandler"),s(this,"invisibleInteraction"),s(this,"initialized",!1),s(this,"wasmService"),s(this,"callbackManager"),this.transmitter=new o,this.wasmService=new y,this.callbackManager=new r,this.transmitter.setCallbackManager(this.callbackManager),this.collector=new l(this.transmitter),this.behaviorCollector=new c(this.transmitter),this.rapidClickDetector=new h(this.transmitter),this.honeypot=new d(this.transmitter),this.mouseTracker=new u(this.transmitter,this.wasmService),this.canvasFingerprinter=new p(this.transmitter,this.wasmService),this.inputTracker=new m(this.transmitter),this.invisibleInteraction=new g(this.transmitter)}async init(t){var e,s;if(this.initialized)return;t.callbacks&&this.callbackManager.setConfigCallbacks(t.callbacks);const i=t.endpoint.replace(/\/events$/,"");try{await this.wasmService.load(i),this.startDetectors(),this.transmitter.setConfig(t),this.challengeHandler=new f(i),this.challengeHandler.setCallbackManager(this.callbackManager),!1!==(null==(e=t.serverConfig)?void 0:e.captchaEnabled)&&this.challengeHandler.start();((null==(s=t.serverConfig)?void 0:s.devtoolsDetection)??!t.debug)&&Promise.resolve().then(()=>k).then(({AntiDebug:t})=>{t.start(),Promise.resolve().then(()=>T).then(({ConsoleDetector:t})=>{new t(()=>{this.transmitter.send("devtools_open",{detected:!0})}).start()})}),this.initialized=!0,t.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(t,e){this.callbackManager.on(t,e)}off(t,e){this.callbackManager.off(t,e)}once(t,e){this.callbackManager.once(t,e)}startDetectors(){this.collector.start(),this.behaviorCollector.start(),this.honeypot.start(),this.mouseTracker.start(),this.canvasFingerprinter.start(),this.inputTracker.start(),this.invisibleInteraction.start()}};"undefined"!=typeof window&&(window.SecuritySDK=w);const v={};class b{static start(){this.saveConsole(),this.disableConsole(),this.preventDevTools()}static stop(){this.intervalId&&clearInterval(this.intervalId)}static getOriginalConsole(){return v}static saveConsole(){const t=["log","debug","info","warn","error","table","trace","dir","clear"];try{const e=window.console;if(!e)return;for(const s of t)"function"==typeof e[s]&&(v[s]=e[s].bind(e))}catch(e){}}static preventDevTools(){this.intervalId=setInterval(()=>{this.debuggerCheck()},this.checkInterval)}static debuggerCheck(){!function(){try{(function(){}).constructor("debugger")()}catch(t){}}()}static disableConsole(){const t=()=>{},e=["log","debug","info","warn","error","table","trace","dir"];try{const s=window.console;if(!s)return;for(const i of e)s[i]&&(s[i]=t)}catch(s){}}}s(b,"checkInterval",1e3),s(b,"intervalId");const k=Object.freeze(Object.defineProperty({__proto__:null,AntiDebug:b},Symbol.toStringTag,{value:"Module"}));const T=Object.freeze(Object.defineProperty({__proto__:null,ConsoleDetector:class{constructor(t){s(this,"onDetect"),s(this,"intervals",[]),s(this,"detected",!1),this.onDetect=t}start(){this.startGetterTrap(),this.startSizeDetection()}stop(){for(const t of this.intervals)clearInterval(t);this.intervals=[]}triggerDetect(){this.detected||(this.detected=!0,this.onDetect(),setTimeout(()=>{this.detected=!1},5e3))}startGetterTrap(){const t=b.getOriginalConsole(),e=t.log,s=t.clear;if(!e)return;const i=document.createElement("div");Object.defineProperty(i,"id",{get:()=>(this.triggerDetect(),"")});const n=/./;n.toString=()=>(this.triggerDetect(),"");const a=setInterval(()=>{try{e(i),e(n),s&&s()}catch(t){}},1500);this.intervals.push(a)}startSizeDetection(){const t=setInterval(()=>{const t=window.outerWidth-window.innerWidth>160,e=window.outerHeight-window.innerHeight>160;(t||e)&&this.triggerDetect()},2e3);this.intervals.push(t)}}},Symbol.toStringTag,{value:"Module"}));t.securitySDK=w,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
1
+ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).SecuritySDKCore={})}(this,function(t){"use strict";var e=Object.defineProperty,i=(t,i,s)=>((t,i,s)=>i in t?e(t,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[i]=s)(t,"symbol"!=typeof i?i+"":i,s);const s="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqbBCvDqyUtfhgI/Lo5pDtn1phwA6qczAyp8N1ZgQ68OTxgbJUGiXV6N67p15bBdME1R4va51P2Czq2IbRby/N+GHTciTaXvmusV8IjnIOGtKlGxWCuKIPrCS+rGjGA2j1irxBbNpqItltFxjhxBGOzsyQAF6LNIz5IKA7sC6cSH8zUyLuFrV96udc801Zc4nCJG64ZljNbDvlVbJJZ6ex5OLLS6AnrVAXpjEDR/MI/I8JvAPe/psHj6EpXgvKrBYMBOH3jzQRzMFoR79jXyGNgPjdy0A+f6RVuEG8H5sUXKeyy+cFvaT+pm6h+t6RPED11tCOwQxYZ2pExhhPxDGeQIDAQAB";class n{static async init(){if(this.sessionKey)return;this.sessionKey=await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]);const t=await this.importPublicKey(s),e=await window.crypto.subtle.exportKey("raw",this.sessionKey),i=await window.crypto.subtle.encrypt({name:"RSA-OAEP"},t,e);this.encryptedSessionKey=this.arrayBufferToBase64(i)}static async encrypt(t){this.sessionKey||await this.init();const e=JSON.stringify(t),i=(new TextEncoder).encode(e),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);return{ek:this.encryptedSessionKey,d:this.arrayBufferToBase64(r.buffer),iv:this.arrayBufferToBase64(s.buffer),tag:this.arrayBufferToBase64(o.buffer)}}static async decrypt(t){if(!this.sessionKey)throw new Error("Session key not initialized");const e=this.base64ToArrayBuffer(t.d),i=this.base64ToArrayBuffer(t.iv),s=this.base64ToArrayBuffer(t.tag),n=new Uint8Array(e.byteLength+s.byteLength);n.set(new Uint8Array(e),0),n.set(new Uint8Array(s),e.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 async importPublicKey(t){const e=window.atob(t),i=this.str2ab(e);return await window.crypto.subtle.importKey("spki",i,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"])}static str2ab(t){const e=new ArrayBuffer(t.length),i=new Uint8Array(e);for(let s=0,n=t.length;s<n;s++)i[s]=t.charCodeAt(s);return e}static arrayBufferToBase64(t){let e="";const i=new Uint8Array(t),s=i.byteLength;for(let n=0;n<s;n++)e+=String.fromCharCode(i[n]);return window.btoa(e)}static base64ToArrayBuffer(t){const e=window.atob(t),i=e.length,s=new Uint8Array(i);for(let n=0;n<i;n++)s[n]=e.charCodeAt(n);return s.buffer}}i(n,"sessionKey",null),i(n,"encryptedSessionKey",null);const a=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"]);class r{constructor(){i(this,"handlers",new Map),i(this,"configCallbacks",{})}setConfigCallbacks(t){this.configCallbacks=t}on(t,e){this.addHandler(t,e,!1)}once(t,e){this.addHandler(t,e,!0)}off(t,e){const i=this.handlers.get(t);if(!i)return;const s=i.filter(t=>t.handler!==e);0===s.length?this.handlers.delete(t):this.handlers.set(t,s)}emit(t,...e){this.callHandlers(t,e);const i=t.indexOf(":");if(-1!==i){const s=t.substring(0,i);this.callHandlers(s,e)}this.callConfigCallback(t,e)}emitChallenge(t){return new Promise(e=>{let i=!1;const s=t=>{i||(i=!0,e(t))},n=this.handlers.has("challenge")&&this.handlers.get("challenge").length>0,a=!!this.configCallbacks.onChallenge;n||a?(this.callHandlers("challenge",[t,s]),this.configCallbacks.onChallenge&&this.safeCall(this.configCallbacks.onChallenge,[t,s]),setTimeout(()=>{i||(i=!0,e(!1))},5e3)):e(!1)})}addHandler(t,e,i){this.handlers.has(t)||this.handlers.set(t,[]),this.handlers.get(t).push({handler:e,once:i})}callHandlers(t,e){const i=this.handlers.get(t);if(!i||0===i.length)return;const s=[];for(let n=0;n<i.length;n++)this.safeCall(i[n].handler,e),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(t)}callConfigCallback(t,e){if(t.startsWith("threat:")||"threat"===t)return void(t.startsWith("threat:")&&this.configCallbacks.onThreatDetected&&this.safeCall(this.configCallbacks.onThreatDetected,e));const i={ready:"onReady",error:"onError",block:"onBlock",allow:"onAllow"}[t];i&&this.configCallbacks[i]&&this.safeCall(this.configCallbacks[i],e)}safeCall(t,e){try{t(...e)}catch(i){}}}class o{constructor(){i(this,"endpoint",""),i(this,"clientKey",""),i(this,"encryptionRequired",!1),i(this,"currentNonce",""),i(this,"buffer",[]),i(this,"batchSize",10),i(this,"flushInterval",3e3),i(this,"intervalId"),i(this,"responseHandler",null),i(this,"callbackManager",null),i(this,"flushing",!1),i(this,"pendingFlush",!1),this.startFlushInterval()}setConfig(t){var e,i;this.endpoint=t.endpoint,this.clientKey=t.clientKey,this.encryptionRequired=(null==(e=t.serverConfig)?void 0:e.encryptionRequired)??!1,this.currentNonce=(null==(i=t.serverConfig)?void 0:i.initialNonce)??""}setResponseHandler(t){this.responseHandler=t}setCallbackManager(t){this.callbackManager=t}send(t,e={}){const i=Date.now();if(this.buffer.push({type:t,data:e,timestamp:i}),this.callbackManager)if(a.has(t)){const s={type:t,data:e,timestamp:i};this.callbackManager.emit(`threat:${t}`,s)}else this.callbackManager.emit(`data:${t}`,{type:t,data:e,timestamp:i});this.buffer.length>=this.batchSize&&this.flush()}async flush(){if(0===this.buffer.length||!this.endpoint)return;if(this.flushing)return void(this.pendingFlush=!0);this.flushing=!0;const t=this.buffer;this.buffer=[];try{let s;if(this.encryptionRequired){const e=await n.encrypt(t);s=JSON.stringify(e)}else s=JSON.stringify(t);const a={"Content-Type":"application/json","x-client-key":this.clientKey};this.currentNonce&&(a["x-request-nonce"]=this.currentNonce,this.currentNonce="");try{const t=await fetch(this.endpoint,{method:"POST",body:s,headers:a,keepalive:!0});if(t.ok&&this.callbackManager&&this.callbackManager.emit("allow",{action:"allow"}),t.ok)try{const e=await t.json();let i=e;this.encryptionRequired&&(i=await n.decrypt(e)),(null==i?void 0:i.nonce)&&(this.currentNonce=i.nonce),this.responseHandler&&this.responseHandler(i)}catch(e){}}catch(i){this.callbackManager&&this.callbackManager.emit("error",{code:"NETWORK_ERROR",message:"Failed to send security events"})}}catch(e){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 l{constructor(t){i(this,"transmitter"),i(this,"listeners",{}),this.transmitter=t}start(){this.attachListeners()}stop(){this.detachListeners()}attachListeners(){this.listeners.mousemove=this.throttle(t=>{const e=t;this.transmitter.send("mousemove",{x:e.clientX,y:e.clientY,timestamp:Date.now()})},100),this.listeners.click=t=>{const e=t;this.transmitter.send("click",{x:e.clientX,y:e.clientY,target:e.target.tagName,timestamp:Date.now()})},this.listeners.keydown=t=>{const e=t;this.transmitter.send("keydown",{key:e.key,timestamp:Date.now()})},window.addEventListener("mousemove",this.listeners.mousemove),window.addEventListener("click",this.listeners.click),window.addEventListener("keydown",this.listeners.keydown)}detachListeners(){this.listeners.mousemove&&window.removeEventListener("mousemove",this.listeners.mousemove),this.listeners.click&&window.removeEventListener("click",this.listeners.click),this.listeners.keydown&&window.removeEventListener("keydown",this.listeners.keydown)}throttle(t,e){let i;return function(...s){i||(t.apply(this,s),i=!0,setTimeout(()=>i=!1,e))}}}class c{constructor(t){i(this,"transmitter"),i(this,"trajectoryBuffer",[]),i(this,"keystrokeBuffer",[]),i(this,"isCollecting",!1),i(this,"flushInterval",3e3),i(this,"flushTimer"),i(this,"lastMouseMoveTime",0),i(this,"onMouseMove",t=>{const e=Date.now();e-this.lastMouseMoveTime>50&&(this.trajectoryBuffer.push({x:t.clientX,y:t.clientY,t:e}),this.lastMouseMoveTime=e)}),i(this,"onKeyDown",t=>{this.keystrokeBuffer.push({code:t.code,t:Date.now(),type:"down"})}),i(this,"onKeyUp",t=>{this.keystrokeBuffer.push({code:t.code,t:Date.now(),type:"up"})}),this.transmitter=t}start(){this.isCollecting||(this.isCollecting=!0,this.attachListeners(),this.startFlushTimer())}stop(){this.isCollecting=!1,this.detachListeners(),this.stopFlushTimer(),this.flush()}attachListeners(){window.addEventListener("mousemove",this.onMouseMove),window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp)}detachListeners(){window.removeEventListener("mousemove",this.onMouseMove),window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp)}startFlushTimer(){this.flushTimer=setInterval(()=>{this.flush()},this.flushInterval)}stopFlushTimer(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}flush(){if(0===this.trajectoryBuffer.length&&0===this.keystrokeBuffer.length)return;const t={trajectory:[...this.trajectoryBuffer],keystrokes:[...this.keystrokeBuffer],url:window.location.href};this.trajectoryBuffer=[],this.keystrokeBuffer=[],this.transmitter.send("behavior_data",t)}}class h{constructor(t){i(this,"transmitter"),i(this,"clickHistory",[]),i(this,"THRESHOLD_COUNT",3),i(this,"THRESHOLD_TIME",500),this.transmitter=t,this.init()}init(){document.addEventListener("click",t=>this.handleClick(t),!0)}handleClick(t){const e=Date.now();if(this.clickHistory.push(e),this.clickHistory=this.clickHistory.filter(t=>e-t<=this.THRESHOLD_TIME),this.clickHistory.length>=this.THRESHOLD_COUNT){const i=t.target,s={tagName:i.tagName,id:i.id,className:i.className,x:t.clientX,y:t.clientY};this.transmitter.send("rapid_click",{count:this.clickHistory.length,duration:this.THRESHOLD_TIME,target:s,timestamp:e}),this.clickHistory=[]}}}class d{constructor(t){i(this,"transmitter"),i(this,"element",null),this.transmitter=t}start(){this.element=document.createElement("input"),this.element.type="text";const t=["website","email_confirm","url","homepage","fax_number","address_line_2"],e=t[Math.floor(Math.random()*t.length)],i=Math.random().toString(36).substr(2,5);this.element.id="hp-"+Math.random().toString(36).substr(2,9),this.element.name=`${e}-${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=t=>{var e;this.transmitter.send("honeypot_triggered",{eventType:t.type,value:null==(e=this.element)?void 0:e.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 u{constructor(t,e){i(this,"transmitter"),i(this,"wasmService"),i(this,"buffer",[]),i(this,"BUFFER_SIZE",10),i(this,"SAMPLE_INTERVAL",50),i(this,"lastSampleTime",0),i(this,"handleMouseMove",t=>{const e=Date.now();e-this.lastSampleTime<this.SAMPLE_INTERVAL||(this.lastSampleTime=e,this.buffer.push({x:t.clientX,y:t.clientY,time:e}),this.buffer.length>this.BUFFER_SIZE&&(this.buffer.shift(),this.analyze()))}),this.transmitter=t,this.wasmService=e}start(){"undefined"!=typeof document&&document.addEventListener("mousemove",this.handleMouseMove)}stop(){"undefined"!=typeof document&&document.removeEventListener("mousemove",this.handleMouseMove)}analyze(){if(this.buffer.length<5)return;const t=this.wasmService.calculateEntropy(this.buffer),e=this.calculateSpeedVariance();this.transmitter.send("behavior_metrics",{entropy:t,speedVariance:e,timestamp:Date.now()}),this.buffer=[]}calculateSpeedVariance(){const t=[];for(let i=1;i<this.buffer.length;i++){const e=this.buffer[i-1],s=this.buffer[i],n=Math.sqrt(Math.pow(s.x-e.x,2)+Math.pow(s.y-e.y,2)),a=s.time-e.time;a>0&&t.push(n/a)}if(t.length<2)return 1;const e=t.reduce((t,e)=>t+e,0)/t.length;return t.reduce((t,i)=>t+Math.pow(i-e,2),0)/t.length}}class m{constructor(t){i(this,"lastInteractionTime",0),i(this,"lastInteractionType","none"),i(this,"transmitter"),i(this,"isMobile",!1),i(this,"keyPressTimes",new Map),i(this,"lastKeyUpTime",0),i(this,"flightTimes",[]),i(this,"dwellTimes",[]),i(this,"suspiciousFocusCount",0),i(this,"suspiciousFocusResetTimer",null),this.transmitter=t,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(t=>{document.addEventListener(t,t=>{this.lastInteractionTime=Date.now(),this.lastInteractionType=t.type},{passive:!0,capture:!0})}),document.addEventListener("focus",t=>{const e=t.target;"INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName||(this.checkFocusIntegrity(),this.flightTimes=[],this.dwellTimes=[],this.lastKeyUpTime=0)},{capture:!0}),document.addEventListener("keydown",t=>{const e=t.target;if("INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName)return;const i=Date.now();if(this.keyPressTimes.set(t.code,i),this.lastKeyUpTime>0){const t=i-this.lastKeyUpTime;t<2e3&&this.flightTimes.push(t)}},{passive:!0,capture:!0}),document.addEventListener("keyup",t=>{const e=t.target;if("INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName)return;const i=Date.now();this.lastKeyUpTime=i;const s=this.keyPressTimes.get(t.code);if(s){const e=i-s;this.dwellTimes.push(e),this.keyPressTimes.delete(t.code)}this.flightTimes.length>=10&&this.reportKeystrokeDynamics(e)},{passive:!0,capture:!0}),document.addEventListener("blur",t=>{const e=t.target;("INPUT"===e.tagName||"TEXTAREA"===e.tagName)&&this.flightTimes.length>0&&this.reportKeystrokeDynamics(e)},{capture:!0})}checkFocusIntegrity(){const t=Date.now(),e=t-this.lastInteractionTime;performance.now()<2e3||(e>200?(this.suspiciousFocusCount++,clearTimeout(this.suspiciousFocusResetTimer),this.suspiciousFocusResetTimer=setTimeout(()=>{this.suspiciousFocusCount=0},3e3),this.transmitter.send("behavior_metrics",{type:"suspicious_focus",timeSinceInteraction:e,lastInteraction:this.lastInteractionType,consecutiveCount:this.suspiciousFocusCount,timestamp:t}),this.suspiciousFocusCount>=3&&(this.transmitter.send("integrity_violation",{type:"programmatic_focus",details:`${this.suspiciousFocusCount} consecutive input focuses without click/tab`,consecutiveCount:this.suspiciousFocusCount,timestamp:t}),this.suspiciousFocusCount=0)):this.suspiciousFocusCount=0)}reportKeystrokeDynamics(t){const e=this.average(this.flightTimes),i=this.variance(this.flightTimes,e),s=this.average(this.dwellTimes),n=this.variance(this.dwellTimes,s);this.transmitter.send("input_metrics",{element:t.id||t.tagName,flight:{avg:e,variance:i,samples:this.flightTimes.length},dwell:{avg:s,variance:n},isMobile:this.isMobile,timestamp:Date.now()}),this.flightTimes=[],this.dwellTimes=[]}average(t){return 0===t.length?0:t.reduce((t,e)=>t+e,0)/t.length}variance(t,e){return 0===t.length?0:t.reduce((t,i)=>t+Math.pow(i-e,2),0)/t.length}}class y{constructor(){i(this,"wasmModule",null),i(this,"memory",null),i(this,"instance",null)}async load(t){try{const e=await fetch(`${t}/sdk/core.wasm`);if(!e.ok)throw new Error(`HTTP ${e.status}`);const i={env:{abort:()=>{}}};if(WebAssembly.instantiateStreaming){const t=await WebAssembly.instantiateStreaming(e,i);this.instance=t.instance}else{const t=await e.arrayBuffer(),s=await WebAssembly.instantiate(t,i);this.instance=s.instance}this.wasmModule=this.instance.exports,this.memory=this.wasmModule.memory}catch(e){}}isLoaded(){return!!this.instance}calculateEntropy(t){if(!this.instance||!this.wasmModule)return 0;const e=2*t.length,i=8*e;try{const s=this.wasmModule.__new(i,0),n=new Float64Array(this.memory.buffer,s,e);for(let e=0;e<t.length;e++)n[2*e]=t[e].x,n[2*e+1]=t[e].y;return this.wasmModule.calculateEntropy(s,e)}catch(s){return 0}}simpleHash(t){if(!this.instance||!this.wasmModule)return 0;try{const e=(new TextEncoder).encode(t),i=e.length,s=this.wasmModule.__new(i,0);return new Uint8Array(this.memory.buffer,s,i).set(e),this.wasmModule.simpleHash(s,i)}catch(e){return 0}}}class f{constructor(t,e){i(this,"transmitter"),i(this,"wasmService"),i(this,"hasRun",!1),this.transmitter=t,this.wasmService=e}start(){this.hasRun||"undefined"==typeof document||setTimeout(()=>{const t=this.generateFingerprint();this.transmitter.send("fingerprint_collected",{hash:t}),this.hasRun=!0},500)}generateFingerprint(){try{const t=document.createElement("canvas"),e=t.getContext("2d");if(!e)return"unknown";e.textBaseline="top",e.font='14px "Arial"',e.textBaseline="alphabetic",e.fillStyle="#f60",e.fillRect(125,1,62,20),e.fillStyle="#069",e.fillText("aientrophy Security 😃",2,15),e.fillStyle="rgba(102, 204, 0, 0.7)",e.fillText("aientrophy Security 😃",4,17),e.globalCompositeOperation="multiply",e.fillStyle="rgb(255,0,255)",e.beginPath(),e.arc(50,50,50,0,2*Math.PI,!0),e.closePath(),e.fill(),e.fillStyle="rgb(0,255,255)",e.beginPath(),e.arc(100,50,50,0,2*Math.PI,!0),e.closePath(),e.fill(),e.fillStyle="rgb(255,255,0)",e.beginPath(),e.arc(75,100,50,0,2*Math.PI,!0),e.closePath(),e.fill();const i=t.toDataURL(),s=this.wasmService.simpleHash(i);return Math.abs(s).toString(16)}catch(t){return"error"}}}class p{constructor(t){i(this,"originalFetch"),i(this,"endpoint"),i(this,"callbackManager",null),this.endpoint=t,this.originalFetch=window.fetch.bind(window)}setCallbackManager(t){this.callbackManager=t}start(){window.fetch=async(t,e)=>{var i;const s=await this.originalFetch(t,e);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(t,e)}return await this.showCaptchaModal()?this.originalFetch(t,e):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(t=>{const e=document.createElement("div");e.id="sec-sdk-challenge-host",e.style.position="fixed",e.style.top="0",e.style.left="0",e.style.width="100vw",e.style.height="100vh",e.style.zIndex="999999",e.style.backgroundColor="rgba(0,0,0,0.5)",e.style.display="flex",e.style.justifyContent="center",e.style.alignItems="center";const i=e.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 l=document.createElement("button");l.textContent="Verify",l.style.padding="8px 16px",l.style.background="#007bff",l.style.color="white",l.style.border="none",l.style.borderRadius="4px",l.style.cursor="pointer";const c=document.createElement("p");c.style.color="red",c.style.fontSize="12px",c.style.display="none",s.appendChild(n),s.appendChild(a),s.appendChild(r),s.appendChild(o),s.appendChild(l),s.appendChild(c),i.appendChild(s),document.body.appendChild(e);let h="";const d=async()=>{try{const t=await this.originalFetch(`${this.endpoint}/challenge`),e=await t.json();h=e.id,r.innerHTML=e.svg}catch(t){r.textContent="Error loading CAPTCHA"}},u=async()=>{c.style.display="none",l.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(e),t(!0)):(c.textContent="Incorrect, try again.",c.style.display="block",l.textContent="Verify",o.value="",d())}catch(i){c.textContent="System error.",c.style.display="block",l.textContent="Verify"}};l.onclick=u,o.onkeydown=t=>{"Enter"===t.key&&u()},d()})}}class g{constructor(t){i(this,"transmitter"),i(this,"eventsToWatch",["click","mousedown","keydown","touchstart","focus"]),i(this,"handleEvent",t=>{const e=t.target;if(!(e&&e instanceof HTMLElement))return;if(e===document.body||e===document.documentElement)return;const i=this.checkVisibility(e,t);if(i){const s=e.getBoundingClientRect();this.transmitter.send("invisible_interaction",{type:t.type,target:e.tagName,id:e.id,reason:i,timestamp:Date.now(),isTrusted:t.isTrusted,coordinates:{x:t instanceof MouseEvent?t.clientX:0,y:t instanceof MouseEvent?t.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=t}start(){this.eventsToWatch.forEach(t=>{document.addEventListener(t,this.handleEvent,{capture:!0,passive:!0})})}stop(){this.eventsToWatch.forEach(t=>{document.removeEventListener(t,this.handleEvent,{capture:!0})})}checkVisibility(t,e){var i,s;const n=window.getComputedStyle(t);if("none"===n.display)return"display:none";if("hidden"===n.visibility)return"visibility:hidden";if("0"===n.opacity)return"opacity:0";const a=t.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(e instanceof MouseEvent||e instanceof TouchEvent){let n,a;if(e instanceof MouseEvent?(n=e.clientX,a=e.clientY):(n=(null==(i=e.touches[0])?void 0:i.clientX)||0,a=(null==(s=e.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!==t&&!t.contains(i)&&!i.contains(t)&&0===n&&0===a&&e.isTrusted)return null}}return null}}const w=new class{constructor(){i(this,"transmitter"),i(this,"collector"),i(this,"behaviorCollector"),i(this,"rapidClickDetector"),i(this,"honeypot"),i(this,"mouseTracker"),i(this,"canvasFingerprinter"),i(this,"inputTracker"),i(this,"challengeHandler"),i(this,"invisibleInteraction"),i(this,"initialized",!1),i(this,"wasmService"),i(this,"callbackManager"),this.transmitter=new o,this.wasmService=new y,this.callbackManager=new r,this.transmitter.setCallbackManager(this.callbackManager),this.collector=new l(this.transmitter),this.behaviorCollector=new c(this.transmitter),this.rapidClickDetector=new h(this.transmitter),this.honeypot=new d(this.transmitter),this.mouseTracker=new u(this.transmitter,this.wasmService),this.canvasFingerprinter=new f(this.transmitter,this.wasmService),this.inputTracker=new m(this.transmitter),this.invisibleInteraction=new g(this.transmitter)}async init(t){var e,i;if(this.initialized)return;t.callbacks&&this.callbackManager.setConfigCallbacks(t.callbacks);const s=t.endpoint.replace(/\/events$/,"");try{await this.wasmService.load(s),this.startDetectors(),this.transmitter.setConfig(t),this.challengeHandler=new p(s),this.challengeHandler.setCallbackManager(this.callbackManager),!1!==(null==(e=t.serverConfig)?void 0:e.captchaEnabled)&&this.challengeHandler.start();((null==(i=t.serverConfig)?void 0:i.devtoolsDetection)??!t.debug)&&Promise.resolve().then(()=>k).then(({AntiDebug:t})=>{t.start(),Promise.resolve().then(()=>T).then(({ConsoleDetector:t})=>{new t(()=>{this.transmitter.send("devtools_open",{detected:!0})}).start()})}),this.initialized=!0,t.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(t,e){this.callbackManager.on(t,e)}off(t,e){this.callbackManager.off(t,e)}once(t,e){this.callbackManager.once(t,e)}startDetectors(){this.collector.start(),this.behaviorCollector.start(),this.honeypot.start(),this.mouseTracker.start(),this.canvasFingerprinter.start(),this.inputTracker.start(),this.invisibleInteraction.start()}};"undefined"!=typeof window&&(window.SecuritySDK=w);const v={};class b{static start(){this.saveConsole(),this.disableConsole(),this.preventDevTools()}static stop(){this.intervalId&&clearInterval(this.intervalId)}static getOriginalConsole(){return v}static saveConsole(){const t=["log","debug","info","warn","error","table","trace","dir","clear"];try{const e=window.console;if(!e)return;for(const i of t)"function"==typeof e[i]&&(v[i]=e[i].bind(e))}catch(e){}}static preventDevTools(){this.intervalId=setInterval(()=>{this.debuggerCheck()},this.checkInterval)}static debuggerCheck(){!function(){try{(function(){}).constructor("debugger")()}catch(t){}}()}static disableConsole(){const t=()=>{},e=["log","debug","info","warn","error","table","trace","dir"];try{const i=window.console;if(!i)return;for(const s of e)i[s]&&(i[s]=t)}catch(i){}}}i(b,"checkInterval",1e3),i(b,"intervalId");const k=Object.freeze(Object.defineProperty({__proto__:null,AntiDebug:b},Symbol.toStringTag,{value:"Module"}));const T=Object.freeze(Object.defineProperty({__proto__:null,ConsoleDetector:class{constructor(t){i(this,"onDetect"),i(this,"intervals",[]),i(this,"detected",!1),this.onDetect=t}start(){this.startGetterTrap(),this.startSizeDetection()}stop(){for(const t of this.intervals)clearInterval(t);this.intervals=[]}triggerDetect(){this.detected||(this.detected=!0,this.onDetect(),setTimeout(()=>{this.detected=!1},5e3))}startGetterTrap(){const t=b.getOriginalConsole(),e=t.log,i=t.clear;if(!e)return;const s=document.createElement("div");Object.defineProperty(s,"id",{get:()=>(this.triggerDetect(),"")});const n=/./;n.toString=()=>(this.triggerDetect(),"");const a=setInterval(()=>{try{e(s),e(n),i&&i()}catch(t){}},1500);this.intervals.push(a)}startSizeDetection(){const t=setInterval(()=>{const t=window.outerWidth-window.innerWidth>160,e=window.outerHeight-window.innerHeight>160;(t||e)&&this.triggerDetect()},2e3);this.intervals.push(t)}}},Symbol.toStringTag,{value:"Module"}));t.securitySDK=w,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
package/dist/loader.js CHANGED
@@ -1 +1 @@
1
- !function(t){"function"==typeof define&&define.amd?define(t):t()}(function(){"use strict";!function(){const t=window.SecuritySDKConfig||{endpoint:"https://api.aientrophy.com/api/v1/events",clientKey:"",debug:!0};async function n(){try{t.debug;const n=`${t.endpoint.replace(/\/events$/,"")}/sdk/payload?clientKey=${encodeURIComponent(t.clientKey||"")}`,e=await fetch(n);if(!e.ok)throw new Error(`HTTP ${e.status}`);const{payload:o,key:i,config:c}=await e.json(),r=function(t,n){try{const e=atob(t);let o="";for(let t=0;t<e.length;t++)o+=String.fromCharCode(e.charCodeAt(t)^n.charCodeAt(t%n.length));return o}catch(e){return""}}(o,i);if(!r)throw new Error("Empty payload");new Function(r)();const a=window.SecuritySDK;if(a&&"function"==typeof a.init){if(await a.init({...t,serverConfig:c||{}}),t.on&&"object"==typeof t.on)for(const[n,e]of Object.entries(t.on))"function"==typeof e&&a.on(n,e);t.debug}}catch(n){}}"complete"===document.readyState?n():window.addEventListener("load",n)}()});
1
+ !function(n){"function"==typeof define&&define.amd?define(n):n()}(function(){"use strict";!function(){const n=window.SecuritySDKConfig||{endpoint:"https://api.aientrophy.com/api/v1/events",clientKey:"",debug:!0};async function t(){try{n.debug;const e=n.endpoint.replace(/\/events$/,""),o=`${e}/sdk/payload?clientKey=${encodeURIComponent(n.clientKey||"")}`,i=await fetch(o);if(!i.ok)throw new Error(`HTTP ${i.status}`);const{payload:c,key:a,config:r}=await i.json();if(null==r?void 0:r.nonceValidation)try{const t=await fetch(`${e}/sdk/nonce?clientKey=${encodeURIComponent(n.clientKey||"")}`);if(t.ok){const n=await t.json();n.nonce&&(r.initialNonce=n.nonce)}}catch(t){n.debug}const d=function(n,e){try{const t=atob(n);let o="";for(let n=0;n<t.length;n++)o+=String.fromCharCode(t.charCodeAt(n)^e.charCodeAt(n%e.length));return o}catch(t){return""}}(c,a);if(!d)throw new Error("Empty payload");new Function(d)();const f=window.SecuritySDK;if(f&&"function"==typeof f.init){if(await f.init({...n,serverConfig:r||{}}),n.on&&"object"==typeof n.on)for(const[t,e]of Object.entries(n.on))"function"==typeof e&&f.on(t,e);n.debug}}catch(t){}}"complete"===document.readyState?t():window.addEventListener("load",t)}()});
@@ -1 +1 @@
1
- "use strict";var __defProp=Object.defineProperty,__publicField=(t,e,i)=>((t,e,i)=>e in t?__defProp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i)(t,"symbol"!=typeof e?e+"":e,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)return;this.sessionKey=await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]);const t=await this.importPublicKey(CONFIG_RSA_PUBLIC_KEY),e=await window.crypto.subtle.exportKey("raw",this.sessionKey),i=await window.crypto.subtle.encrypt({name:"RSA-OAEP"},t,e);this.encryptedSessionKey=this.arrayBufferToBase64(i)}static async encrypt(t){this.sessionKey||await this.init();const e=JSON.stringify(t),i=(new TextEncoder).encode(e),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),l=a.slice(a.length-16);return{ek:this.encryptedSessionKey,d:this.arrayBufferToBase64(r.buffer),iv:this.arrayBufferToBase64(s.buffer),tag:this.arrayBufferToBase64(l.buffer)}}static async decrypt(t){if(!this.sessionKey)throw new Error("Session key not initialized");const e=this.base64ToArrayBuffer(t.d),i=this.base64ToArrayBuffer(t.iv),s=this.base64ToArrayBuffer(t.tag),n=new Uint8Array(e.byteLength+s.byteLength);n.set(new Uint8Array(e),0),n.set(new Uint8Array(s),e.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 async importPublicKey(t){const e=window.atob(t),i=this.str2ab(e);return await window.crypto.subtle.importKey("spki",i,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"])}static str2ab(t){const e=new ArrayBuffer(t.length),i=new Uint8Array(e);for(let s=0,n=t.length;s<n;s++)i[s]=t.charCodeAt(s);return e}static arrayBufferToBase64(t){let e="";const i=new Uint8Array(t),s=i.byteLength;for(let n=0;n<s;n++)e+=String.fromCharCode(i[n]);return window.btoa(e)}static base64ToArrayBuffer(t){const e=window.atob(t),i=e.length,s=new Uint8Array(i);for(let n=0;n<i;n++)s[n]=e.charCodeAt(n);return s.buffer}}__publicField(CryptoUtils,"sessionKey",null),__publicField(CryptoUtils,"encryptedSessionKey",null);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"]);class CallbackManager{constructor(){__publicField(this,"handlers",new Map),__publicField(this,"configCallbacks",{})}setConfigCallbacks(t){this.configCallbacks=t}on(t,e){this.addHandler(t,e,!1)}once(t,e){this.addHandler(t,e,!0)}off(t,e){const i=this.handlers.get(t);if(!i)return;const s=i.filter(t=>t.handler!==e);0===s.length?this.handlers.delete(t):this.handlers.set(t,s)}emit(t,...e){this.callHandlers(t,e);const i=t.indexOf(":");if(-1!==i){const s=t.substring(0,i);this.callHandlers(s,e)}this.callConfigCallback(t,e)}emitChallenge(t){return new Promise(e=>{let i=!1;const s=t=>{i||(i=!0,e(t))},n=this.handlers.has("challenge")&&this.handlers.get("challenge").length>0,a=!!this.configCallbacks.onChallenge;n||a?(this.callHandlers("challenge",[t,s]),this.configCallbacks.onChallenge&&this.safeCall(this.configCallbacks.onChallenge,[t,s]),setTimeout(()=>{i||(i=!0,e(!1))},5e3)):e(!1)})}addHandler(t,e,i){this.handlers.has(t)||this.handlers.set(t,[]),this.handlers.get(t).push({handler:e,once:i})}callHandlers(t,e){const i=this.handlers.get(t);if(!i||0===i.length)return;const s=[];for(let n=0;n<i.length;n++)this.safeCall(i[n].handler,e),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(t)}callConfigCallback(t,e){if(t.startsWith("threat:")||"threat"===t)return void(t.startsWith("threat:")&&this.configCallbacks.onThreatDetected&&this.safeCall(this.configCallbacks.onThreatDetected,e));const i={ready:"onReady",error:"onError",block:"onBlock",allow:"onAllow"}[t];i&&this.configCallbacks[i]&&this.safeCall(this.configCallbacks[i],e)}safeCall(t,e){try{t(...e)}catch(i){}}}class Transmitter{constructor(){__publicField(this,"endpoint",""),__publicField(this,"clientKey",""),__publicField(this,"encryptionRequired",!1),__publicField(this,"currentNonce",""),__publicField(this,"buffer",[]),__publicField(this,"batchSize",10),__publicField(this,"flushInterval",1e3),__publicField(this,"intervalId"),__publicField(this,"responseHandler",null),__publicField(this,"callbackManager",null),this.startFlushInterval()}setConfig(t){var e,i;this.endpoint=t.endpoint,this.clientKey=t.clientKey,this.encryptionRequired=(null==(e=t.serverConfig)?void 0:e.encryptionRequired)??!1,this.currentNonce=(null==(i=t.serverConfig)?void 0:i.initialNonce)??""}setResponseHandler(t){this.responseHandler=t}setCallbackManager(t){this.callbackManager=t}send(t,e={}){const i=Date.now();if(this.buffer.push({type:t,data:e,timestamp:i}),this.callbackManager)if(THREAT_EVENTS.has(t)){const s={type:t,data:e,timestamp:i};this.callbackManager.emit(`threat:${t}`,s)}else this.callbackManager.emit(`data:${t}`,{type:t,data:e,timestamp:i});this.buffer.length>=this.batchSize&&this.flush()}async flush(){if(0===this.buffer.length||!this.endpoint)return;const t=this.buffer;this.buffer=[];try{let e;if(this.encryptionRequired){const i=await CryptoUtils.encrypt(t);e=JSON.stringify(i)}else e=JSON.stringify(t);const i={"Content-Type":"application/json","x-client-key":this.clientKey};this.currentNonce&&(i["x-request-nonce"]=this.currentNonce,this.currentNonce=""),fetch(this.endpoint,{method:"POST",body:e,headers:i,keepalive:!0}).then(async t=>{if(t.ok&&this.callbackManager&&this.callbackManager.emit("allow",{action:"allow"}),t.ok)try{const e=await t.json();let i=e;this.encryptionRequired&&(i=await CryptoUtils.decrypt(e)),(null==i?void 0:i.nonce)&&(this.currentNonce=i.nonce),this.responseHandler&&this.responseHandler(i)}catch(e){}}).catch(t=>{this.callbackManager&&this.callbackManager.emit("error",{code:"NETWORK_ERROR",message:"Failed to send security events"})})}catch(e){this.callbackManager&&this.callbackManager.emit("error",{code:"PAYLOAD_ERROR",message:"Failed to prepare security payload"})}}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null),this.flush()}startFlushInterval(){this.intervalId=setInterval(()=>{this.flush()},this.flushInterval)}}class EventCollector{constructor(t){__publicField(this,"transmitter"),__publicField(this,"listeners",{}),this.transmitter=t}start(){this.attachListeners()}stop(){this.detachListeners()}attachListeners(){this.listeners.mousemove=this.throttle(t=>{const e=t;this.transmitter.send("mousemove",{x:e.clientX,y:e.clientY,timestamp:Date.now()})},100),this.listeners.click=t=>{const e=t;this.transmitter.send("click",{x:e.clientX,y:e.clientY,target:e.target.tagName,timestamp:Date.now()})},this.listeners.keydown=t=>{const e=t;this.transmitter.send("keydown",{key:e.key,timestamp:Date.now()})},window.addEventListener("mousemove",this.listeners.mousemove),window.addEventListener("click",this.listeners.click),window.addEventListener("keydown",this.listeners.keydown)}detachListeners(){this.listeners.mousemove&&window.removeEventListener("mousemove",this.listeners.mousemove),this.listeners.click&&window.removeEventListener("click",this.listeners.click),this.listeners.keydown&&window.removeEventListener("keydown",this.listeners.keydown)}throttle(t,e){let i;return function(...s){i||(t.apply(this,s),i=!0,setTimeout(()=>i=!1,e))}}}class BehaviorCollector{constructor(t){__publicField(this,"transmitter"),__publicField(this,"trajectoryBuffer",[]),__publicField(this,"keystrokeBuffer",[]),__publicField(this,"isCollecting",!1),__publicField(this,"flushInterval",3e3),__publicField(this,"flushTimer"),__publicField(this,"lastMouseMoveTime",0),__publicField(this,"onMouseMove",t=>{const e=Date.now();e-this.lastMouseMoveTime>50&&(this.trajectoryBuffer.push({x:t.clientX,y:t.clientY,t:e}),this.lastMouseMoveTime=e)}),__publicField(this,"onKeyDown",t=>{this.keystrokeBuffer.push({code:t.code,t:Date.now(),type:"down"})}),__publicField(this,"onKeyUp",t=>{this.keystrokeBuffer.push({code:t.code,t:Date.now(),type:"up"})}),this.transmitter=t}start(){this.isCollecting||(this.isCollecting=!0,this.attachListeners(),this.startFlushTimer())}stop(){this.isCollecting=!1,this.detachListeners(),this.stopFlushTimer(),this.flush()}attachListeners(){window.addEventListener("mousemove",this.onMouseMove),window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp)}detachListeners(){window.removeEventListener("mousemove",this.onMouseMove),window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp)}startFlushTimer(){this.flushTimer=setInterval(()=>{this.flush()},this.flushInterval)}stopFlushTimer(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}flush(){if(0===this.trajectoryBuffer.length&&0===this.keystrokeBuffer.length)return;const t={trajectory:[...this.trajectoryBuffer],keystrokes:[...this.keystrokeBuffer],url:window.location.href};this.trajectoryBuffer=[],this.keystrokeBuffer=[],this.transmitter.send("behavior_data",t)}}class RapidClickDetector{constructor(t){__publicField(this,"transmitter"),__publicField(this,"clickHistory",[]),__publicField(this,"THRESHOLD_COUNT",3),__publicField(this,"THRESHOLD_TIME",500),this.transmitter=t,this.init()}init(){document.addEventListener("click",t=>this.handleClick(t),!0)}handleClick(t){const e=Date.now();if(this.clickHistory.push(e),this.clickHistory=this.clickHistory.filter(t=>e-t<=this.THRESHOLD_TIME),this.clickHistory.length>=this.THRESHOLD_COUNT){const i=t.target,s={tagName:i.tagName,id:i.id,className:i.className,x:t.clientX,y:t.clientY};this.transmitter.send("rapid_click",{count:this.clickHistory.length,duration:this.THRESHOLD_TIME,target:s,timestamp:e}),this.clickHistory=[]}}}class Honeypot{constructor(t){__publicField(this,"transmitter"),__publicField(this,"element",null),this.transmitter=t}start(){this.element=document.createElement("input"),this.element.type="text";const t=["website","email_confirm","url","homepage","fax_number","address_line_2"],e=t[Math.floor(Math.random()*t.length)],i=Math.random().toString(36).substr(2,5);this.element.id="hp-"+Math.random().toString(36).substr(2,9),this.element.name=`${e}-${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=t=>{var e;this.transmitter.send("honeypot_triggered",{eventType:t.type,value:null==(e=this.element)?void 0:e.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(t,e){__publicField(this,"transmitter"),__publicField(this,"wasmService"),__publicField(this,"buffer",[]),__publicField(this,"BUFFER_SIZE",10),__publicField(this,"SAMPLE_INTERVAL",50),__publicField(this,"lastSampleTime",0),__publicField(this,"handleMouseMove",t=>{const e=Date.now();e-this.lastSampleTime<this.SAMPLE_INTERVAL||(this.lastSampleTime=e,this.buffer.push({x:t.clientX,y:t.clientY,time:e}),this.buffer.length>this.BUFFER_SIZE&&(this.buffer.shift(),this.analyze()))}),this.transmitter=t,this.wasmService=e}start(){"undefined"!=typeof document&&document.addEventListener("mousemove",this.handleMouseMove)}stop(){"undefined"!=typeof document&&document.removeEventListener("mousemove",this.handleMouseMove)}analyze(){if(this.buffer.length<5)return;const t=this.wasmService.calculateEntropy(this.buffer),e=this.calculateSpeedVariance();this.transmitter.send("behavior_metrics",{entropy:t,speedVariance:e,timestamp:Date.now()}),this.buffer=[]}calculateSpeedVariance(){const t=[];for(let i=1;i<this.buffer.length;i++){const e=this.buffer[i-1],s=this.buffer[i],n=Math.sqrt(Math.pow(s.x-e.x,2)+Math.pow(s.y-e.y,2)),a=s.time-e.time;a>0&&t.push(n/a)}if(t.length<2)return 1;const e=t.reduce((t,e)=>t+e,0)/t.length;return t.reduce((t,i)=>t+Math.pow(i-e,2),0)/t.length}}class InputTracker{constructor(t){__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),this.transmitter=t,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(t=>{document.addEventListener(t,t=>{this.lastInteractionTime=Date.now(),this.lastInteractionType=t.type},{passive:!0,capture:!0})}),document.addEventListener("focus",t=>{const e=t.target;"INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName||(this.checkFocusIntegrity(),this.flightTimes=[],this.dwellTimes=[],this.lastKeyUpTime=0)},{capture:!0}),document.addEventListener("keydown",t=>{const e=t.target;if("INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName)return;const i=Date.now();if(this.keyPressTimes.set(t.code,i),this.lastKeyUpTime>0){const t=i-this.lastKeyUpTime;t<2e3&&this.flightTimes.push(t)}},{passive:!0,capture:!0}),document.addEventListener("keyup",t=>{const e=t.target;if("INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName)return;const i=Date.now();this.lastKeyUpTime=i;const s=this.keyPressTimes.get(t.code);if(s){const e=i-s;this.dwellTimes.push(e),this.keyPressTimes.delete(t.code)}this.flightTimes.length>=10&&this.reportKeystrokeDynamics(e)},{passive:!0,capture:!0}),document.addEventListener("blur",t=>{const e=t.target;("INPUT"===e.tagName||"TEXTAREA"===e.tagName)&&this.flightTimes.length>0&&this.reportKeystrokeDynamics(e)},{capture:!0})}checkFocusIntegrity(){const t=Date.now(),e=t-this.lastInteractionTime;performance.now()<2e3||(e>200?(this.suspiciousFocusCount++,clearTimeout(this.suspiciousFocusResetTimer),this.suspiciousFocusResetTimer=setTimeout(()=>{this.suspiciousFocusCount=0},3e3),this.transmitter.send("behavior_metrics",{type:"suspicious_focus",timeSinceInteraction:e,lastInteraction:this.lastInteractionType,consecutiveCount:this.suspiciousFocusCount,timestamp:t}),this.suspiciousFocusCount>=3&&(this.transmitter.send("integrity_violation",{type:"programmatic_focus",details:`${this.suspiciousFocusCount} consecutive input focuses without click/tab`,consecutiveCount:this.suspiciousFocusCount,timestamp:t}),this.suspiciousFocusCount=0)):this.suspiciousFocusCount=0)}reportKeystrokeDynamics(t){const e=this.average(this.flightTimes),i=this.variance(this.flightTimes,e),s=this.average(this.dwellTimes),n=this.variance(this.dwellTimes,s);this.transmitter.send("input_metrics",{element:t.id||t.tagName,flight:{avg:e,variance:i,samples:this.flightTimes.length},dwell:{avg:s,variance:n},isMobile:this.isMobile,timestamp:Date.now()}),this.flightTimes=[],this.dwellTimes=[]}average(t){return 0===t.length?0:t.reduce((t,e)=>t+e,0)/t.length}variance(t,e){return 0===t.length?0:t.reduce((t,i)=>t+Math.pow(i-e,2),0)/t.length}}class WasmService{constructor(){__publicField(this,"wasmModule",null),__publicField(this,"memory",null),__publicField(this,"instance",null)}async load(t){try{const e=await fetch(`${t}/sdk/core.wasm`);if(!e.ok)throw new Error(`HTTP ${e.status}`);const i={env:{abort:()=>{}}};if(WebAssembly.instantiateStreaming){const t=await WebAssembly.instantiateStreaming(e,i);this.instance=t.instance}else{const t=await e.arrayBuffer(),s=await WebAssembly.instantiate(t,i);this.instance=s.instance}this.wasmModule=this.instance.exports,this.memory=this.wasmModule.memory}catch(e){}}isLoaded(){return!!this.instance}calculateEntropy(t){if(!this.instance||!this.wasmModule)return 0;const e=2*t.length,i=8*e;try{const s=this.wasmModule.__new(i,0),n=new Float64Array(this.memory.buffer,s,e);for(let e=0;e<t.length;e++)n[2*e]=t[e].x,n[2*e+1]=t[e].y;return this.wasmModule.calculateEntropy(s,e)}catch(s){return 0}}simpleHash(t){if(!this.instance||!this.wasmModule)return 0;try{const e=(new TextEncoder).encode(t),i=e.length,s=this.wasmModule.__new(i,0);return new Uint8Array(this.memory.buffer,s,i).set(e),this.wasmModule.simpleHash(s,i)}catch(e){return 0}}}class CanvasFingerprinter{constructor(t,e){__publicField(this,"transmitter"),__publicField(this,"wasmService"),__publicField(this,"hasRun",!1),this.transmitter=t,this.wasmService=e}start(){this.hasRun||"undefined"==typeof document||setTimeout(()=>{const t=this.generateFingerprint();this.transmitter.send("fingerprint_collected",{hash:t}),this.hasRun=!0},500)}generateFingerprint(){try{const t=document.createElement("canvas"),e=t.getContext("2d");if(!e)return"unknown";e.textBaseline="top",e.font='14px "Arial"',e.textBaseline="alphabetic",e.fillStyle="#f60",e.fillRect(125,1,62,20),e.fillStyle="#069",e.fillText("aientrophy Security 😃",2,15),e.fillStyle="rgba(102, 204, 0, 0.7)",e.fillText("aientrophy Security 😃",4,17),e.globalCompositeOperation="multiply",e.fillStyle="rgb(255,0,255)",e.beginPath(),e.arc(50,50,50,0,2*Math.PI,!0),e.closePath(),e.fill(),e.fillStyle="rgb(0,255,255)",e.beginPath(),e.arc(100,50,50,0,2*Math.PI,!0),e.closePath(),e.fill(),e.fillStyle="rgb(255,255,0)",e.beginPath(),e.arc(75,100,50,0,2*Math.PI,!0),e.closePath(),e.fill();const i=t.toDataURL(),s=this.wasmService.simpleHash(i);return Math.abs(s).toString(16)}catch(t){return"error"}}}class ChallengeHandler{constructor(t){__publicField(this,"originalFetch"),__publicField(this,"endpoint"),__publicField(this,"callbackManager",null),this.endpoint=t,this.originalFetch=window.fetch.bind(window)}setCallbackManager(t){this.callbackManager=t}start(){window.fetch=async(t,e)=>{var i;const s=await this.originalFetch(t,e);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(t,e)}return await this.showCaptchaModal()?this.originalFetch(t,e):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(t=>{const e=document.createElement("div");e.id="sec-sdk-challenge-host",e.style.position="fixed",e.style.top="0",e.style.left="0",e.style.width="100vw",e.style.height="100vh",e.style.zIndex="999999",e.style.backgroundColor="rgba(0,0,0,0.5)",e.style.display="flex",e.style.justifyContent="center",e.style.alignItems="center";const i=e.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 l=document.createElement("input");l.type="text",l.placeholder="Enter details",l.style.padding="8px",l.style.marginRight="8px",l.style.border="1px solid #ddd",l.style.borderRadius="4px";const o=document.createElement("button");o.textContent="Verify",o.style.padding="8px 16px",o.style.background="#007bff",o.style.color="white",o.style.border="none",o.style.borderRadius="4px",o.style.cursor="pointer";const c=document.createElement("p");c.style.color="red",c.style.fontSize="12px",c.style.display="none",s.appendChild(n),s.appendChild(a),s.appendChild(r),s.appendChild(l),s.appendChild(o),s.appendChild(c),i.appendChild(s),document.body.appendChild(e);let h="";const d=async()=>{try{const t=await this.originalFetch(`${this.endpoint}/challenge`),e=await t.json();h=e.id,r.innerHTML=e.svg}catch(t){r.textContent="Error loading CAPTCHA"}},u=async()=>{c.style.display="none",o.textContent="Verifying...";try{const i=l.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(e),t(!0)):(c.textContent="Incorrect, try again.",c.style.display="block",o.textContent="Verify",l.value="",d())}catch(i){c.textContent="System error.",c.style.display="block",o.textContent="Verify"}};o.onclick=u,l.onkeydown=t=>{"Enter"===t.key&&u()},d()})}}class InvisibleInteraction{constructor(t){__publicField(this,"transmitter"),__publicField(this,"eventsToWatch",["click","mousedown","keydown","touchstart","focus"]),__publicField(this,"handleEvent",t=>{const e=t.target;if(!(e&&e instanceof HTMLElement))return;if(e===document.body||e===document.documentElement)return;const i=this.checkVisibility(e,t);if(i){const s=e.getBoundingClientRect();this.transmitter.send("invisible_interaction",{type:t.type,target:e.tagName,id:e.id,reason:i,timestamp:Date.now(),isTrusted:t.isTrusted,coordinates:{x:t instanceof MouseEvent?t.clientX:0,y:t instanceof MouseEvent?t.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=t}start(){this.eventsToWatch.forEach(t=>{document.addEventListener(t,this.handleEvent,{capture:!0,passive:!0})})}stop(){this.eventsToWatch.forEach(t=>{document.removeEventListener(t,this.handleEvent,{capture:!0})})}checkVisibility(t,e){var i,s;const n=window.getComputedStyle(t);if("none"===n.display)return"display:none";if("hidden"===n.visibility)return"visibility:hidden";if("0"===n.opacity)return"opacity:0";const a=t.getBoundingClientRect();if(a.width<=0||a.height<=0)return"zero_size";const r=a.right<0||a.left>window.innerWidth,l=a.bottom<0||a.top>window.innerHeight;if(r||l)return"off_screen";if(e instanceof MouseEvent||e instanceof TouchEvent){let n,a;if(e instanceof MouseEvent?(n=e.clientX,a=e.clientY):(n=(null==(i=e.touches[0])?void 0:i.clientX)||0,a=(null==(s=e.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!==t&&!t.contains(i)&&!i.contains(t)&&0===n&&0===a&&e.isTrusted)return null}}return null}}const securitySDK=new class{constructor(){__publicField(this,"transmitter"),__publicField(this,"collector"),__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,"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.collector=new EventCollector(this.transmitter),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)}async init(t){var e,i;if(this.initialized)return;t.callbacks&&this.callbackManager.setConfigCallbacks(t.callbacks);const s=t.endpoint.replace(/\/events$/,"");try{await this.wasmService.load(s),this.startDetectors(),this.transmitter.setConfig(t),this.challengeHandler=new ChallengeHandler(s),this.challengeHandler.setCallbackManager(this.callbackManager),!1!==(null==(e=t.serverConfig)?void 0:e.captchaEnabled)&&this.challengeHandler.start();((null==(i=t.serverConfig)?void 0:i.devtoolsDetection)??!t.debug)&&Promise.resolve().then(()=>require("../anti-debug-CYwG4s7P.cjs")).then(({AntiDebug:t})=>{t.start(),Promise.resolve().then(()=>require("../console-D3Kd9M_6.cjs")).then(({ConsoleDetector:t})=>{new t(()=>{this.transmitter.send("devtools_open",{detected:!0})}).start()})}),this.initialized=!0,t.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(t,e){this.callbackManager.on(t,e)}off(t,e){this.callbackManager.off(t,e)}once(t,e){this.callbackManager.once(t,e)}startDetectors(){this.collector.start(),this.behaviorCollector.start(),this.honeypot.start(),this.mouseTracker.start(),this.canvasFingerprinter.start(),this.inputTracker.start(),this.invisibleInteraction.start()}};"undefined"!=typeof window&&(window.SecuritySDK=securitySDK);exports.Aientrophy=class{constructor(t){__publicField(this,"config"),this.config=t}async protect(){const t=this.config.endpoint||"https://api.aientrophy.com/api/v1/events";let e={};try{const s=t.replace(/\/events$/,""),n=await fetch(`${s}/sdk/payload?clientKey=${encodeURIComponent(this.config.clientKey)}`);if(n.ok){e=(await n.json()).config||{}}if(e.nonceValidation)try{const t=await fetch(`${s}/sdk/nonce?clientKey=${encodeURIComponent(this.config.clientKey)}`);if(t.ok){const i=await t.json();i.nonce&&(e.initialNonce=i.nonce)}}catch(i){this.config.debug}}catch(i){this.config.debug}await securitySDK.init({endpoint:t,clientKey:this.config.clientKey,debug:this.config.debug,callbacks:this.config.callbacks,serverConfig:e})}on(t,e){securitySDK.on(t,e)}off(t,e){securitySDK.off(t,e)}once(t,e){securitySDK.once(t,e)}};
1
+ "use strict";var __defProp=Object.defineProperty,__publicField=(t,e,i)=>((t,e,i)=>e in t?__defProp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i)(t,"symbol"!=typeof e?e+"":e,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)return;this.sessionKey=await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]);const t=await this.importPublicKey(CONFIG_RSA_PUBLIC_KEY),e=await window.crypto.subtle.exportKey("raw",this.sessionKey),i=await window.crypto.subtle.encrypt({name:"RSA-OAEP"},t,e);this.encryptedSessionKey=this.arrayBufferToBase64(i)}static async encrypt(t){this.sessionKey||await this.init();const e=JSON.stringify(t),i=(new TextEncoder).encode(e),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),l=a.slice(a.length-16);return{ek:this.encryptedSessionKey,d:this.arrayBufferToBase64(r.buffer),iv:this.arrayBufferToBase64(s.buffer),tag:this.arrayBufferToBase64(l.buffer)}}static async decrypt(t){if(!this.sessionKey)throw new Error("Session key not initialized");const e=this.base64ToArrayBuffer(t.d),i=this.base64ToArrayBuffer(t.iv),s=this.base64ToArrayBuffer(t.tag),n=new Uint8Array(e.byteLength+s.byteLength);n.set(new Uint8Array(e),0),n.set(new Uint8Array(s),e.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 async importPublicKey(t){const e=window.atob(t),i=this.str2ab(e);return await window.crypto.subtle.importKey("spki",i,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"])}static str2ab(t){const e=new ArrayBuffer(t.length),i=new Uint8Array(e);for(let s=0,n=t.length;s<n;s++)i[s]=t.charCodeAt(s);return e}static arrayBufferToBase64(t){let e="";const i=new Uint8Array(t),s=i.byteLength;for(let n=0;n<s;n++)e+=String.fromCharCode(i[n]);return window.btoa(e)}static base64ToArrayBuffer(t){const e=window.atob(t),i=e.length,s=new Uint8Array(i);for(let n=0;n<i;n++)s[n]=e.charCodeAt(n);return s.buffer}}__publicField(CryptoUtils,"sessionKey",null),__publicField(CryptoUtils,"encryptedSessionKey",null);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"]);class CallbackManager{constructor(){__publicField(this,"handlers",new Map),__publicField(this,"configCallbacks",{})}setConfigCallbacks(t){this.configCallbacks=t}on(t,e){this.addHandler(t,e,!1)}once(t,e){this.addHandler(t,e,!0)}off(t,e){const i=this.handlers.get(t);if(!i)return;const s=i.filter(t=>t.handler!==e);0===s.length?this.handlers.delete(t):this.handlers.set(t,s)}emit(t,...e){this.callHandlers(t,e);const i=t.indexOf(":");if(-1!==i){const s=t.substring(0,i);this.callHandlers(s,e)}this.callConfigCallback(t,e)}emitChallenge(t){return new Promise(e=>{let i=!1;const s=t=>{i||(i=!0,e(t))},n=this.handlers.has("challenge")&&this.handlers.get("challenge").length>0,a=!!this.configCallbacks.onChallenge;n||a?(this.callHandlers("challenge",[t,s]),this.configCallbacks.onChallenge&&this.safeCall(this.configCallbacks.onChallenge,[t,s]),setTimeout(()=>{i||(i=!0,e(!1))},5e3)):e(!1)})}addHandler(t,e,i){this.handlers.has(t)||this.handlers.set(t,[]),this.handlers.get(t).push({handler:e,once:i})}callHandlers(t,e){const i=this.handlers.get(t);if(!i||0===i.length)return;const s=[];for(let n=0;n<i.length;n++)this.safeCall(i[n].handler,e),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(t)}callConfigCallback(t,e){if(t.startsWith("threat:")||"threat"===t)return void(t.startsWith("threat:")&&this.configCallbacks.onThreatDetected&&this.safeCall(this.configCallbacks.onThreatDetected,e));const i={ready:"onReady",error:"onError",block:"onBlock",allow:"onAllow"}[t];i&&this.configCallbacks[i]&&this.safeCall(this.configCallbacks[i],e)}safeCall(t,e){try{t(...e)}catch(i){}}}class Transmitter{constructor(){__publicField(this,"endpoint",""),__publicField(this,"clientKey",""),__publicField(this,"encryptionRequired",!1),__publicField(this,"currentNonce",""),__publicField(this,"buffer",[]),__publicField(this,"batchSize",10),__publicField(this,"flushInterval",3e3),__publicField(this,"intervalId"),__publicField(this,"responseHandler",null),__publicField(this,"callbackManager",null),__publicField(this,"flushing",!1),__publicField(this,"pendingFlush",!1),this.startFlushInterval()}setConfig(t){var e,i;this.endpoint=t.endpoint,this.clientKey=t.clientKey,this.encryptionRequired=(null==(e=t.serverConfig)?void 0:e.encryptionRequired)??!1,this.currentNonce=(null==(i=t.serverConfig)?void 0:i.initialNonce)??""}setResponseHandler(t){this.responseHandler=t}setCallbackManager(t){this.callbackManager=t}send(t,e={}){const i=Date.now();if(this.buffer.push({type:t,data:e,timestamp:i}),this.callbackManager)if(THREAT_EVENTS.has(t)){const s={type:t,data:e,timestamp:i};this.callbackManager.emit(`threat:${t}`,s)}else this.callbackManager.emit(`data:${t}`,{type:t,data:e,timestamp:i});this.buffer.length>=this.batchSize&&this.flush()}async flush(){if(0===this.buffer.length||!this.endpoint)return;if(this.flushing)return void(this.pendingFlush=!0);this.flushing=!0;const t=this.buffer;this.buffer=[];try{let s;if(this.encryptionRequired){const e=await CryptoUtils.encrypt(t);s=JSON.stringify(e)}else s=JSON.stringify(t);const n={"Content-Type":"application/json","x-client-key":this.clientKey};this.currentNonce&&(n["x-request-nonce"]=this.currentNonce,this.currentNonce="");try{const t=await fetch(this.endpoint,{method:"POST",body:s,headers:n,keepalive:!0});if(t.ok&&this.callbackManager&&this.callbackManager.emit("allow",{action:"allow"}),t.ok)try{const e=await t.json();let i=e;this.encryptionRequired&&(i=await CryptoUtils.decrypt(e)),(null==i?void 0:i.nonce)&&(this.currentNonce=i.nonce),this.responseHandler&&this.responseHandler(i)}catch(e){}}catch(i){this.callbackManager&&this.callbackManager.emit("error",{code:"NETWORK_ERROR",message:"Failed to send security events"})}}catch(e){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 EventCollector{constructor(t){__publicField(this,"transmitter"),__publicField(this,"listeners",{}),this.transmitter=t}start(){this.attachListeners()}stop(){this.detachListeners()}attachListeners(){this.listeners.mousemove=this.throttle(t=>{const e=t;this.transmitter.send("mousemove",{x:e.clientX,y:e.clientY,timestamp:Date.now()})},100),this.listeners.click=t=>{const e=t;this.transmitter.send("click",{x:e.clientX,y:e.clientY,target:e.target.tagName,timestamp:Date.now()})},this.listeners.keydown=t=>{const e=t;this.transmitter.send("keydown",{key:e.key,timestamp:Date.now()})},window.addEventListener("mousemove",this.listeners.mousemove),window.addEventListener("click",this.listeners.click),window.addEventListener("keydown",this.listeners.keydown)}detachListeners(){this.listeners.mousemove&&window.removeEventListener("mousemove",this.listeners.mousemove),this.listeners.click&&window.removeEventListener("click",this.listeners.click),this.listeners.keydown&&window.removeEventListener("keydown",this.listeners.keydown)}throttle(t,e){let i;return function(...s){i||(t.apply(this,s),i=!0,setTimeout(()=>i=!1,e))}}}class BehaviorCollector{constructor(t){__publicField(this,"transmitter"),__publicField(this,"trajectoryBuffer",[]),__publicField(this,"keystrokeBuffer",[]),__publicField(this,"isCollecting",!1),__publicField(this,"flushInterval",3e3),__publicField(this,"flushTimer"),__publicField(this,"lastMouseMoveTime",0),__publicField(this,"onMouseMove",t=>{const e=Date.now();e-this.lastMouseMoveTime>50&&(this.trajectoryBuffer.push({x:t.clientX,y:t.clientY,t:e}),this.lastMouseMoveTime=e)}),__publicField(this,"onKeyDown",t=>{this.keystrokeBuffer.push({code:t.code,t:Date.now(),type:"down"})}),__publicField(this,"onKeyUp",t=>{this.keystrokeBuffer.push({code:t.code,t:Date.now(),type:"up"})}),this.transmitter=t}start(){this.isCollecting||(this.isCollecting=!0,this.attachListeners(),this.startFlushTimer())}stop(){this.isCollecting=!1,this.detachListeners(),this.stopFlushTimer(),this.flush()}attachListeners(){window.addEventListener("mousemove",this.onMouseMove),window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp)}detachListeners(){window.removeEventListener("mousemove",this.onMouseMove),window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp)}startFlushTimer(){this.flushTimer=setInterval(()=>{this.flush()},this.flushInterval)}stopFlushTimer(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null)}flush(){if(0===this.trajectoryBuffer.length&&0===this.keystrokeBuffer.length)return;const t={trajectory:[...this.trajectoryBuffer],keystrokes:[...this.keystrokeBuffer],url:window.location.href};this.trajectoryBuffer=[],this.keystrokeBuffer=[],this.transmitter.send("behavior_data",t)}}class RapidClickDetector{constructor(t){__publicField(this,"transmitter"),__publicField(this,"clickHistory",[]),__publicField(this,"THRESHOLD_COUNT",3),__publicField(this,"THRESHOLD_TIME",500),this.transmitter=t,this.init()}init(){document.addEventListener("click",t=>this.handleClick(t),!0)}handleClick(t){const e=Date.now();if(this.clickHistory.push(e),this.clickHistory=this.clickHistory.filter(t=>e-t<=this.THRESHOLD_TIME),this.clickHistory.length>=this.THRESHOLD_COUNT){const i=t.target,s={tagName:i.tagName,id:i.id,className:i.className,x:t.clientX,y:t.clientY};this.transmitter.send("rapid_click",{count:this.clickHistory.length,duration:this.THRESHOLD_TIME,target:s,timestamp:e}),this.clickHistory=[]}}}class Honeypot{constructor(t){__publicField(this,"transmitter"),__publicField(this,"element",null),this.transmitter=t}start(){this.element=document.createElement("input"),this.element.type="text";const t=["website","email_confirm","url","homepage","fax_number","address_line_2"],e=t[Math.floor(Math.random()*t.length)],i=Math.random().toString(36).substr(2,5);this.element.id="hp-"+Math.random().toString(36).substr(2,9),this.element.name=`${e}-${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=t=>{var e;this.transmitter.send("honeypot_triggered",{eventType:t.type,value:null==(e=this.element)?void 0:e.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(t,e){__publicField(this,"transmitter"),__publicField(this,"wasmService"),__publicField(this,"buffer",[]),__publicField(this,"BUFFER_SIZE",10),__publicField(this,"SAMPLE_INTERVAL",50),__publicField(this,"lastSampleTime",0),__publicField(this,"handleMouseMove",t=>{const e=Date.now();e-this.lastSampleTime<this.SAMPLE_INTERVAL||(this.lastSampleTime=e,this.buffer.push({x:t.clientX,y:t.clientY,time:e}),this.buffer.length>this.BUFFER_SIZE&&(this.buffer.shift(),this.analyze()))}),this.transmitter=t,this.wasmService=e}start(){"undefined"!=typeof document&&document.addEventListener("mousemove",this.handleMouseMove)}stop(){"undefined"!=typeof document&&document.removeEventListener("mousemove",this.handleMouseMove)}analyze(){if(this.buffer.length<5)return;const t=this.wasmService.calculateEntropy(this.buffer),e=this.calculateSpeedVariance();this.transmitter.send("behavior_metrics",{entropy:t,speedVariance:e,timestamp:Date.now()}),this.buffer=[]}calculateSpeedVariance(){const t=[];for(let i=1;i<this.buffer.length;i++){const e=this.buffer[i-1],s=this.buffer[i],n=Math.sqrt(Math.pow(s.x-e.x,2)+Math.pow(s.y-e.y,2)),a=s.time-e.time;a>0&&t.push(n/a)}if(t.length<2)return 1;const e=t.reduce((t,e)=>t+e,0)/t.length;return t.reduce((t,i)=>t+Math.pow(i-e,2),0)/t.length}}class InputTracker{constructor(t){__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),this.transmitter=t,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(t=>{document.addEventListener(t,t=>{this.lastInteractionTime=Date.now(),this.lastInteractionType=t.type},{passive:!0,capture:!0})}),document.addEventListener("focus",t=>{const e=t.target;"INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName||(this.checkFocusIntegrity(),this.flightTimes=[],this.dwellTimes=[],this.lastKeyUpTime=0)},{capture:!0}),document.addEventListener("keydown",t=>{const e=t.target;if("INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName)return;const i=Date.now();if(this.keyPressTimes.set(t.code,i),this.lastKeyUpTime>0){const t=i-this.lastKeyUpTime;t<2e3&&this.flightTimes.push(t)}},{passive:!0,capture:!0}),document.addEventListener("keyup",t=>{const e=t.target;if("INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName)return;const i=Date.now();this.lastKeyUpTime=i;const s=this.keyPressTimes.get(t.code);if(s){const e=i-s;this.dwellTimes.push(e),this.keyPressTimes.delete(t.code)}this.flightTimes.length>=10&&this.reportKeystrokeDynamics(e)},{passive:!0,capture:!0}),document.addEventListener("blur",t=>{const e=t.target;("INPUT"===e.tagName||"TEXTAREA"===e.tagName)&&this.flightTimes.length>0&&this.reportKeystrokeDynamics(e)},{capture:!0})}checkFocusIntegrity(){const t=Date.now(),e=t-this.lastInteractionTime;performance.now()<2e3||(e>200?(this.suspiciousFocusCount++,clearTimeout(this.suspiciousFocusResetTimer),this.suspiciousFocusResetTimer=setTimeout(()=>{this.suspiciousFocusCount=0},3e3),this.transmitter.send("behavior_metrics",{type:"suspicious_focus",timeSinceInteraction:e,lastInteraction:this.lastInteractionType,consecutiveCount:this.suspiciousFocusCount,timestamp:t}),this.suspiciousFocusCount>=3&&(this.transmitter.send("integrity_violation",{type:"programmatic_focus",details:`${this.suspiciousFocusCount} consecutive input focuses without click/tab`,consecutiveCount:this.suspiciousFocusCount,timestamp:t}),this.suspiciousFocusCount=0)):this.suspiciousFocusCount=0)}reportKeystrokeDynamics(t){const e=this.average(this.flightTimes),i=this.variance(this.flightTimes,e),s=this.average(this.dwellTimes),n=this.variance(this.dwellTimes,s);this.transmitter.send("input_metrics",{element:t.id||t.tagName,flight:{avg:e,variance:i,samples:this.flightTimes.length},dwell:{avg:s,variance:n},isMobile:this.isMobile,timestamp:Date.now()}),this.flightTimes=[],this.dwellTimes=[]}average(t){return 0===t.length?0:t.reduce((t,e)=>t+e,0)/t.length}variance(t,e){return 0===t.length?0:t.reduce((t,i)=>t+Math.pow(i-e,2),0)/t.length}}class WasmService{constructor(){__publicField(this,"wasmModule",null),__publicField(this,"memory",null),__publicField(this,"instance",null)}async load(t){try{const e=await fetch(`${t}/sdk/core.wasm`);if(!e.ok)throw new Error(`HTTP ${e.status}`);const i={env:{abort:()=>{}}};if(WebAssembly.instantiateStreaming){const t=await WebAssembly.instantiateStreaming(e,i);this.instance=t.instance}else{const t=await e.arrayBuffer(),s=await WebAssembly.instantiate(t,i);this.instance=s.instance}this.wasmModule=this.instance.exports,this.memory=this.wasmModule.memory}catch(e){}}isLoaded(){return!!this.instance}calculateEntropy(t){if(!this.instance||!this.wasmModule)return 0;const e=2*t.length,i=8*e;try{const s=this.wasmModule.__new(i,0),n=new Float64Array(this.memory.buffer,s,e);for(let e=0;e<t.length;e++)n[2*e]=t[e].x,n[2*e+1]=t[e].y;return this.wasmModule.calculateEntropy(s,e)}catch(s){return 0}}simpleHash(t){if(!this.instance||!this.wasmModule)return 0;try{const e=(new TextEncoder).encode(t),i=e.length,s=this.wasmModule.__new(i,0);return new Uint8Array(this.memory.buffer,s,i).set(e),this.wasmModule.simpleHash(s,i)}catch(e){return 0}}}class CanvasFingerprinter{constructor(t,e){__publicField(this,"transmitter"),__publicField(this,"wasmService"),__publicField(this,"hasRun",!1),this.transmitter=t,this.wasmService=e}start(){this.hasRun||"undefined"==typeof document||setTimeout(()=>{const t=this.generateFingerprint();this.transmitter.send("fingerprint_collected",{hash:t}),this.hasRun=!0},500)}generateFingerprint(){try{const t=document.createElement("canvas"),e=t.getContext("2d");if(!e)return"unknown";e.textBaseline="top",e.font='14px "Arial"',e.textBaseline="alphabetic",e.fillStyle="#f60",e.fillRect(125,1,62,20),e.fillStyle="#069",e.fillText("aientrophy Security 😃",2,15),e.fillStyle="rgba(102, 204, 0, 0.7)",e.fillText("aientrophy Security 😃",4,17),e.globalCompositeOperation="multiply",e.fillStyle="rgb(255,0,255)",e.beginPath(),e.arc(50,50,50,0,2*Math.PI,!0),e.closePath(),e.fill(),e.fillStyle="rgb(0,255,255)",e.beginPath(),e.arc(100,50,50,0,2*Math.PI,!0),e.closePath(),e.fill(),e.fillStyle="rgb(255,255,0)",e.beginPath(),e.arc(75,100,50,0,2*Math.PI,!0),e.closePath(),e.fill();const i=t.toDataURL(),s=this.wasmService.simpleHash(i);return Math.abs(s).toString(16)}catch(t){return"error"}}}class ChallengeHandler{constructor(t){__publicField(this,"originalFetch"),__publicField(this,"endpoint"),__publicField(this,"callbackManager",null),this.endpoint=t,this.originalFetch=window.fetch.bind(window)}setCallbackManager(t){this.callbackManager=t}start(){window.fetch=async(t,e)=>{var i;const s=await this.originalFetch(t,e);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(t,e)}return await this.showCaptchaModal()?this.originalFetch(t,e):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(t=>{const e=document.createElement("div");e.id="sec-sdk-challenge-host",e.style.position="fixed",e.style.top="0",e.style.left="0",e.style.width="100vw",e.style.height="100vh",e.style.zIndex="999999",e.style.backgroundColor="rgba(0,0,0,0.5)",e.style.display="flex",e.style.justifyContent="center",e.style.alignItems="center";const i=e.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 l=document.createElement("input");l.type="text",l.placeholder="Enter details",l.style.padding="8px",l.style.marginRight="8px",l.style.border="1px solid #ddd",l.style.borderRadius="4px";const o=document.createElement("button");o.textContent="Verify",o.style.padding="8px 16px",o.style.background="#007bff",o.style.color="white",o.style.border="none",o.style.borderRadius="4px",o.style.cursor="pointer";const c=document.createElement("p");c.style.color="red",c.style.fontSize="12px",c.style.display="none",s.appendChild(n),s.appendChild(a),s.appendChild(r),s.appendChild(l),s.appendChild(o),s.appendChild(c),i.appendChild(s),document.body.appendChild(e);let h="";const d=async()=>{try{const t=await this.originalFetch(`${this.endpoint}/challenge`),e=await t.json();h=e.id,r.innerHTML=e.svg}catch(t){r.textContent="Error loading CAPTCHA"}},u=async()=>{c.style.display="none",o.textContent="Verifying...";try{const i=l.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(e),t(!0)):(c.textContent="Incorrect, try again.",c.style.display="block",o.textContent="Verify",l.value="",d())}catch(i){c.textContent="System error.",c.style.display="block",o.textContent="Verify"}};o.onclick=u,l.onkeydown=t=>{"Enter"===t.key&&u()},d()})}}class InvisibleInteraction{constructor(t){__publicField(this,"transmitter"),__publicField(this,"eventsToWatch",["click","mousedown","keydown","touchstart","focus"]),__publicField(this,"handleEvent",t=>{const e=t.target;if(!(e&&e instanceof HTMLElement))return;if(e===document.body||e===document.documentElement)return;const i=this.checkVisibility(e,t);if(i){const s=e.getBoundingClientRect();this.transmitter.send("invisible_interaction",{type:t.type,target:e.tagName,id:e.id,reason:i,timestamp:Date.now(),isTrusted:t.isTrusted,coordinates:{x:t instanceof MouseEvent?t.clientX:0,y:t instanceof MouseEvent?t.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=t}start(){this.eventsToWatch.forEach(t=>{document.addEventListener(t,this.handleEvent,{capture:!0,passive:!0})})}stop(){this.eventsToWatch.forEach(t=>{document.removeEventListener(t,this.handleEvent,{capture:!0})})}checkVisibility(t,e){var i,s;const n=window.getComputedStyle(t);if("none"===n.display)return"display:none";if("hidden"===n.visibility)return"visibility:hidden";if("0"===n.opacity)return"opacity:0";const a=t.getBoundingClientRect();if(a.width<=0||a.height<=0)return"zero_size";const r=a.right<0||a.left>window.innerWidth,l=a.bottom<0||a.top>window.innerHeight;if(r||l)return"off_screen";if(e instanceof MouseEvent||e instanceof TouchEvent){let n,a;if(e instanceof MouseEvent?(n=e.clientX,a=e.clientY):(n=(null==(i=e.touches[0])?void 0:i.clientX)||0,a=(null==(s=e.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!==t&&!t.contains(i)&&!i.contains(t)&&0===n&&0===a&&e.isTrusted)return null}}return null}}const securitySDK=new class{constructor(){__publicField(this,"transmitter"),__publicField(this,"collector"),__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,"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.collector=new EventCollector(this.transmitter),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)}async init(t){var e,i;if(this.initialized)return;t.callbacks&&this.callbackManager.setConfigCallbacks(t.callbacks);const s=t.endpoint.replace(/\/events$/,"");try{await this.wasmService.load(s),this.startDetectors(),this.transmitter.setConfig(t),this.challengeHandler=new ChallengeHandler(s),this.challengeHandler.setCallbackManager(this.callbackManager),!1!==(null==(e=t.serverConfig)?void 0:e.captchaEnabled)&&this.challengeHandler.start();((null==(i=t.serverConfig)?void 0:i.devtoolsDetection)??!t.debug)&&Promise.resolve().then(()=>require("../anti-debug-CYwG4s7P.cjs")).then(({AntiDebug:t})=>{t.start(),Promise.resolve().then(()=>require("../console-D3Kd9M_6.cjs")).then(({ConsoleDetector:t})=>{new t(()=>{this.transmitter.send("devtools_open",{detected:!0})}).start()})}),this.initialized=!0,t.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(t,e){this.callbackManager.on(t,e)}off(t,e){this.callbackManager.off(t,e)}once(t,e){this.callbackManager.once(t,e)}startDetectors(){this.collector.start(),this.behaviorCollector.start(),this.honeypot.start(),this.mouseTracker.start(),this.canvasFingerprinter.start(),this.inputTracker.start(),this.invisibleInteraction.start()}};"undefined"!=typeof window&&(window.SecuritySDK=securitySDK);exports.Aientrophy=class{constructor(t){__publicField(this,"config"),this.config=t}async protect(){const t=this.config.endpoint||"https://api.aientrophy.com/api/v1/events";let e={};try{const s=t.replace(/\/events$/,""),n=await fetch(`${s}/sdk/payload?clientKey=${encodeURIComponent(this.config.clientKey)}`);if(n.ok){e=(await n.json()).config||{}}if(e.nonceValidation)try{const t=await fetch(`${s}/sdk/nonce?clientKey=${encodeURIComponent(this.config.clientKey)}`);if(t.ok){const i=await t.json();i.nonce&&(e.initialNonce=i.nonce)}}catch(i){this.config.debug}}catch(i){this.config.debug}await securitySDK.init({endpoint:t,clientKey:this.config.clientKey,debug:this.config.debug,callbacks:this.config.callbacks,serverConfig:e})}on(t,e){securitySDK.on(t,e)}off(t,e){securitySDK.off(t,e)}once(t,e){securitySDK.once(t,e)}};
@@ -257,10 +257,12 @@ class Transmitter {
257
257
  __publicField(this, "currentNonce", "");
258
258
  __publicField(this, "buffer", []);
259
259
  __publicField(this, "batchSize", 10);
260
- __publicField(this, "flushInterval", 1e3);
260
+ __publicField(this, "flushInterval", 3e3);
261
261
  __publicField(this, "intervalId");
262
262
  __publicField(this, "responseHandler", null);
263
263
  __publicField(this, "callbackManager", null);
264
+ __publicField(this, "flushing", false);
265
+ __publicField(this, "pendingFlush", false);
264
266
  this.startFlushInterval();
265
267
  }
266
268
  setConfig(config) {
@@ -293,6 +295,11 @@ class Transmitter {
293
295
  }
294
296
  async flush() {
295
297
  if (this.buffer.length === 0 || !this.endpoint) return;
298
+ if (this.flushing) {
299
+ this.pendingFlush = true;
300
+ return;
301
+ }
302
+ this.flushing = true;
296
303
  const rawPayload = this.buffer;
297
304
  this.buffer = [];
298
305
  try {
@@ -311,12 +318,13 @@ class Transmitter {
311
318
  requestHeaders["x-request-nonce"] = this.currentNonce;
312
319
  this.currentNonce = "";
313
320
  }
314
- fetch(this.endpoint, {
315
- method: "POST",
316
- body: payload,
317
- headers: requestHeaders,
318
- keepalive: true
319
- }).then(async (res) => {
321
+ try {
322
+ const res = await fetch(this.endpoint, {
323
+ method: "POST",
324
+ body: payload,
325
+ headers: requestHeaders,
326
+ keepalive: true
327
+ });
320
328
  if (res.ok && this.callbackManager) {
321
329
  this.callbackManager.emit("allow", { action: "allow" });
322
330
  }
@@ -336,14 +344,14 @@ class Transmitter {
336
344
  } catch (e) {
337
345
  }
338
346
  }
339
- }).catch((err) => {
347
+ } catch (err) {
340
348
  if (this.callbackManager) {
341
349
  this.callbackManager.emit("error", {
342
350
  code: "NETWORK_ERROR",
343
351
  message: "Failed to send security events"
344
352
  });
345
353
  }
346
- });
354
+ }
347
355
  } catch (e) {
348
356
  if (this.callbackManager) {
349
357
  this.callbackManager.emit("error", {
@@ -351,6 +359,12 @@ class Transmitter {
351
359
  message: "Failed to prepare security payload"
352
360
  });
353
361
  }
362
+ } finally {
363
+ this.flushing = false;
364
+ if (this.pendingFlush) {
365
+ this.pendingFlush = false;
366
+ this.flush();
367
+ }
354
368
  }
355
369
  }
356
370
  stop() {
@@ -11,6 +11,8 @@ export declare class Transmitter {
11
11
  private intervalId;
12
12
  private responseHandler;
13
13
  private callbackManager;
14
+ private flushing;
15
+ private pendingFlush;
14
16
  constructor();
15
17
  setConfig(config: SecuritySDKConfig): void;
16
18
  setResponseHandler(handler: (response: any) => void): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aientrophy/sdk",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Aientrophy Security SDK – bot detection, threat monitoring, and CAPTCHA protection",
5
5
  "main": "dist/npm/index.cjs.js",
6
6
  "module": "dist/npm/index.es.js",