@aientrophy/sdk 0.3.4 → 0.3.5

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.
@@ -0,0 +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 antiDebug=require("./anti-debug-JDCTbZps.cjs");exports.ConsoleDetector=class{constructor(t){__publicField(this,"onDetect"),__publicField(this,"intervals",[]),__publicField(this,"detected",!1),this.onDetect=t}isMobile(){return navigator.maxTouchPoints>0||/Mobile|Android|iPhone|iPad/i.test(navigator.userAgent)}start(){this.isMobile()||(this.startGetterTrap(),this.startSizeDetection())}stop(){for(const t of this.intervals)clearInterval(t);this.intervals=[]}triggerDetect(){this.detected||(this.detected=!0,this.onDetect(),antiDebug.AntiDebug.reportDevtoolsDetection(),setTimeout(()=>{this.detected=!1},2e3))}startGetterTrap(){const t=antiDebug.AntiDebug.getOriginalConsole(),e=t.log,i=t.clear;if(!e)return;const r=document.createElement("div");Object.defineProperty(r,"id",{get:()=>(this.triggerDetect(),"")});const o=/./;o.toString=()=>(this.triggerDetect(),"");const s=setInterval(()=>{try{e(r),e(o),i&&i()}catch(t){}},1500);this.intervals.push(s)}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)}};
@@ -9,7 +9,11 @@ class ConsoleDetector {
9
9
  __publicField(this, "detected", false);
10
10
  this.onDetect = onDetect;
11
11
  }
12
+ isMobile() {
13
+ return navigator.maxTouchPoints > 0 || /Mobile|Android|iPhone|iPad/i.test(navigator.userAgent);
14
+ }
12
15
  start() {
16
+ if (this.isMobile()) return;
13
17
  this.startGetterTrap();
14
18
  this.startSizeDetection();
15
19
  }
@@ -73,9 +77,6 @@ class ConsoleDetector {
73
77
  * large outerHeight-innerHeight gaps, causing false positives.
74
78
  */
75
79
  startSizeDetection() {
76
- if (navigator.maxTouchPoints > 0 || /Mobile|Android|iPhone|iPad/i.test(navigator.userAgent)) {
77
- return;
78
- }
79
80
  const threshold = 160;
80
81
  const id = setInterval(() => {
81
82
  const wDiff = window.outerWidth - window.innerWidth > threshold;
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,n=(t,n,s)=>((t,n,s)=>n in t?e(t,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[n]=s)(t,"symbol"!=typeof n?n+"":n,s);const s="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqbBCvDqyUtfhgI/Lo5pDtn1phwA6qczAyp8N1ZgQ68OTxgbJUGiXV6N67p15bBdME1R4va51P2Czq2IbRby/N+GHTciTaXvmusV8IjnIOGtKlGxWCuKIPrCS+rGjGA2j1irxBbNpqItltFxjhxBGOzsyQAF6LNIz5IKA7sC6cSH8zUyLuFrV96udc801Zc4nCJG64ZljNbDvlVbJJZ6ex5OLLS6AnrVAXpjEDR/MI/I8JvAPe/psHj6EpXgvKrBYMBOH3jzQRzMFoR79jXyGNgPjdy0A+f6RVuEG8H5sUXKeyy+cFvaT+pm6h+t6RPED11tCOwQxYZ2pExhhPxDGeQIDAQAB";class i{static async init(){if(!this.sessionKey)try{await this.initECDH()}catch(t){await this.initRSA()}}static async initECDH(){const t=await window.crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),e=await window.crypto.subtle.exportKey("raw",t.publicKey);this.ecdhPublicKeyBase64=this.arrayBufferToBase64(e);const n=(window.__securitySDKEndpoint||"").replace(/\/events$/,""),s=await fetch(`${n}/key-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientPublicKey:this.ecdhPublicKeyBase64})});if(!s.ok)throw new Error("Key exchange failed");const{serverPublicKey:i,salt:r}=await s.json(),a=this.base64ToArrayBuffer(i),o=await window.crypto.subtle.importKey("raw",a,{name:"ECDH",namedCurve:"P-256"},!1,[]),c=await window.crypto.subtle.deriveBits({name:"ECDH",public:o},t.privateKey,256),l=await window.crypto.subtle.importKey("raw",c,"HKDF",!1,["deriveKey"]),h=this.base64ToArrayBuffer(r);this.sessionKey=await window.crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:h,info:(new TextEncoder).encode("aientrophy-session-enc")},l,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),this.protocolVersion=2}static async initRSA(){this.sessionKey=await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]);const t=await this.importRSAPublicKey(s),e=await window.crypto.subtle.exportKey("raw",this.sessionKey),n=await window.crypto.subtle.encrypt({name:"RSA-OAEP"},t,e);this.encryptedSessionKey=this.arrayBufferToBase64(n),this.protocolVersion=1}static async encrypt(t){this.sessionKey||await this.init();const e=JSON.stringify(t),n=(new TextEncoder).encode(e),s=window.crypto.getRandomValues(new Uint8Array(12)),i=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.sessionKey,n),r=new Uint8Array(i),a=r.slice(0,r.length-16),o=r.slice(r.length-16),c={ek:2===this.protocolVersion?this.ecdhPublicKeyBase64:this.encryptedSessionKey,d:this.arrayBufferToBase64(a.buffer),iv:this.arrayBufferToBase64(s.buffer),tag:this.arrayBufferToBase64(o.buffer)};return 2===this.protocolVersion&&(c.v=2),c}static async decrypt(t){if(!this.sessionKey)throw new Error("Session key not initialized");const e=this.base64ToArrayBuffer(t.d),n=this.base64ToArrayBuffer(t.iv),s=this.base64ToArrayBuffer(t.tag),i=new Uint8Array(e.byteLength+s.byteLength);i.set(new Uint8Array(e),0),i.set(new Uint8Array(s),e.byteLength);const r=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:n},this.sessionKey,i),a=(new TextDecoder).decode(r);return JSON.parse(a)}static setEndpoint(t){window.__securitySDKEndpoint=t}static async importRSAPublicKey(t){const e=window.atob(t),n=this.str2ab(e);return await window.crypto.subtle.importKey("spki",n,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"])}static str2ab(t){const e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let s=0,i=t.length;s<i;s++)n[s]=t.charCodeAt(s);return e}static arrayBufferToBase64(t){let e="";const n=new Uint8Array(t),s=n.byteLength;for(let i=0;i<s;i++)e+=String.fromCharCode(n[i]);return window.btoa(e)}static base64ToArrayBuffer(t){const e=window.atob(t),n=e.length,s=new Uint8Array(n);for(let i=0;i<n;i++)s[i]=e.charCodeAt(i);return s.buffer}}n(i,"sessionKey",null),n(i,"ecdhPublicKeyBase64",null),n(i,"encryptedSessionKey",null),n(i,"protocolVersion",2);const r=new Set(["rapid_click","honeypot_triggered","devtools_open","invisible_interaction","integrity_violation","dom_mutation","behavior_metrics","behavior_analysis","input_metrics","keystroke_dynamics","environmental_integrity","init_signals","automation_detected","cross_context_mismatch","headless_probe","script_injection","worker_integrity"]);class a{constructor(){n(this,"handlers",new Map),n(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 n=this.handlers.get(t);if(!n)return;const s=n.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 n=t.indexOf(":");if(-1!==n){const s=t.substring(0,n);this.callHandlers(s,e)}this.callConfigCallback(t,e)}emitChallenge(t){return new Promise(e=>{let n=!1;const s=t=>{n||(n=!0,e(t))},i=this.handlers.has("challenge")&&this.handlers.get("challenge").length>0,r=!!this.configCallbacks.onChallenge;i||r?(this.callHandlers("challenge",[t,s]),this.configCallbacks.onChallenge&&this.safeCall(this.configCallbacks.onChallenge,[t,s]),setTimeout(()=>{n||(n=!0,e(!1))},5e3)):e(!1)})}addHandler(t,e,n){this.handlers.has(t)||this.handlers.set(t,[]),this.handlers.get(t).push({handler:e,once:n})}callHandlers(t,e){const n=this.handlers.get(t);if(!n||0===n.length)return;const s=[];for(let i=0;i<n.length;i++)this.safeCall(n[i].handler,e),n[i].once&&s.push(i);for(let i=s.length-1;i>=0;i--)n.splice(s[i],1);0===n.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 n={ready:"onReady",error:"onError",block:"onBlock",allow:"onAllow"}[t];n&&this.configCallbacks[n]&&this.safeCall(this.configCallbacks[n],e)}safeCall(t,e){try{t(...e)}catch(n){}}}class o{constructor(){n(this,"endpoint",""),n(this,"clientKey",""),n(this,"encryptionRequired",!1),n(this,"currentNonce",""),n(this,"buffer",[]),n(this,"batchSize",20),n(this,"flushInterval",5e3),n(this,"intervalId"),n(this,"responseHandler",null),n(this,"callbackManager",null),n(this,"flushing",!1),n(this,"pendingFlush",!1),n(this,"backoffMs",0),n(this,"maxBackoffMs",6e4),n(this,"_lastBackoffStart",0),this.startFlushInterval()}setConfig(t){var e,n;this.endpoint=t.endpoint,this.clientKey=t.clientKey,this.encryptionRequired=(null==(e=t.serverConfig)?void 0:e.encryptionRequired)??!1,this.currentNonce=(null==(n=t.serverConfig)?void 0:n.initialNonce)??"",i.setEndpoint(t.endpoint)}setResponseHandler(t){this.responseHandler=t}setCallbackManager(t){this.callbackManager=t}send(t,e={}){const n=Date.now();if(this.buffer.push({type:t,data:e,timestamp:n}),this.callbackManager)if(r.has(t)){const s={type:t,data:e,timestamp:n};this.callbackManager.emit(`threat:${t}`,s)}else this.callbackManager.emit(`data:${t}`,{type:t,data:e,timestamp:n});this.buffer.length>=this.batchSize&&this.flush()}async flush(){if(0===this.buffer.length||!this.endpoint)return;if(this.backoffMs>0){const t=Date.now();if(this._lastBackoffStart||(this._lastBackoffStart=t),t-this._lastBackoffStart<this.backoffMs)return;this._lastBackoffStart=0}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 i.encrypt(t);s=JSON.stringify(e)}else s=JSON.stringify(t);const r={"Content-Type":"application/json","x-client-key":this.clientKey};this.currentNonce&&(r["x-request-nonce"]=this.currentNonce,this.currentNonce="");try{const n=await fetch(this.endpoint,{method:"POST",body:s,headers:r,keepalive:!0});if(429===n.status)return this.buffer=t.concat(this.buffer).slice(0,500),this.backoffMs=0===this.backoffMs?5e3:Math.min(2*this.backoffMs,this.maxBackoffMs),void(this._lastBackoffStart=Date.now());if(this.backoffMs=0,n.ok&&this.callbackManager&&this.callbackManager.emit("allow",{action:"allow"}),n.ok)try{const t=await n.json();let e=t;this.encryptionRequired&&(e=await i.decrypt(t)),(null==e?void 0:e.nonce)&&(this.currentNonce=e.nonce),this.responseHandler&&this.responseHandler(e)}catch(e){}}catch(n){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 c{constructor(t){n(this,"transmitter"),n(this,"isCollecting",!1),this.transmitter=t}start(){this.isCollecting||(this.isCollecting=!0)}stop(){this.isCollecting=!1}}class l{constructor(t){n(this,"transmitter"),n(this,"clickHistory",[]),n(this,"THRESHOLD_COUNT",3),n(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 n=t.target,s={tagName:n.tagName,id:n.id,className:n.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 h{constructor(t){n(this,"transmitter"),n(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)],n=Math.random().toString(36).substr(2,5);this.element.id="hp-"+Math.random().toString(36).substr(2,9),this.element.name=`${e}-${n}`,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){n(this,"transmitter"),n(this,"wasmService"),n(this,"buffer",[]),n(this,"BUFFER_SIZE",50),n(this,"SAMPLE_INTERVAL",100),n(this,"SEND_COOLDOWN",5e3),n(this,"lastSampleTime",0),n(this,"lastSendTime",0),n(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.buffer.length>=this.BUFFER_SIZE&&e-this.lastSendTime>=this.SEND_COOLDOWN&&(this.analyze(),this.lastSendTime=e))}),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<20)return;const t=this.wasmService.calculateEntropy(this.buffer),e=this.calculateSpeedVariance(),n=this.buffer.map(t=>({x:t.x,y:t.y,t:t.time}));this.transmitter.send("behavior_metrics",{entropy:t,speedVariance:e,sampleSize:this.buffer.length,timestamp:Date.now(),rawTrajectory:n})}calculateSpeedVariance(){const t=[];for(let n=1;n<this.buffer.length;n++){const e=this.buffer[n-1],s=this.buffer[n],i=Math.sqrt(Math.pow(s.x-e.x,2)+Math.pow(s.y-e.y,2)),r=s.time-e.time;r>0&&t.push(i/r)}if(t.length<2)return 1;const e=t.reduce((t,e)=>t+e,0)/t.length;return t.reduce((t,n)=>t+Math.pow(n-e,2),0)/t.length}}class d{constructor(t){n(this,"lastInteractionTime",0),n(this,"lastInteractionType","none"),n(this,"transmitter"),n(this,"isMobile",!1),n(this,"keyPressTimes",new Map),n(this,"lastKeyUpTime",0),n(this,"flightTimes",[]),n(this,"dwellTimes",[]),n(this,"suspiciousFocusCount",0),n(this,"suspiciousFocusResetTimer",null),n(this,"rawKeystrokes",[]),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.rawKeystrokes=[],this.lastKeyUpTime=0)},{capture:!0}),document.addEventListener("keydown",t=>{const e=t.target;if("INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName)return;const n=Date.now();if(this.keyPressTimes.set(t.code,n),this.rawKeystrokes.push({code:t.code,t:n,type:"down"}),this.lastKeyUpTime>0){const t=n-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 n=Date.now();this.lastKeyUpTime=n,this.rawKeystrokes.push({code:t.code,t:n,type:"up"});const s=this.keyPressTimes.get(t.code);if(s){const e=n-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()<5e3||(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=0)}reportKeystrokeDynamics(t){const e=this.average(this.flightTimes),n=this.variance(this.flightTimes,e),s=this.average(this.dwellTimes),i=this.variance(this.dwellTimes,s);this.transmitter.send("input_metrics",{element:t.id||t.tagName,flight:{avg:e,variance:n,samples:this.flightTimes.length},dwell:{avg:s,variance:i},isMobile:this.isMobile,timestamp:Date.now(),rawKeystrokes:[...this.rawKeystrokes]}),this.flightTimes=[],this.dwellTimes=[],this.rawKeystrokes=[]}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,n)=>t+Math.pow(n-e,2),0)/t.length}}class p{constructor(){n(this,"wasmModule",null),n(this,"memory",null),n(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 n={env:{abort:()=>{}}};if(WebAssembly.instantiateStreaming){const t=await WebAssembly.instantiateStreaming(e,n);this.instance=t.instance}else{const t=await e.arrayBuffer(),s=await WebAssembly.instantiate(t,n);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,n=8*e;try{const s=this.wasmModule.__new(n,0),i=new Float64Array(this.memory.buffer,s,e);for(let e=0;e<t.length;e++)i[2*e]=t[e].x,i[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),n=e.length,s=this.wasmModule.__new(n,0);return new Uint8Array(this.memory.buffer,s,n).set(e),this.wasmModule.simpleHash(s,n)}catch(e){return 0}}}class m{constructor(t,e){n(this,"transmitter"),n(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof document||setTimeout(async()=>{const t=await this.generateFingerprint(),e=this.collectWebGLFingerprint(),n=this.collectAudioFingerprint();this.transmitter.send("fingerprint_collected",{hash:t,webgl:e,audio:n}),this.hasRun=!0},500)}async 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 n=t.toDataURL();return await this.sha256(n)}catch(t){return"error"}}async sha256(t){const e=(new TextEncoder).encode(t),n=await window.crypto.subtle.digest("SHA-256",e),s=new Uint8Array(n);return Array.from(s).map(t=>t.toString(16).padStart(2,"0")).join("")}collectWebGLFingerprint(){try{const t=document.createElement("canvas"),e=t.getContext("webgl")||t.getContext("experimental-webgl");if(!e)return{available:!1};const n=e,s={available:!0},i=n.getExtension("WEBGL_debug_renderer_info");return i&&(s.renderer=n.getParameter(i.UNMASKED_RENDERER_WEBGL),s.vendor=n.getParameter(i.UNMASKED_VENDOR_WEBGL)),s.maxTextureSize=n.getParameter(n.MAX_TEXTURE_SIZE),s.maxViewportDims=Array.from(n.getParameter(n.MAX_VIEWPORT_DIMS)),s.maxRenderbufferSize=n.getParameter(n.MAX_RENDERBUFFER_SIZE),s.maxVertexAttribs=n.getParameter(n.MAX_VERTEX_ATTRIBS),s.extensions=(n.getSupportedExtensions()||[]).length,s}catch(t){return{available:!1,error:!0}}}collectAudioFingerprint(){try{const t=window.AudioContext||window.webkitAudioContext;if(!t)return{available:!1};const e=new t,n={available:!0,sampleRate:e.sampleRate,state:e.state,maxChannels:e.destination.maxChannelCount};return e.close(),n}catch(t){return{available:!1}}}}class g{constructor(t){n(this,"originalFetch"),n(this,"endpoint"),n(this,"callbackManager",null),n(this,"challengeInProgress",null),this.endpoint=t,this.originalFetch=window.fetch.bind(window)}setCallbackManager(t){this.callbackManager=t}start(){window.fetch=async(t,e)=>{var n;const s=await this.originalFetch(t,e);if(403===s.status){const r=s.clone();try{const i=await r.json();if("challenge"===i.action&&"captcha"===(null==(n=i.metadata)?void 0:n.type)){const n={action:"challenge",score:i.score,metadata:i.metadata};if(this.callbackManager){if(await this.callbackManager.emitChallenge(n))return this.originalFetch(t,e)}this.challengeInProgress||(this.challengeInProgress=this.showCaptchaModal().finally(()=>{this.challengeInProgress=null}));return await this.challengeInProgress?this.originalFetch(t,e):s}"block"===i.action&&this.callbackManager&&this.callbackManager.emit("block",{action:"block",score:i.score,metadata:i.metadata})}catch(i){}}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 n=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 i=document.createElement("h3");i.textContent="Security Check",i.style.margin="0 0 16px 0";const r=document.createElement("p");r.textContent="Unusual activity detected. Please verify you are human.",r.style.marginBottom="16px",r.style.fontSize="14px",r.style.color="#666";const a=document.createElement("div");a.innerHTML="Loading...",a.style.marginBottom="16px";const o=document.createElement("input");o.type="text",o.placeholder="Enter details",o.style.padding="8px",o.style.marginRight="8px",o.style.border="1px solid #ddd",o.style.borderRadius="4px";const c=document.createElement("button");c.textContent="Verify",c.style.padding="8px 16px",c.style.background="#007bff",c.style.color="white",c.style.border="none",c.style.borderRadius="4px",c.style.cursor="pointer";const l=document.createElement("p");l.style.color="red",l.style.fontSize="12px",l.style.display="none",s.appendChild(i),s.appendChild(r),s.appendChild(a),s.appendChild(o),s.appendChild(c),s.appendChild(l),n.appendChild(s),document.body.appendChild(e);let h="";const u=async()=>{try{const t=await this.originalFetch(`${this.endpoint}/challenge`),e=await t.json();h=e.id,a.innerHTML=e.svg}catch(t){a.textContent="Error loading CAPTCHA"}},d=async()=>{l.style.display="none",c.textContent="Verifying...";try{const n=o.value,s=await this.originalFetch(`${this.endpoint}/challenge/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:h,answer:n})});(await s.json()).success?(document.body.removeChild(e),t(!0)):(l.textContent="Incorrect, try again.",l.style.display="block",c.textContent="Verify",o.value="",u())}catch(n){l.textContent="System error.",l.style.display="block",c.textContent="Verify"}};c.onclick=d,o.onkeydown=t=>{"Enter"===t.key&&d()},u()})}}class y{constructor(t){n(this,"transmitter"),n(this,"eventsToWatch",["click","mousedown","keydown","touchstart","focus"]),n(this,"handleEvent",t=>{const e=t.target;if(!(e&&e instanceof HTMLElement))return;if(e===document.body||e===document.documentElement)return;const n=this.checkVisibility(e,t);if(n){const s=e.getBoundingClientRect();this.transmitter.send("invisible_interaction",{type:t.type,target:e.tagName,id:e.id,reason:n,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 n,s;const i=window.getComputedStyle(t);if("none"===i.display)return"display:none";if("hidden"===i.visibility)return"visibility:hidden";if("0"===i.opacity)return"opacity:0";const r=t.getBoundingClientRect();if(r.width<=0||r.height<=0)return"zero_size";const a=r.right<0||r.left>window.innerWidth,o=r.bottom<0||r.top>window.innerHeight;if(a||o)return"off_screen";if(e instanceof MouseEvent||e instanceof TouchEvent){let i,r;if(e instanceof MouseEvent?(i=e.clientX,r=e.clientY):(i=(null==(n=e.touches[0])?void 0:n.clientX)||0,r=(null==(s=e.touches[0])?void 0:s.clientY)||0),i>=0&&i<=window.innerWidth&&r>=0&&r<=window.innerHeight){const n=document.elementFromPoint(i,r);if(n&&n!==t&&!t.contains(n)&&!n.contains(t)&&0===i&&0===r&&e.isTrusted)return null}}return null}}class f{constructor(t){n(this,"transmitter"),n(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(setTimeout(()=>this.detect(),1500),this.hasRun=!0)}detect(){var t,e;const n={};let s=0;!0===navigator.webdriver&&(n.webdriver=!0,s+=40);try{this.detectCDP()&&(n.cdp=!0,s+=50)}catch(c){}const i=this.detectAutomationGlobals();i.length>0&&(n.automationGlobals=i,s+=30);const r=this.checkWebGL();r.suspicious&&(n.webgl=r,s+=25);const a=this.checkInconsistencies();a.length>0&&(n.inconsistencies=a,s+=15);const o=this.checkHeadless();o.score>0&&(n.headless=o.flags,s+=o.score),s>0&&this.transmitter.send("automation_detected",{signals:n,score:s,timestamp:Date.now()}),this.transmitter.send("init_signals",{webdriver:!!navigator.webdriver,plugins:(null==(t=navigator.plugins)?void 0:t.length)??0,languages:(null==(e=navigator.languages)?void 0:e.length)??0,platform:navigator.platform,hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:navigator.deviceMemory,maxTouchPoints:navigator.maxTouchPoints,webglRenderer:r.renderer,webglVendor:r.vendor,timestamp:Date.now()})}detectCDP(){let t=!1;const e=console.debug;return console.debug=e,t}detectAutomationGlobals(){const t=[],e=[["selenium",()=>!!window._selenium],["selenium_unwrapped",()=>!!document.__selenium_unwrapped],["driver_evaluate",()=>!!document.__driver_evaluate],["webdriver_evaluate",()=>!!document.__webdriver_evaluate],["driver_unwrapped",()=>!!document.__driver_unwrapped],["fxdriver",()=>!!document.__fxdriver_evaluate],["playwright",()=>!!window.__playwright],["playwright_binding",()=>!!window.__playwright__binding__],["pwInitScripts",()=>!!window.__pwInitScripts],["puppeteer",()=>!!window.__puppeteer_evaluation_script__],["phantom",()=>!!window.callPhantom||!!window._phantom],["nightmare",()=>!!window.__nightmare],["cdc",()=>Object.keys(document).some(t=>t.startsWith("cdc_")||t.startsWith("$cdc_"))]];for(const[s,i]of e)try{i()&&t.push(s)}catch(n){}return t}checkWebGL(){try{const t=document.createElement("canvas"),e=t.getContext("webgl")||t.getContext("experimental-webgl");if(!e)return{suspicious:!1,renderer:"unavailable",vendor:"unavailable"};const n=e.getExtension("WEBGL_debug_renderer_info");if(!n)return{suspicious:!1,renderer:"no_debug_info",vendor:"no_debug_info"};const s=e.getParameter(n.UNMASKED_RENDERER_WEBGL)||"",i=e.getParameter(n.UNMASKED_VENDOR_WEBGL)||"";return{suspicious:/SwiftShader/i.test(s)||/Mesa OffScreen/i.test(s)||/llvmpipe/i.test(s),renderer:s,vendor:i}}catch(t){return{suspicious:!1,renderer:"error",vendor:"error"}}}checkInconsistencies(){const t=[];try{const e=navigator.userAgent,n=navigator.platform;/Windows/.test(e)&&/Mac/.test(n)&&t.push("ua_platform_mismatch_win_mac"),/Macintosh/.test(e)&&/Win/.test(n)&&t.push("ua_platform_mismatch_mac_win"),/Mobile|Android|iPhone/.test(e)&&0===navigator.maxTouchPoints&&t.push("mobile_ua_no_touch"),/Chrome/.test(e)&&navigator.plugins&&0===navigator.plugins.length&&t.push("chrome_no_plugins"),navigator.languages&&0!==navigator.languages.length||t.push("no_languages")}catch(e){}return t}checkHeadless(){const t=[];let e=0;try{if(/HeadlessChrome/.test(navigator.userAgent)&&(t.push("headless_ua"),e+=40),/Chrome/.test(navigator.userAgent)&&!window.chrome&&(t.push("chrome_ua_no_chrome_obj"),e+=15),window.screen&&800===window.screen.width&&600===window.screen.height&&(t.push("default_screen_size"),e+=10),"Notification"in window){"denied"===window.Notification.permission&&navigator.userAgent.includes("Chrome")&&(t.push("notification_denied_default"),e+=5)}const n=navigator.connection;n&&0===n.rtt&&(t.push("zero_rtt"),e+=10)}catch(n){}return{score:e,flags:t}}}class w{constructor(t){n(this,"transmitter"),n(this,"sessionStart",0),n(this,"pageTransitions",[]),n(this,"interactionTimestamps",[]),n(this,"lastPageUrl",""),n(this,"formStartTimes",new Map),n(this,"reportInterval",null),this.transmitter=t}start(){if("undefined"==typeof window)return;this.sessionStart=Date.now(),this.lastPageUrl=window.location.href;["mousedown","keydown","touchstart","scroll"].forEach(t=>{document.addEventListener(t,()=>{this.interactionTimestamps.push(Date.now()),this.interactionTimestamps.length>500&&this.interactionTimestamps.shift()},{passive:!0,capture:!0})}),this.observeNavigation(),this.observeForms(),this.reportInterval=setInterval(()=>this.report(),15e3)}observeNavigation(){const t=history.pushState,e=history.replaceState,n=this;history.pushState=function(e,s,i){t.call(this,e,s,i),n.onPageTransition()},history.replaceState=function(t,s,i){e.call(this,t,s,i),n.onPageTransition()},window.addEventListener("popstate",()=>this.onPageTransition())}onPageTransition(){const t=Date.now(),e=window.location.href;e!==this.lastPageUrl&&(this.pageTransitions.push(t),this.lastPageUrl=e)}observeForms(){document.addEventListener("focus",t=>{const e=t.target;if("INPUT"===e.tagName||"TEXTAREA"===e.tagName||"SELECT"===e.tagName){const t=e.closest("form"),n=(null==t?void 0:t.id)||(null==t?void 0:t.action)||"anonymous_form";this.formStartTimes.has(n)||this.formStartTimes.set(n,Date.now())}},{capture:!0}),document.addEventListener("submit",t=>{const e=t.target,n=e.id||e.action||"anonymous_form",s=this.formStartTimes.get(n);if(s){const t=Date.now()-s;this.transmitter.send("session_metrics",{type:"form_completion",formId:n,duration:t,timestamp:Date.now()}),this.formStartTimes.delete(n)}},{capture:!0})}report(){const t=Date.now(),e=t-this.sessionStart;if(this.interactionTimestamps.length<10)return;const n=this.calculateIntervals(this.interactionTimestamps),s=this.analyzeTimingDistribution(n),i=this.analyzePageTransitions();this.transmitter.send("session_metrics",{type:"session_analysis",sessionDuration:e,totalInteractions:this.interactionTimestamps.length,pageTransitions:this.pageTransitions.length,timing:s,pages:i,timestamp:t})}calculateIntervals(t){const e=[];for(let n=1;n<t.length;n++)e.push(t[n]-t[n-1]);return e}analyzeTimingDistribution(t){if(t.length<5)return{samples:t.length};const e=t.reduce((t,e)=>t+e,0)/t.length,n=t.reduce((t,n)=>t+Math.pow(n-e,2),0)/t.length,s=Math.sqrt(n),i=e>0?s/e:0,r=this.shannonEntropy(t,50),a=this.autocorrelation(t);return{mean:Math.round(e),stdDev:Math.round(s),cv:parseFloat(i.toFixed(4)),entropy:parseFloat(r.toFixed(4)),autocorrelation:parseFloat(a.toFixed(4)),samples:t.length}}analyzePageTransitions(){if(this.pageTransitions.length<2)return{count:this.pageTransitions.length};const t=this.calculateIntervals(this.pageTransitions),e=t.reduce((t,e)=>t+e,0)/t.length,n=t.reduce((t,n)=>t+Math.pow(n-e,2),0)/t.length,s=e>0?Math.sqrt(n)/e:0;return{count:this.pageTransitions.length,avgInterval:Math.round(e),cv:parseFloat(s.toFixed(4))}}shannonEntropy(t,e){const n=new Map;for(const r of t){const t=Math.floor(r/e);n.set(t,(n.get(t)||0)+1)}const s=t.length;let i=0;for(const r of n.values()){const t=r/s;t>0&&(i-=t*Math.log2(t))}return i}autocorrelation(t){if(t.length<3)return 0;const e=t.reduce((t,e)=>t+e,0)/t.length;let n=0,s=0;for(let i=0;i<t.length-1;i++)n+=(t[i]-e)*(t[i+1]-e);for(let i=0;i<t.length;i++)s+=Math.pow(t[i]-e,2);return 0===s?0:n/s}}class v{constructor(t){n(this,"transmitter"),n(this,"tabTimestamps",[]),n(this,"shiftTabCount",0),n(this,"tabCount",0),n(this,"isShiftDown",!1),n(this,"BURST_THRESHOLD_MS",80),n(this,"reportInterval",null),n(this,"REPORT_INTERVAL_MS",1e4),n(this,"MIN_TABS_TO_REPORT",5),n(this,"TAB_TRIGGER_COUNT",20),n(this,"onKeyDown",t=>{if("Shift"!==t.key){if("Tab"===t.key){const t=Date.now();this.isShiftDown?this.shiftTabCount++:(this.tabCount++,this.tabTimestamps.push(t),this.tabTimestamps.length>100&&this.tabTimestamps.shift()),this.tabCount+this.shiftTabCount>=this.TAB_TRIGGER_COUNT&&this.report()}}else this.isShiftDown=!0}),n(this,"onKeyUp",t=>{"Shift"===t.key&&(this.isShiftDown=!1)}),this.transmitter=t}start(){"undefined"!=typeof document&&(document.addEventListener("keydown",this.onKeyDown,{passive:!0,capture:!0}),document.addEventListener("keyup",this.onKeyUp,{passive:!0,capture:!0}),this.reportInterval=setInterval(()=>this.report(),this.REPORT_INTERVAL_MS))}stop(){"undefined"!=typeof document&&(document.removeEventListener("keydown",this.onKeyDown,{capture:!0}),document.removeEventListener("keyup",this.onKeyUp,{capture:!0}),this.reportInterval&&(clearInterval(this.reportInterval),this.reportInterval=null),this.report())}report(){const t=this.tabCount+this.shiftTabCount;if(t<this.MIN_TABS_TO_REPORT)return;const e=this.calculateIntervals(this.tabTimestamps);if(e.length<3)return void this.resetBuffers();const n=this.analyzeIntervals(e),s=this.analyzeBursts(e),i=t>0?this.shiftTabCount/t:0;this.transmitter.send("tab_navigation_metrics",{tabCount:this.tabCount,shiftTabCount:this.shiftTabCount,shiftTabRatio:parseFloat(i.toFixed(4)),intervals:n,bursts:s,timestamp:Date.now()}),this.resetBuffers()}resetBuffers(){this.tabTimestamps=[],this.tabCount=0,this.shiftTabCount=0}calculateIntervals(t){const e=[];for(let n=1;n<t.length;n++){const s=t[n]-t[n-1];s<5e3&&e.push(s)}return e}analyzeIntervals(t){if(0===t.length)return{avg:0,variance:0,cv:0,min:0,samples:0};const e=t.reduce((t,e)=>t+e,0)/t.length,n=t.reduce((t,n)=>t+Math.pow(n-e,2),0)/t.length,s=Math.sqrt(n),i=e>0?s/e:0,r=Math.min(...t);return{avg:parseFloat(e.toFixed(2)),variance:parseFloat(n.toFixed(2)),cv:parseFloat(i.toFixed(4)),min:r,samples:t.length}}analyzeBursts(t){let e=0,n=0,s=0,i=0,r=0;for(const a of t)a<this.BURST_THRESHOLD_MS?(n++,i+=a,r++):(n>=3&&(e++,s+=n),n=0);return n>=3&&(e++,s+=n),{count:e,avgLength:e>0?parseFloat((s/e).toFixed(1)):0,avgInterval:r>0?parseFloat((i/r).toFixed(2)):0}}}class b{constructor(t){n(this,"transmitter"),n(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2e3))}async detect(){try{const t=this.analyzeGPU(),e=this.analyzeHardware(),n=this.analyzeScreen(),s=await this.analyzeMedia(),i=this.benchmarkCanvas();let r=0;"virtual_gpu"!==t.category&&"software_render"!==t.category&&"cloud_gpu"!==t.category||(r+=2),e.cores<=2&&r++,null!==e.memory&&e.memory<=2&&r++,24===e.colorDepth&&r++,1===e.pixelRatio&&r++,n.noTaskbar&&r++,n.isVMResolution&&r++,0===s.cameras&&0===s.microphones&&r++,s.hasBluetooth||s.hasUSB||r++,i.canvasRenderTime>50&&r++;const{classification:a,confidence:o}=this.classify(t,e,r);this.transmitter.send("cloud_environment",{classification:a,confidence:o,signals:{gpu:{renderer:t.renderer,vendor:t.vendor,category:t.category},hardware:e,screen:n,media:s,performance:i},vmIndicatorCount:r,timestamp:Date.now()})}catch(t){}}analyzeGPU(){try{const t=document.createElement("canvas"),e=t.getContext("webgl")||t.getContext("experimental-webgl");if(!e)return{renderer:"unavailable",vendor:"unavailable",category:"unknown"};const n=e.getExtension("WEBGL_debug_renderer_info");if(!n)return{renderer:"no_debug_info",vendor:"no_debug_info",category:"unknown"};const s=e.getParameter(n.UNMASKED_RENDERER_WEBGL)||"",i=e.getParameter(n.UNMASKED_VENDOR_WEBGL)||"";return{renderer:s,vendor:i,category:this.categorizeGPU(s,i)}}catch(t){return{renderer:"error",vendor:"error",category:"unknown"}}}categorizeGPU(t,e){const n=t.toLowerCase(),s=e.toLowerCase();return/swiftshader|llvmpipe|mesa offscreen|softpipe/.test(n)?"software_render":/svga3d|svga|vmware/.test(n)||/virtualbox/.test(n)||/parallels/.test(n)||/qxl|virtio|red hat|spice/.test(n)||/hyper-v|microsoft basic render/i.test(n)||/citrix/.test(n)?"virtual_gpu":/amazon|elastic|aws/.test(n)||/amazon|elastic|aws/.test(s)||/google cloud|gce/.test(n)||/google cloud|gce/.test(s)||/azure/.test(n)||/azure/.test(s)?"cloud_gpu":"physical"}analyzeHardware(){return{cores:navigator.hardwareConcurrency||0,memory:navigator.deviceMemory??null,colorDepth:screen.colorDepth,pixelRatio:window.devicePixelRatio||1}}analyzeScreen(){const t=screen.width,e=screen.height,n=screen.availHeight,s=e===n&&e===window.innerHeight,i=[[800,600],[1024,768],[1280,1024],[1280,800],[1920,1080]].some(([n,s])=>t===n&&e===s&&!(1920===n&&1080===s));return{width:t,height:e,availHeight:n,noTaskbar:s,isVMResolution:i}}async analyzeMedia(){let t=-1,e=-1;try{if(navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices){const n=await navigator.mediaDevices.enumerateDevices();t=n.filter(t=>"videoinput"===t.kind).length,e=n.filter(t=>"audioinput"===t.kind).length}}catch(r){}const n=!!navigator.bluetooth,s=!!navigator.usb;let i=null;try{if(navigator.getBattery){const t=await navigator.getBattery();i=!(t.charging&&1===t.level&&0===t.chargingTime)}}catch(r){}return{cameras:t,microphones:e,hasBluetooth:n,hasUSB:s,hasBattery:i}}benchmarkCanvas(){try{const t=document.createElement("canvas");t.width=200,t.height=200;const e=t.getContext("2d");if(!e)return{canvasRenderTime:-1};const n=performance.now();for(let i=0;i<500;i++)e.fillStyle=`rgb(${i%256},${3*i%256},${7*i%256})`,e.fillRect(13*i%200,7*i%200,10,10);e.getImageData(0,0,1,1);const s=performance.now()-n;return{canvasRenderTime:Math.round(100*s)/100}}catch(t){return{canvasRenderTime:-1}}}classify(t,e,n){return"virtual_gpu"===t.category?24===e.colorDepth?{classification:"rdp_likely",confidence:.85}:{classification:"vm_detected",confidence:.95}:"cloud_gpu"===t.category?{classification:"cloud_likely",confidence:.9}:"software_render"===t.category?{classification:"vm_detected",confidence:.9}:n>=5?{classification:"vm_likely",confidence:.8}:n>=3?{classification:"vm_likely",confidence:.6}:{classification:"physical",confidence:1-.1*n}}}class _{constructor(t){n(this,"transmitter"),n(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2500))}async detect(){var t,e;const n={};let s=0;const i={webdriver:!!navigator.webdriver,languages:(null==(t=navigator.languages)?void 0:t.join(","))||"",platform:navigator.platform||"",hardwareConcurrency:navigator.hardwareConcurrency||0,userAgent:navigator.userAgent||"",pluginsLength:(null==(e=navigator.plugins)?void 0:e.length)??0},r=this.checkIframe(i);r.score>0&&(n.iframe=r.mismatches,s+=r.score);try{const t=await this.checkWorker(i);t.score>0&&(n.worker=t.mismatches,s+=t.score)}catch(a){}s>0&&this.transmitter.send("cross_context_mismatch",{signals:n,score:s,timestamp:Date.now()})}checkIframe(t){var e,n;const s=[];let i=0;try{const r=document.createElement("iframe");r.style.display="none",r.sandbox="allow-same-origin",document.body.appendChild(r);const a=r.contentWindow;if(!a)return document.body.removeChild(r),{score:0,mismatches:[]};const o=a.navigator;o.webdriver!==navigator.webdriver&&(s.push("webdriver_mismatch"),i+=40),navigator.webdriver||!0!==o.webdriver||(s.push("webdriver_spoofed_in_main"),i+=30);((null==(e=o.languages)?void 0:e.join(","))||"")!==t.languages&&(s.push("languages_mismatch"),i+=15),o.platform!==t.platform&&(s.push("platform_mismatch"),i+=15);((null==(n=o.plugins)?void 0:n.length)??0)!==t.pluginsLength&&(s.push("plugins_mismatch"),i+=10),document.body.removeChild(r)}catch(r){}return{score:i,mismatches:s}}checkWorker(t){return new Promise(e=>{try{const n=new Blob(["\n self.onmessage = function() {\n var nav = self.navigator;\n self.postMessage({\n webdriver: !!nav.webdriver,\n languages: (nav.languages || []).join(','),\n platform: nav.platform || '',\n hardwareConcurrency: nav.hardwareConcurrency || 0,\n userAgent: nav.userAgent || ''\n });\n };\n "],{type:"application/javascript"}),s=URL.createObjectURL(n),i=new Worker(s),r=setTimeout(()=>{i.terminate(),URL.revokeObjectURL(s),e({score:0,mismatches:[]})},3e3);i.onmessage=n=>{clearTimeout(r),i.terminate(),URL.revokeObjectURL(s);const a=n.data,o=[];let c=0;a.webdriver!==t.webdriver&&(o.push("worker_webdriver_mismatch"),c+=35),a.languages!==t.languages&&(o.push("worker_languages_mismatch"),c+=15),a.platform!==t.platform&&(o.push("worker_platform_mismatch"),c+=15),a.hardwareConcurrency!==t.hardwareConcurrency&&(o.push("worker_concurrency_mismatch"),c+=10),a.userAgent!==t.userAgent&&(o.push("worker_ua_mismatch"),c+=20),e({score:c,mismatches:o})},i.onerror=()=>{clearTimeout(r),i.terminate(),URL.revokeObjectURL(s),e({score:0,mismatches:[]})},i.postMessage("check")}catch(n){e({score:0,mismatches:[]})}})}}class T{constructor(t){n(this,"transmitter"),n(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2e3))}async detect(){const t={};let e=0;const n=await this.checkBrokenImage();n.suspicious&&(t.brokenImage=n,e+=25);const s=await this.checkClientHints();s.suspicious&&(t.clientHints=s,e+=20);const i=this.checkCDPMouseSignature();i.suspicious&&(t.cdpMouse=i,e+=30);const r=this.checkHairlineSupport();r.suspicious&&(t.hairline=r,e+=10);const a=this.checkExtraFrameworks();a.length>0&&(t.extraFrameworks=a,e+=20);(await this.checkWorkerCDP()).suspicious&&(t.workerCDP=!0,e+=35),e>0&&this.transmitter.send("headless_probe",{signals:t,score:e,timestamp:Date.now()})}checkBrokenImage(){return new Promise(t=>{try{const e=document.createElement("img");e.src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==___invalid";const n=setTimeout(()=>{t({suspicious:!1,width:-1,height:-1})},2e3);e.onerror=()=>{clearTimeout(n);const s=e.width,i=e.height;t({suspicious:0===s&&0===i,width:s,height:i})},e.onload=()=>{clearTimeout(n),t({suspicious:!1,width:e.width,height:e.height})},e.style.position="absolute",e.style.left="-9999px",document.body.appendChild(e),setTimeout(()=>{try{document.body.removeChild(e)}catch(t){}},100)}catch(e){t({suspicious:!1,width:-1,height:-1})}})}async checkClientHints(){const t=[];try{const e=navigator.userAgentData;if(!e)return{suspicious:!1,mismatches:[]};const n=navigator.userAgent,s=(e.brands||[]).map(t=>t.brand);/Chrome\/\d/.test(n)&&!s.some(t=>/Chromium|Google Chrome|Chrome/.test(t))&&t.push("ua_chrome_no_brand"),e.platform&&(/Windows/.test(n)&&"Windows"!==e.platform&&t.push("ua_windows_brand_mismatch"),/Macintosh/.test(n)&&"macOS"!==e.platform&&t.push("ua_mac_brand_mismatch"),/Linux/.test(n)&&!/Linux|Android|ChromeOS/.test(e.platform)&&t.push("ua_linux_brand_mismatch")),/Mobile/.test(n)&&!1===e.mobile&&t.push("ua_mobile_brand_mismatch")}catch(e){}return{suspicious:t.length>0,mismatches:t}}checkCDPMouseSignature(){let t=0,e=0,n=!1;try{const s=[],i=n=>{s.push(n),e++,0===n.movementX&&0===n.movementY&&t++};document.addEventListener("mousemove",i,{passive:!0}),setTimeout(()=>{document.removeEventListener("mousemove",i)},5e3),e>10&&t/e>.9&&(n=!0)}catch(s){}return{suspicious:n,zeroMovementCount:t,totalEvents:e}}checkHairlineSupport(){try{const t=document.createElement("div");t.style.border=".5px solid transparent",t.style.position="absolute",t.style.left="-9999px",document.body.appendChild(t);const e=t.offsetHeight;return document.body.removeChild(t),{suspicious:0===e,offsetHeight:e}}catch(t){return{suspicious:!1,offsetHeight:-1}}}checkExtraFrameworks(){const t=[];try{const n=window.external;if(n&&"function"==typeof n.toString)try{const e=n.toString();/Sequentum/i.test(e)&&t.push("sequentum")}catch(e){}const s=["__webdriver_script_fn","__webdriver_script_func","__webdriver_evaluate","__selenium_evaluate","__fxdriver_evaluate","__driver_evaluate","__webdriver_unwrapped","__selenium_unwrapped","__fxdriver_unwrapped","__driver_unwrapped","_Selenium_IDE_Recorder","_selenium","calledSelenium","_WEBDRIVER_ELEM_CACHE","ChromeDriverw","driver-hierarchical","__$webdriverAsyncExecutor","__lastWatirAlert","__lastWatirConfirm","__lastWatirPrompt","_WEBDRIVER_ELEM_CACHE","webdriver","_phantom","__nightmare","_selenium"];for(const e of s)(e in document||e in window)&&t.push(`global_${e}`);const i=Object.getOwnPropertyNames(navigator);for(const e of i)/webdriver|selenium|puppeteer|playwright|phantom/i.test(e)&&t.push(`nav_${e}`)}catch(e){}return t}checkWorkerCDP(){return new Promise(t=>{try{const e=new Blob(["\n self.onmessage = function() {\n var detected = false;\n try {\n var marker = {};\n Object.defineProperty(marker, 'stack', {\n get: function() { detected = true; return ''; }\n });\n console.debug(marker);\n } catch(e) {}\n self.postMessage({ cdp: detected });\n };\n "],{type:"application/javascript"}),n=URL.createObjectURL(e),s=new Worker(n),i=setTimeout(()=>{s.terminate(),URL.revokeObjectURL(n),t({suspicious:!1})},3e3);s.onmessage=e=>{clearTimeout(i),s.terminate(),URL.revokeObjectURL(n),t({suspicious:!0===e.data.cdp})},s.onerror=()=>{clearTimeout(i),s.terminate(),URL.revokeObjectURL(n),t({suspicious:!1})},s.postMessage("check")}catch(e){t({suspicious:!1})}})}}class k{constructor(t){n(this,"transmitter"),n(this,"hasRun",!1),n(this,"injectedScriptCount",0),n(this,"cspViolations",[]),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,this.startDOMObserver(),this.startCSPMonitor(),setTimeout(()=>this.detect(),1500))}detect(){const t={};let e=0;try{const n=this.checkNativeFunctionIntegrity();n.issues.length>0&&(t.nativeFunctionIntegrity=n.issues,e+=25)}catch(n){}try{const n=this.checkPropertyOverrides();n.issues.length>0&&(t.propertyOverrides=n.issues,e+=30)}catch(n){}this.injectedScriptCount>0&&(t.domScriptInjection={count:this.injectedScriptCount},e+=20),this.cspViolations.length>0&&(t.cspViolations=this.cspViolations.slice(0,10),e+=15);try{const n=this.checkGlobalPollution();n.length>0&&(t.globalPollution=n,e+=20)}catch(n){}try{const n=this.checkPrototypeIntegrity();n.length>0&&(t.prototypeIntegrity=n,e+=20)}catch(n){}e>0&&this.transmitter.send("script_injection",{signals:t,score:e,timestamp:Date.now()})}checkNativeFunctionIntegrity(){const t=[];try{const e=Object.getOwnPropertyDescriptor(navigator,"webdriver");if(e&&(!0===e.configurable&&t.push("webdriver_descriptor_configurable"),e.get)){const n=Function.prototype.toString.call(e.get);/\[native code\]/.test(n)||t.push("webdriver_non_native_getter")}}catch(e){}try{const e=["userAgent","platform","languages","hardwareConcurrency"];for(const n of e){const e=Object.getOwnPropertyDescriptor(Navigator.prototype,n);if(e&&e.get){const s=Function.prototype.toString.call(e.get);/\[native code\]/.test(s)||t.push(`navigator_${n}_non_native`)}}}catch(e){}try{const e=Function.prototype.toString.call(Function.prototype.toString);/\[native code\]/.test(e)||t.push("function_tostring_overridden")}catch(e){}return{issues:t}}checkPropertyOverrides(){const t=[];try{"[object Navigator]"!==Object.prototype.toString.call(navigator)&&t.push("navigator_proxy_or_spoofed")}catch(e){}try{if(navigator.plugins){"[object PluginArray]"!==Object.prototype.toString.call(navigator.plugins)&&t.push("plugins_spoofed"),Array.isArray(navigator.plugins)&&t.push("plugins_is_array")}}catch(e){}try{if(navigator.mimeTypes){"[object MimeTypeArray]"!==Object.prototype.toString.call(navigator.mimeTypes)&&t.push("mimetypes_spoofed")}}catch(e){}try{const e=Function.prototype.toString.call(Object.getOwnPropertyDescriptor);/\[native code\]/.test(e)||t.push("getOwnPropertyDescriptor_overridden")}catch(e){}return{issues:t}}startDOMObserver(){try{if("undefined"==typeof MutationObserver)return;const t=new MutationObserver(t=>{for(const e of t)for(let t=0;t<e.addedNodes.length;t++){const n=e.addedNodes[t];if("SCRIPT"===n.nodeName){n.src||this.injectedScriptCount++}}});t.observe(document.documentElement,{childList:!0,subtree:!0}),setTimeout(()=>{try{t.disconnect()}catch(e){}},1e4)}catch(t){}}startCSPMonitor(){try{const t=t=>{try{const e=`${t.violatedDirective}|${t.blockedURI||"inline"}`;this.cspViolations.push(e)}catch(e){}};document.addEventListener("securitypolicyviolation",t),setTimeout(()=>{try{document.removeEventListener("securitypolicyviolation",t)}catch(e){}},1e4)}catch(t){}}checkGlobalPollution(){const t=[],e=window,n=document,s=[["__webdriver_evaluate",()=>!!n.__webdriver_evaluate],["__selenium_evaluate",()=>!!n.__selenium_evaluate],["__webdriver_script_function",()=>!!n.__webdriver_script_function],["__webdriver_script_func",()=>!!n.__webdriver_script_func],["__webdriver_script_fn",()=>!!n.__webdriver_script_fn],["_Selenium_IDE_Recorder",()=>!!e._Selenium_IDE_Recorder],["__lastWatirAlert",()=>!!e.__lastWatirAlert],["__lastWatirConfirm",()=>!!e.__lastWatirConfirm],["__lastWatirPrompt",()=>!!e.__lastWatirPrompt],["_phantom",()=>!!e._phantom],["callPhantom",()=>!!e.callPhantom],["__nightmare",()=>!!e.__nightmare],["Buffer",()=>"function"==typeof e.Buffer&&"function"==typeof e.Buffer.alloc],["process",()=>!!e.process&&!!e.process.versions],["global_redefined",()=>!!e.global&&e.global!==e&&"object"==typeof e.global],["window_emit",()=>"function"==typeof e.emit]];for(const[r,a]of s)try{a()&&t.push(r)}catch(i){}try{const e=Object.keys(document);for(const n of e)/^cdc_|^__cdc_/.test(n)&&t.push(`cdc:${n}`)}catch(i){}try{const e=Object.keys(window);for(const n of e)/^cdc_|^__cdc_/.test(n)&&t.push(`cdc_window:${n}`)}catch(i){}return t}checkPrototypeIntegrity(){const t=[];try{const e=HTMLElement.prototype,n=Object.getOwnPropertyNames(e);for(const s of n)/^__selenium|^__webdriver|^__playwright|^__puppeteer/.test(s)&&t.push(`htmlelement_proto_${s}`)}catch(e){}try{const e=document.createElement("div");e instanceof HTMLDivElement||t.push("createElement_not_genuine");"[object HTMLDivElement]"!==Object.prototype.toString.call(e)&&t.push("createElement_wrong_tostring")}catch(e){}try{const e=new Event("test");e instanceof Event||t.push("event_not_instance");"[object Event]"!==Object.prototype.toString.call(e)&&t.push("event_wrong_prototype")}catch(e){}try{const e=Function.prototype.toString.call(document.createElement);/\[native code\]/.test(e)||t.push("createElement_overridden")}catch(e){}return t}}class C{constructor(t){n(this,"transmitter"),n(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2e3))}async detect(){try{if("undefined"==typeof Worker||"undefined"==typeof Blob)return;const e={webdriver:!!navigator.webdriver,userAgent:navigator.userAgent||"",platform:navigator.platform||"",languages:JSON.stringify(navigator.languages||[]),hardwareConcurrency:navigator.hardwareConcurrency||0,dateNow:Date.now(),perfNow:performance.now(),toStringNative:!1};try{e.toStringNative=/\[native code\]/.test(Function.prototype.toString.call(Array.prototype.push))}catch(t){e.toStringNative=!1}const n=await this.runWorker(e);if(!n)return;const s={};let i=0;const r=[];e.webdriver||!0!==n.webdriver?n.webdriver!==e.webdriver&&(r.push("webdriver_mismatch"),i+=30):(r.push("webdriver_spoofed"),i+=40),n.userAgent!==e.userAgent&&(r.push("userAgent_mismatch"),i+=30),n.platform!==e.platform&&(r.push("platform_mismatch"),i+=30),n.languages!==e.languages&&(r.push("languages_mismatch"),i+=30),n.hardwareConcurrency!==e.hardwareConcurrency&&(r.push("hardwareConcurrency_mismatch"),i+=30),r.length>0&&(s.navigatorMismatch=r);const a=n.benchmarkMs;"number"==typeof a&&(a<1||a>500)&&(s.benchmarkAnomaly={benchmarkMs:a,reason:a<1?"abnormally_fast":"abnormally_slow"},i+=20),!1===n.cryptoEntropy&&(s.cryptoMock={entropy:!1,values:n.cryptoValues},i+=15);const o=Math.abs(n.dateNow-e.dateNow);if(o>1e3&&(s.timeManipulation={mainDateNow:e.dateNow,workerDateNow:n.dateNow,deltaMs:o},i+=15),!n.toStringNative||!e.toStringNative){const t=[];n.toStringNative||t.push("worker_tampered"),e.toStringNative||t.push("main_tampered"),s.toStringTampering=t,i+=20}i>0&&this.transmitter.send("worker_integrity",{signals:s,score:i,timestamp:Date.now()})}catch(t){}}runWorker(t){return new Promise(e=>{try{const n=new Blob(["\n self.onmessage = function(e) {\n var results = {};\n\n // 1. Navigator check\n try {\n results.webdriver = !!navigator.webdriver;\n results.userAgent = navigator.userAgent || '';\n results.platform = navigator.platform || '';\n results.languages = JSON.stringify(navigator.languages || []);\n results.hardwareConcurrency = navigator.hardwareConcurrency || 0;\n } catch(ex) {\n results.webdriver = false;\n results.userAgent = '';\n results.platform = '';\n results.languages = '[]';\n results.hardwareConcurrency = 0;\n }\n\n // 2. Performance benchmark\n try {\n var start = performance.now();\n var sum = 0;\n for (var i = 0; i < 1000000; i++) sum += i;\n results.benchmarkMs = performance.now() - start;\n } catch(ex) {\n results.benchmarkMs = -1;\n }\n\n // 3. Crypto check\n try {\n var arr = new Uint32Array(4);\n crypto.getRandomValues(arr);\n results.cryptoEntropy = arr[0] !== arr[1] && arr[1] !== arr[2] && arr[0] !== 0;\n results.cryptoValues = Array.from(arr);\n } catch(ex) {\n results.cryptoEntropy = false;\n results.cryptoValues = [];\n }\n\n // 4. Time check\n results.dateNow = Date.now();\n results.perfNow = performance.now();\n\n // 5. toString integrity\n try {\n results.toStringNative = /\\[native code\\]/.test(\n Function.prototype.toString.call(Array.prototype.push)\n );\n } catch(ex) {\n results.toStringNative = false;\n }\n\n self.postMessage(results);\n };\n "],{type:"application/javascript"}),s=URL.createObjectURL(n),i=new Worker(s),r=setTimeout(()=>{i.terminate(),URL.revokeObjectURL(s),e(null)},5e3);i.onmessage=t=>{clearTimeout(r),i.terminate(),URL.revokeObjectURL(s),e(t.data)},i.onerror=()=>{clearTimeout(r),i.terminate(),URL.revokeObjectURL(s),e(null)},i.postMessage({mainValues:t})}catch(n){e(null)}})}}const E="__aie_token";class S{constructor(t){n(this,"config"),n(this,"renewTimer",null),n(this,"verified",!1),this.config=t}async start(){const t=this.getToken();if(t&&!this.isExpired(t))return this.verified=!0,this.scheduleRenewal(t),this.revealContent(),this.config.debug,!0;this.hideContent();const e=await this.solveChallenge();return e?(this.verified=!0,this.revealContent()):this.config.insertHoneypot&&this.insertHoneypotData(),e}isVerified(){return this.verified}stop(){this.renewTimer&&(clearTimeout(this.renewTimer),this.renewTimer=null)}async solveChallenge(){try{const t=await fetch(`${this.config.apiBase}/crawl-protect/challenge`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":this.config.clientId}});if(!t.ok)return!1;const{id:e,challenges:n}=await t.json(),s=[];for(const c of n)if("math"===c.type){const t="add"===c.op?c.a+c.b:c.a*c.b;s.push(String(t))}else if("crypto"===c.type){const t=await this.sha256(c.nonce);s.push(t.slice(0,8))}const i=s.join(":"),r=await this.getFingerprint(),a=await fetch(`${this.config.apiBase}/crawl-protect/verify`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":this.config.clientId},body:JSON.stringify({id:e,solution:i,fingerprint:r}),credentials:"include"});if(!a.ok)return!1;const o=await a.json();return!(!o.success||!o.token)&&(this.setToken(o.token),this.scheduleRenewal(o.token),this.config.debug,!0)}catch(t){return this.config.debug,!1}}hideContent(){var t;if(null==(t=this.config.protectSelectors)?void 0:t.length)for(const e of this.config.protectSelectors){document.querySelectorAll(e).forEach(t=>{t.dataset.aieOrigDisplay=t.style.display,t.style.display="none"})}}revealContent(){var t;if(null==(t=this.config.protectSelectors)?void 0:t.length)for(const e of this.config.protectSelectors){document.querySelectorAll(e).forEach(t=>{t.style.display=t.dataset.aieOrigDisplay||"",delete t.dataset.aieOrigDisplay})}}insertHoneypotData(){const t=document.createElement("div");t.style.cssText="position:absolute;left:-9999px;top:-9999px;opacity:0;pointer-events:none;",t.setAttribute("aria-hidden","true"),t.innerHTML='\n <span class="price" data-aie-honeypot="1">₩999,999,999</span>\n <span class="stock" data-aie-honeypot="1">재고: 0개</span>\n <a href="mailto:honeypot@aientrophy.com" data-aie-honeypot="1">contact</a>\n ',document.body.appendChild(t)}getToken(){const t=document.cookie.match(new RegExp(`(?:^|; )${E}=([^;]*)`));return t?decodeURIComponent(t[1]):null}setToken(t){const e=new Date(Date.now()+18e5).toUTCString();document.cookie=`${E}=${encodeURIComponent(t)};path=/;expires=${e};SameSite=None;Secure`}isExpired(t){try{const[e]=t.split("."),n=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return Date.now()>n.exp}catch{return!0}}scheduleRenewal(t){try{const[e]=t.split("."),n=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/"))),s=n.exp-3e5-Date.now();s>0&&(this.renewTimer=setTimeout(()=>this.solveChallenge(),s))}catch{}}async sha256(t){const e=new TextEncoder,n=await crypto.subtle.digest("SHA-256",e.encode(t));return Array.from(new Uint8Array(n)).map(t=>t.toString(16).padStart(2,"0")).join("")}async getFingerprint(){const t=[navigator.userAgent,navigator.language,screen.width+"x"+screen.height,Intl.DateTimeFormat().resolvedOptions().timeZone];return this.sha256(t.join("|"))}}const D=new class{constructor(){n(this,"transmitter"),n(this,"behaviorCollector"),n(this,"rapidClickDetector"),n(this,"honeypot"),n(this,"mouseTracker"),n(this,"canvasFingerprinter"),n(this,"inputTracker"),n(this,"challengeHandler"),n(this,"invisibleInteraction"),n(this,"automationDetector"),n(this,"sessionAnalyzer"),n(this,"tabNavigationAnalyzer"),n(this,"cloudEnvironmentDetector"),n(this,"crossContextDetector"),n(this,"headlessProbeDetector"),n(this,"scriptInjectionDetector"),n(this,"workerIntegrityDetector"),n(this,"crawlProtect",null),n(this,"initialized",!1),n(this,"wasmService"),n(this,"callbackManager"),this.transmitter=new o,this.wasmService=new p,this.callbackManager=new a,this.transmitter.setCallbackManager(this.callbackManager),this.behaviorCollector=new c(this.transmitter),this.rapidClickDetector=new l(this.transmitter),this.honeypot=new h(this.transmitter),this.mouseTracker=new u(this.transmitter,this.wasmService),this.canvasFingerprinter=new m(this.transmitter,this.wasmService),this.inputTracker=new d(this.transmitter),this.invisibleInteraction=new y(this.transmitter),this.automationDetector=new f(this.transmitter),this.sessionAnalyzer=new w(this.transmitter),this.tabNavigationAnalyzer=new v(this.transmitter),this.cloudEnvironmentDetector=new b(this.transmitter),this.crossContextDetector=new _(this.transmitter),this.headlessProbeDetector=new T(this.transmitter),this.scriptInjectionDetector=new k(this.transmitter),this.workerIntegrityDetector=new C(this.transmitter)}async init(t){var e,n;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 g(s),this.challengeHandler.setCallbackManager(this.callbackManager),!1!==(null==(e=t.serverConfig)?void 0:e.captchaEnabled)&&this.challengeHandler.start();((null==(n=t.serverConfig)?void 0:n.devtoolsDetection)??!t.debug)&&Promise.resolve().then(()=>P).then(({AntiDebug:t})=>{t.start(),t.setOnDevtoolsMaxed(()=>{this.transmitter.send("devtools_force_close",{reason:"devtools_threshold_exceeded",detectionCount:3,maxThreat:!0})}),Promise.resolve().then(()=>O).then(({ConsoleDetector:t})=>{new t(()=>{this.transmitter.send("devtools_open",{detected:!0})}).start()})}),t.crawlProtect&&(this.crawlProtect=new S({apiBase:s,clientId:t.clientKey,protectSelectors:t.crawlProtect.protectSelectors,insertHoneypot:t.crawlProtect.insertHoneypot,debug:t.debug}),this.crawlProtect.start().catch(e=>{t.debug})),this.initialized=!0,t.debug,this.callbackManager.emit("ready")}catch(i){this.callbackManager.emit("error",{code:"INIT_ERROR",message:"SecuritySDK initialization failed",details:null==i?void 0:i.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.behaviorCollector.start(),this.honeypot.start(),this.mouseTracker.start(),this.canvasFingerprinter.start(),this.inputTracker.start(),this.invisibleInteraction.start(),this.automationDetector.start(),this.sessionAnalyzer.start(),this.tabNavigationAnalyzer.start(),this.cloudEnvironmentDetector.start(),this.crossContextDetector.start(),this.headlessProbeDetector.start(),this.scriptInjectionDetector.start(),this.workerIntegrityDetector.start()}};"undefined"!=typeof window&&(window.SecuritySDK=D);const A={};let M=0;let R=!1,x=null;class I{static start(){this.saveConsole(),this.disableConsole(),this.preventDevTools(),this.blockDevToolsKeys()}static stop(){this.intervalId&&clearInterval(this.intervalId)}static setOnDevtoolsMaxed(t){x=t}static reportDevtoolsDetection(){R||(M++,M>=3&&(R=!0,this.handleDevtoolsMaxed()))}static getOriginalConsole(){return A}static handleDevtoolsMaxed(){if(x)try{x()}catch(t){}try{alert("개발자 도구가 탐지되었습니다.\n보안 정책에 의해 브라우저가 종료됩니다.")}catch(t){}try{document.documentElement.innerHTML=""}catch(t){}try{window.open("","_self"),window.close()}catch(t){}setTimeout(()=>{try{window.location.href="about:blank"}catch(t){}},100)}static saveConsole(){const t=["log","debug","info","warn","error","table","trace","dir","clear"];try{const e=window.console;if(!e)return;for(const n of t)"function"==typeof e[n]&&(A[n]=e[n].bind(e))}catch(e){}}static preventDevTools(){this.intervalId=setInterval(()=>{this.debuggerCheck()},this.checkInterval)}static debuggerCheck(){!function(){try{(function(){}).constructor("debugger")()}catch(t){}}()}static blockDevToolsKeys(){document.addEventListener("keydown",t=>{"F12"!==t.key?t.ctrlKey&&t.shiftKey&&["I","i","J","j","C","c"].includes(t.key)?t.preventDefault():!t.ctrlKey||"u"!==t.key&&"U"!==t.key||t.preventDefault():t.preventDefault()},!0)}static disableConsole(){const t=()=>{},e=["log","debug","info","warn","error","table","trace","dir"];try{const n=window.console;if(!n)return;for(const s of e)n[s]&&(n[s]=t)}catch(n){}}}n(I,"checkInterval",1e3),n(I,"intervalId");const P=Object.freeze(Object.defineProperty({__proto__:null,AntiDebug:I},Symbol.toStringTag,{value:"Module"}));const O=Object.freeze(Object.defineProperty({__proto__:null,ConsoleDetector:class{constructor(t){n(this,"onDetect"),n(this,"intervals",[]),n(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(),I.reportDevtoolsDetection(),setTimeout(()=>{this.detected=!1},2e3))}startGetterTrap(){const t=I.getOriginalConsole(),e=t.log,n=t.clear;if(!e)return;const s=document.createElement("div");Object.defineProperty(s,"id",{get:()=>(this.triggerDetect(),"")});const i=/./;i.toString=()=>(this.triggerDetect(),"");const r=setInterval(()=>{try{e(s),e(i),n&&n()}catch(t){}},1500);this.intervals.push(r)}startSizeDetection(){if(navigator.maxTouchPoints>0||/Mobile|Android|iPhone|iPad/i.test(navigator.userAgent))return;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=D,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,n=(t,n,s)=>((t,n,s)=>n in t?e(t,n,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[n]=s)(t,"symbol"!=typeof n?n+"":n,s);const s="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqbBCvDqyUtfhgI/Lo5pDtn1phwA6qczAyp8N1ZgQ68OTxgbJUGiXV6N67p15bBdME1R4va51P2Czq2IbRby/N+GHTciTaXvmusV8IjnIOGtKlGxWCuKIPrCS+rGjGA2j1irxBbNpqItltFxjhxBGOzsyQAF6LNIz5IKA7sC6cSH8zUyLuFrV96udc801Zc4nCJG64ZljNbDvlVbJJZ6ex5OLLS6AnrVAXpjEDR/MI/I8JvAPe/psHj6EpXgvKrBYMBOH3jzQRzMFoR79jXyGNgPjdy0A+f6RVuEG8H5sUXKeyy+cFvaT+pm6h+t6RPED11tCOwQxYZ2pExhhPxDGeQIDAQAB";class i{static async init(){if(!this.sessionKey)try{await this.initECDH()}catch(t){await this.initRSA()}}static async initECDH(){const t=await window.crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),e=await window.crypto.subtle.exportKey("raw",t.publicKey);this.ecdhPublicKeyBase64=this.arrayBufferToBase64(e);const n=(window.__securitySDKEndpoint||"").replace(/\/events$/,""),s=await fetch(`${n}/key-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientPublicKey:this.ecdhPublicKeyBase64})});if(!s.ok)throw new Error("Key exchange failed");const{serverPublicKey:i,salt:r}=await s.json(),a=this.base64ToArrayBuffer(i),o=await window.crypto.subtle.importKey("raw",a,{name:"ECDH",namedCurve:"P-256"},!1,[]),c=await window.crypto.subtle.deriveBits({name:"ECDH",public:o},t.privateKey,256),l=await window.crypto.subtle.importKey("raw",c,"HKDF",!1,["deriveKey"]),h=this.base64ToArrayBuffer(r);this.sessionKey=await window.crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:h,info:(new TextEncoder).encode("aientrophy-session-enc")},l,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),this.protocolVersion=2}static async initRSA(){this.sessionKey=await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]);const t=await this.importRSAPublicKey(s),e=await window.crypto.subtle.exportKey("raw",this.sessionKey),n=await window.crypto.subtle.encrypt({name:"RSA-OAEP"},t,e);this.encryptedSessionKey=this.arrayBufferToBase64(n),this.protocolVersion=1}static async encrypt(t){this.sessionKey||await this.init();const e=JSON.stringify(t),n=(new TextEncoder).encode(e),s=window.crypto.getRandomValues(new Uint8Array(12)),i=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.sessionKey,n),r=new Uint8Array(i),a=r.slice(0,r.length-16),o=r.slice(r.length-16),c={ek:2===this.protocolVersion?this.ecdhPublicKeyBase64:this.encryptedSessionKey,d:this.arrayBufferToBase64(a.buffer),iv:this.arrayBufferToBase64(s.buffer),tag:this.arrayBufferToBase64(o.buffer)};return 2===this.protocolVersion&&(c.v=2),c}static async decrypt(t){if(!this.sessionKey)throw new Error("Session key not initialized");const e=this.base64ToArrayBuffer(t.d),n=this.base64ToArrayBuffer(t.iv),s=this.base64ToArrayBuffer(t.tag),i=new Uint8Array(e.byteLength+s.byteLength);i.set(new Uint8Array(e),0),i.set(new Uint8Array(s),e.byteLength);const r=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:n},this.sessionKey,i),a=(new TextDecoder).decode(r);return JSON.parse(a)}static setEndpoint(t){window.__securitySDKEndpoint=t}static async importRSAPublicKey(t){const e=window.atob(t),n=this.str2ab(e);return await window.crypto.subtle.importKey("spki",n,{name:"RSA-OAEP",hash:"SHA-256"},!0,["encrypt"])}static str2ab(t){const e=new ArrayBuffer(t.length),n=new Uint8Array(e);for(let s=0,i=t.length;s<i;s++)n[s]=t.charCodeAt(s);return e}static arrayBufferToBase64(t){let e="";const n=new Uint8Array(t),s=n.byteLength;for(let i=0;i<s;i++)e+=String.fromCharCode(n[i]);return window.btoa(e)}static base64ToArrayBuffer(t){const e=window.atob(t),n=e.length,s=new Uint8Array(n);for(let i=0;i<n;i++)s[i]=e.charCodeAt(i);return s.buffer}}n(i,"sessionKey",null),n(i,"ecdhPublicKeyBase64",null),n(i,"encryptedSessionKey",null),n(i,"protocolVersion",2);const r=new Set(["rapid_click","honeypot_triggered","devtools_open","invisible_interaction","integrity_violation","dom_mutation","behavior_metrics","behavior_analysis","input_metrics","keystroke_dynamics","environmental_integrity","init_signals","automation_detected","cross_context_mismatch","headless_probe","script_injection","worker_integrity"]);class a{constructor(){n(this,"handlers",new Map),n(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 n=this.handlers.get(t);if(!n)return;const s=n.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 n=t.indexOf(":");if(-1!==n){const s=t.substring(0,n);this.callHandlers(s,e)}this.callConfigCallback(t,e)}emitChallenge(t){return new Promise(e=>{let n=!1;const s=t=>{n||(n=!0,e(t))},i=this.handlers.has("challenge")&&this.handlers.get("challenge").length>0,r=!!this.configCallbacks.onChallenge;i||r?(this.callHandlers("challenge",[t,s]),this.configCallbacks.onChallenge&&this.safeCall(this.configCallbacks.onChallenge,[t,s]),setTimeout(()=>{n||(n=!0,e(!1))},5e3)):e(!1)})}addHandler(t,e,n){this.handlers.has(t)||this.handlers.set(t,[]),this.handlers.get(t).push({handler:e,once:n})}callHandlers(t,e){const n=this.handlers.get(t);if(!n||0===n.length)return;const s=[];for(let i=0;i<n.length;i++)this.safeCall(n[i].handler,e),n[i].once&&s.push(i);for(let i=s.length-1;i>=0;i--)n.splice(s[i],1);0===n.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 n={ready:"onReady",error:"onError",block:"onBlock",allow:"onAllow"}[t];n&&this.configCallbacks[n]&&this.safeCall(this.configCallbacks[n],e)}safeCall(t,e){try{t(...e)}catch(n){}}}class o{constructor(){n(this,"endpoint",""),n(this,"clientKey",""),n(this,"encryptionRequired",!1),n(this,"currentNonce",""),n(this,"buffer",[]),n(this,"batchSize",20),n(this,"flushInterval",5e3),n(this,"intervalId"),n(this,"responseHandler",null),n(this,"callbackManager",null),n(this,"flushing",!1),n(this,"pendingFlush",!1),n(this,"backoffMs",0),n(this,"maxBackoffMs",6e4),n(this,"_lastBackoffStart",0),this.startFlushInterval()}setConfig(t){var e,n;this.endpoint=t.endpoint,this.clientKey=t.clientKey,this.encryptionRequired=(null==(e=t.serverConfig)?void 0:e.encryptionRequired)??!1,this.currentNonce=(null==(n=t.serverConfig)?void 0:n.initialNonce)??"",i.setEndpoint(t.endpoint)}setResponseHandler(t){this.responseHandler=t}setCallbackManager(t){this.callbackManager=t}send(t,e={}){const n=Date.now();if(this.buffer.push({type:t,data:e,timestamp:n}),this.callbackManager)if(r.has(t)){const s={type:t,data:e,timestamp:n};this.callbackManager.emit(`threat:${t}`,s)}else this.callbackManager.emit(`data:${t}`,{type:t,data:e,timestamp:n});this.buffer.length>=this.batchSize&&this.flush()}async flush(){if(0===this.buffer.length||!this.endpoint)return;if(this.backoffMs>0){const t=Date.now();if(this._lastBackoffStart||(this._lastBackoffStart=t),t-this._lastBackoffStart<this.backoffMs)return;this._lastBackoffStart=0}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 i.encrypt(t);s=JSON.stringify(e)}else s=JSON.stringify(t);const r={"Content-Type":"application/json","x-client-key":this.clientKey};this.currentNonce&&(r["x-request-nonce"]=this.currentNonce,this.currentNonce="");try{const n=await fetch(this.endpoint,{method:"POST",body:s,headers:r,keepalive:!0});if(429===n.status)return this.buffer=t.concat(this.buffer).slice(0,500),this.backoffMs=0===this.backoffMs?5e3:Math.min(2*this.backoffMs,this.maxBackoffMs),void(this._lastBackoffStart=Date.now());if(this.backoffMs=0,n.ok&&this.callbackManager&&this.callbackManager.emit("allow",{action:"allow"}),n.ok)try{const t=await n.json();let e=t;this.encryptionRequired&&(e=await i.decrypt(t)),(null==e?void 0:e.nonce)&&(this.currentNonce=e.nonce),this.responseHandler&&this.responseHandler(e)}catch(e){}}catch(n){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 c{constructor(t){n(this,"transmitter"),n(this,"isCollecting",!1),this.transmitter=t}start(){this.isCollecting||(this.isCollecting=!0)}stop(){this.isCollecting=!1}}class l{constructor(t){n(this,"transmitter"),n(this,"clickHistory",[]),n(this,"THRESHOLD_COUNT",3),n(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 n=t.target,s={tagName:n.tagName,id:n.id,className:n.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 h{constructor(t){n(this,"transmitter"),n(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)],n=Math.random().toString(36).substr(2,5);this.element.id="hp-"+Math.random().toString(36).substr(2,9),this.element.name=`${e}-${n}`,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){n(this,"transmitter"),n(this,"wasmService"),n(this,"buffer",[]),n(this,"BUFFER_SIZE",50),n(this,"SAMPLE_INTERVAL",100),n(this,"SEND_COOLDOWN",5e3),n(this,"lastSampleTime",0),n(this,"lastSendTime",0),n(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.buffer.length>=this.BUFFER_SIZE&&e-this.lastSendTime>=this.SEND_COOLDOWN&&(this.analyze(),this.lastSendTime=e))}),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<20)return;const t=this.wasmService.calculateEntropy(this.buffer),e=this.calculateSpeedVariance(),n=this.buffer.map(t=>({x:t.x,y:t.y,t:t.time}));this.transmitter.send("behavior_metrics",{entropy:t,speedVariance:e,sampleSize:this.buffer.length,timestamp:Date.now(),rawTrajectory:n})}calculateSpeedVariance(){const t=[];for(let n=1;n<this.buffer.length;n++){const e=this.buffer[n-1],s=this.buffer[n],i=Math.sqrt(Math.pow(s.x-e.x,2)+Math.pow(s.y-e.y,2)),r=s.time-e.time;r>0&&t.push(i/r)}if(t.length<2)return 1;const e=t.reduce((t,e)=>t+e,0)/t.length;return t.reduce((t,n)=>t+Math.pow(n-e,2),0)/t.length}}class d{constructor(t){n(this,"lastInteractionTime",0),n(this,"lastInteractionType","none"),n(this,"transmitter"),n(this,"isMobile",!1),n(this,"keyPressTimes",new Map),n(this,"lastKeyUpTime",0),n(this,"flightTimes",[]),n(this,"dwellTimes",[]),n(this,"suspiciousFocusCount",0),n(this,"suspiciousFocusResetTimer",null),n(this,"rawKeystrokes",[]),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.rawKeystrokes=[],this.lastKeyUpTime=0)},{capture:!0}),document.addEventListener("keydown",t=>{const e=t.target;if("INPUT"!==e.tagName&&"TEXTAREA"!==e.tagName)return;const n=Date.now();if(this.keyPressTimes.set(t.code,n),this.rawKeystrokes.push({code:t.code,t:n,type:"down"}),this.lastKeyUpTime>0){const t=n-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 n=Date.now();this.lastKeyUpTime=n,this.rawKeystrokes.push({code:t.code,t:n,type:"up"});const s=this.keyPressTimes.get(t.code);if(s){const e=n-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()<5e3||(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=0)}reportKeystrokeDynamics(t){const e=this.average(this.flightTimes),n=this.variance(this.flightTimes,e),s=this.average(this.dwellTimes),i=this.variance(this.dwellTimes,s);this.transmitter.send("input_metrics",{element:t.id||t.tagName,flight:{avg:e,variance:n,samples:this.flightTimes.length},dwell:{avg:s,variance:i},isMobile:this.isMobile,timestamp:Date.now(),rawKeystrokes:[...this.rawKeystrokes]}),this.flightTimes=[],this.dwellTimes=[],this.rawKeystrokes=[]}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,n)=>t+Math.pow(n-e,2),0)/t.length}}class p{constructor(){n(this,"wasmModule",null),n(this,"memory",null),n(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 n={env:{abort:()=>{}}};if(WebAssembly.instantiateStreaming){const t=await WebAssembly.instantiateStreaming(e,n);this.instance=t.instance}else{const t=await e.arrayBuffer(),s=await WebAssembly.instantiate(t,n);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,n=8*e;try{const s=this.wasmModule.__new(n,0),i=new Float64Array(this.memory.buffer,s,e);for(let e=0;e<t.length;e++)i[2*e]=t[e].x,i[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),n=e.length,s=this.wasmModule.__new(n,0);return new Uint8Array(this.memory.buffer,s,n).set(e),this.wasmModule.simpleHash(s,n)}catch(e){return 0}}}class m{constructor(t,e){n(this,"transmitter"),n(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof document||setTimeout(async()=>{const t=await this.generateFingerprint(),e=this.collectWebGLFingerprint(),n=this.collectAudioFingerprint();this.transmitter.send("fingerprint_collected",{hash:t,webgl:e,audio:n}),this.hasRun=!0},500)}async 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 n=t.toDataURL();return await this.sha256(n)}catch(t){return"error"}}async sha256(t){const e=(new TextEncoder).encode(t),n=await window.crypto.subtle.digest("SHA-256",e),s=new Uint8Array(n);return Array.from(s).map(t=>t.toString(16).padStart(2,"0")).join("")}collectWebGLFingerprint(){try{const t=document.createElement("canvas"),e=t.getContext("webgl")||t.getContext("experimental-webgl");if(!e)return{available:!1};const n=e,s={available:!0},i=n.getExtension("WEBGL_debug_renderer_info");return i&&(s.renderer=n.getParameter(i.UNMASKED_RENDERER_WEBGL),s.vendor=n.getParameter(i.UNMASKED_VENDOR_WEBGL)),s.maxTextureSize=n.getParameter(n.MAX_TEXTURE_SIZE),s.maxViewportDims=Array.from(n.getParameter(n.MAX_VIEWPORT_DIMS)),s.maxRenderbufferSize=n.getParameter(n.MAX_RENDERBUFFER_SIZE),s.maxVertexAttribs=n.getParameter(n.MAX_VERTEX_ATTRIBS),s.extensions=(n.getSupportedExtensions()||[]).length,s}catch(t){return{available:!1,error:!0}}}collectAudioFingerprint(){try{const t=window.AudioContext||window.webkitAudioContext;if(!t)return{available:!1};const e=new t,n={available:!0,sampleRate:e.sampleRate,state:e.state,maxChannels:e.destination.maxChannelCount};return e.close(),n}catch(t){return{available:!1}}}}class g{constructor(t){n(this,"originalFetch"),n(this,"endpoint"),n(this,"callbackManager",null),n(this,"challengeInProgress",null),this.endpoint=t,this.originalFetch=window.fetch.bind(window)}setCallbackManager(t){this.callbackManager=t}start(){window.fetch=async(t,e)=>{var n;const s=await this.originalFetch(t,e);if(403===s.status){const r=s.clone();try{const i=await r.json();if("challenge"===i.action&&"captcha"===(null==(n=i.metadata)?void 0:n.type)){const n={action:"challenge",score:i.score,metadata:i.metadata};if(this.callbackManager){if(await this.callbackManager.emitChallenge(n))return this.originalFetch(t,e)}this.challengeInProgress||(this.challengeInProgress=this.showCaptchaModal().finally(()=>{this.challengeInProgress=null}));return await this.challengeInProgress?this.originalFetch(t,e):s}"block"===i.action&&this.callbackManager&&this.callbackManager.emit("block",{action:"block",score:i.score,metadata:i.metadata})}catch(i){}}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 n=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 i=document.createElement("h3");i.textContent="Security Check",i.style.margin="0 0 16px 0";const r=document.createElement("p");r.textContent="Unusual activity detected. Please verify you are human.",r.style.marginBottom="16px",r.style.fontSize="14px",r.style.color="#666";const a=document.createElement("div");a.innerHTML="Loading...",a.style.marginBottom="16px";const o=document.createElement("input");o.type="text",o.placeholder="Enter details",o.style.padding="8px",o.style.marginRight="8px",o.style.border="1px solid #ddd",o.style.borderRadius="4px";const c=document.createElement("button");c.textContent="Verify",c.style.padding="8px 16px",c.style.background="#007bff",c.style.color="white",c.style.border="none",c.style.borderRadius="4px",c.style.cursor="pointer";const l=document.createElement("p");l.style.color="red",l.style.fontSize="12px",l.style.display="none",s.appendChild(i),s.appendChild(r),s.appendChild(a),s.appendChild(o),s.appendChild(c),s.appendChild(l),n.appendChild(s),document.body.appendChild(e);let h="";const u=async()=>{try{const t=await this.originalFetch(`${this.endpoint}/challenge`),e=await t.json();h=e.id,a.innerHTML=e.svg}catch(t){a.textContent="Error loading CAPTCHA"}},d=async()=>{l.style.display="none",c.textContent="Verifying...";try{const n=o.value,s=await this.originalFetch(`${this.endpoint}/challenge/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:h,answer:n})});(await s.json()).success?(document.body.removeChild(e),t(!0)):(l.textContent="Incorrect, try again.",l.style.display="block",c.textContent="Verify",o.value="",u())}catch(n){l.textContent="System error.",l.style.display="block",c.textContent="Verify"}};c.onclick=d,o.onkeydown=t=>{"Enter"===t.key&&d()},u()})}}class y{constructor(t){n(this,"transmitter"),n(this,"eventsToWatch",["click","mousedown","keydown","touchstart","focus"]),n(this,"handleEvent",t=>{const e=t.target;if(!(e&&e instanceof HTMLElement))return;if(e===document.body||e===document.documentElement)return;const n=this.checkVisibility(e,t);if(n){const s=e.getBoundingClientRect();this.transmitter.send("invisible_interaction",{type:t.type,target:e.tagName,id:e.id,reason:n,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 n,s;const i=window.getComputedStyle(t);if("none"===i.display)return"display:none";if("hidden"===i.visibility)return"visibility:hidden";if("0"===i.opacity)return"opacity:0";const r=t.getBoundingClientRect();if(r.width<=0||r.height<=0)return"zero_size";const a=r.right<0||r.left>window.innerWidth,o=r.bottom<0||r.top>window.innerHeight;if(a||o)return"off_screen";if(e instanceof MouseEvent||e instanceof TouchEvent){let i,r;if(e instanceof MouseEvent?(i=e.clientX,r=e.clientY):(i=(null==(n=e.touches[0])?void 0:n.clientX)||0,r=(null==(s=e.touches[0])?void 0:s.clientY)||0),i>=0&&i<=window.innerWidth&&r>=0&&r<=window.innerHeight){const n=document.elementFromPoint(i,r);if(n&&n!==t&&!t.contains(n)&&!n.contains(t)&&0===i&&0===r&&e.isTrusted)return null}}return null}}class f{constructor(t){n(this,"transmitter"),n(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(setTimeout(()=>this.detect(),1500),this.hasRun=!0)}detect(){var t,e;const n={};let s=0;!0===navigator.webdriver&&(n.webdriver=!0,s+=40);try{this.detectCDP()&&(n.cdp=!0,s+=50)}catch(c){}const i=this.detectAutomationGlobals();i.length>0&&(n.automationGlobals=i,s+=30);const r=this.checkWebGL();r.suspicious&&(n.webgl=r,s+=25);const a=this.checkInconsistencies();a.length>0&&(n.inconsistencies=a,s+=15);const o=this.checkHeadless();o.score>0&&(n.headless=o.flags,s+=o.score),s>0&&this.transmitter.send("automation_detected",{signals:n,score:s,timestamp:Date.now()}),this.transmitter.send("init_signals",{webdriver:!!navigator.webdriver,plugins:(null==(t=navigator.plugins)?void 0:t.length)??0,languages:(null==(e=navigator.languages)?void 0:e.length)??0,platform:navigator.platform,hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:navigator.deviceMemory,maxTouchPoints:navigator.maxTouchPoints,webglRenderer:r.renderer,webglVendor:r.vendor,timestamp:Date.now()})}detectCDP(){let t=!1;const e=console.debug;return console.debug=e,t}detectAutomationGlobals(){const t=[],e=[["selenium",()=>!!window._selenium],["selenium_unwrapped",()=>!!document.__selenium_unwrapped],["driver_evaluate",()=>!!document.__driver_evaluate],["webdriver_evaluate",()=>!!document.__webdriver_evaluate],["driver_unwrapped",()=>!!document.__driver_unwrapped],["fxdriver",()=>!!document.__fxdriver_evaluate],["playwright",()=>!!window.__playwright],["playwright_binding",()=>!!window.__playwright__binding__],["pwInitScripts",()=>!!window.__pwInitScripts],["puppeteer",()=>!!window.__puppeteer_evaluation_script__],["phantom",()=>!!window.callPhantom||!!window._phantom],["nightmare",()=>!!window.__nightmare],["cdc",()=>Object.keys(document).some(t=>t.startsWith("cdc_")||t.startsWith("$cdc_"))]];for(const[s,i]of e)try{i()&&t.push(s)}catch(n){}return t}checkWebGL(){try{const t=document.createElement("canvas"),e=t.getContext("webgl")||t.getContext("experimental-webgl");if(!e)return{suspicious:!1,renderer:"unavailable",vendor:"unavailable"};const n=e.getExtension("WEBGL_debug_renderer_info");if(!n)return{suspicious:!1,renderer:"no_debug_info",vendor:"no_debug_info"};const s=e.getParameter(n.UNMASKED_RENDERER_WEBGL)||"",i=e.getParameter(n.UNMASKED_VENDOR_WEBGL)||"";return{suspicious:/SwiftShader/i.test(s)||/Mesa OffScreen/i.test(s)||/llvmpipe/i.test(s),renderer:s,vendor:i}}catch(t){return{suspicious:!1,renderer:"error",vendor:"error"}}}checkInconsistencies(){const t=[];try{const e=navigator.userAgent,n=navigator.platform;/Windows/.test(e)&&/Mac/.test(n)&&t.push("ua_platform_mismatch_win_mac"),/Macintosh/.test(e)&&/Win/.test(n)&&t.push("ua_platform_mismatch_mac_win"),/Mobile|Android|iPhone/.test(e)&&0===navigator.maxTouchPoints&&t.push("mobile_ua_no_touch"),/Chrome/.test(e)&&navigator.plugins&&0===navigator.plugins.length&&t.push("chrome_no_plugins"),navigator.languages&&0!==navigator.languages.length||t.push("no_languages")}catch(e){}return t}checkHeadless(){const t=[];let e=0;try{if(/HeadlessChrome/.test(navigator.userAgent)&&(t.push("headless_ua"),e+=40),/Chrome/.test(navigator.userAgent)&&!window.chrome&&(t.push("chrome_ua_no_chrome_obj"),e+=15),window.screen&&800===window.screen.width&&600===window.screen.height&&(t.push("default_screen_size"),e+=10),"Notification"in window){"denied"===window.Notification.permission&&navigator.userAgent.includes("Chrome")&&(t.push("notification_denied_default"),e+=5)}const n=navigator.connection;n&&0===n.rtt&&(t.push("zero_rtt"),e+=10)}catch(n){}return{score:e,flags:t}}}class w{constructor(t){n(this,"transmitter"),n(this,"sessionStart",0),n(this,"pageTransitions",[]),n(this,"interactionTimestamps",[]),n(this,"lastPageUrl",""),n(this,"formStartTimes",new Map),n(this,"reportInterval",null),this.transmitter=t}start(){if("undefined"==typeof window)return;this.sessionStart=Date.now(),this.lastPageUrl=window.location.href;["mousedown","keydown","touchstart","scroll"].forEach(t=>{document.addEventListener(t,()=>{this.interactionTimestamps.push(Date.now()),this.interactionTimestamps.length>500&&this.interactionTimestamps.shift()},{passive:!0,capture:!0})}),this.observeNavigation(),this.observeForms(),this.reportInterval=setInterval(()=>this.report(),15e3)}observeNavigation(){const t=history.pushState,e=history.replaceState,n=this;history.pushState=function(e,s,i){t.call(this,e,s,i),n.onPageTransition()},history.replaceState=function(t,s,i){e.call(this,t,s,i),n.onPageTransition()},window.addEventListener("popstate",()=>this.onPageTransition())}onPageTransition(){const t=Date.now(),e=window.location.href;e!==this.lastPageUrl&&(this.pageTransitions.push(t),this.lastPageUrl=e)}observeForms(){document.addEventListener("focus",t=>{const e=t.target;if("INPUT"===e.tagName||"TEXTAREA"===e.tagName||"SELECT"===e.tagName){const t=e.closest("form"),n=(null==t?void 0:t.id)||(null==t?void 0:t.action)||"anonymous_form";this.formStartTimes.has(n)||this.formStartTimes.set(n,Date.now())}},{capture:!0}),document.addEventListener("submit",t=>{const e=t.target,n=e.id||e.action||"anonymous_form",s=this.formStartTimes.get(n);if(s){const t=Date.now()-s;this.transmitter.send("session_metrics",{type:"form_completion",formId:n,duration:t,timestamp:Date.now()}),this.formStartTimes.delete(n)}},{capture:!0})}report(){const t=Date.now(),e=t-this.sessionStart;if(this.interactionTimestamps.length<10)return;const n=this.calculateIntervals(this.interactionTimestamps),s=this.analyzeTimingDistribution(n),i=this.analyzePageTransitions();this.transmitter.send("session_metrics",{type:"session_analysis",sessionDuration:e,totalInteractions:this.interactionTimestamps.length,pageTransitions:this.pageTransitions.length,timing:s,pages:i,timestamp:t})}calculateIntervals(t){const e=[];for(let n=1;n<t.length;n++)e.push(t[n]-t[n-1]);return e}analyzeTimingDistribution(t){if(t.length<5)return{samples:t.length};const e=t.reduce((t,e)=>t+e,0)/t.length,n=t.reduce((t,n)=>t+Math.pow(n-e,2),0)/t.length,s=Math.sqrt(n),i=e>0?s/e:0,r=this.shannonEntropy(t,50),a=this.autocorrelation(t);return{mean:Math.round(e),stdDev:Math.round(s),cv:parseFloat(i.toFixed(4)),entropy:parseFloat(r.toFixed(4)),autocorrelation:parseFloat(a.toFixed(4)),samples:t.length}}analyzePageTransitions(){if(this.pageTransitions.length<2)return{count:this.pageTransitions.length};const t=this.calculateIntervals(this.pageTransitions),e=t.reduce((t,e)=>t+e,0)/t.length,n=t.reduce((t,n)=>t+Math.pow(n-e,2),0)/t.length,s=e>0?Math.sqrt(n)/e:0;return{count:this.pageTransitions.length,avgInterval:Math.round(e),cv:parseFloat(s.toFixed(4))}}shannonEntropy(t,e){const n=new Map;for(const r of t){const t=Math.floor(r/e);n.set(t,(n.get(t)||0)+1)}const s=t.length;let i=0;for(const r of n.values()){const t=r/s;t>0&&(i-=t*Math.log2(t))}return i}autocorrelation(t){if(t.length<3)return 0;const e=t.reduce((t,e)=>t+e,0)/t.length;let n=0,s=0;for(let i=0;i<t.length-1;i++)n+=(t[i]-e)*(t[i+1]-e);for(let i=0;i<t.length;i++)s+=Math.pow(t[i]-e,2);return 0===s?0:n/s}}class v{constructor(t){n(this,"transmitter"),n(this,"tabTimestamps",[]),n(this,"shiftTabCount",0),n(this,"tabCount",0),n(this,"isShiftDown",!1),n(this,"BURST_THRESHOLD_MS",80),n(this,"reportInterval",null),n(this,"REPORT_INTERVAL_MS",1e4),n(this,"MIN_TABS_TO_REPORT",5),n(this,"TAB_TRIGGER_COUNT",20),n(this,"onKeyDown",t=>{if("Shift"!==t.key){if("Tab"===t.key){const t=Date.now();this.isShiftDown?this.shiftTabCount++:(this.tabCount++,this.tabTimestamps.push(t),this.tabTimestamps.length>100&&this.tabTimestamps.shift()),this.tabCount+this.shiftTabCount>=this.TAB_TRIGGER_COUNT&&this.report()}}else this.isShiftDown=!0}),n(this,"onKeyUp",t=>{"Shift"===t.key&&(this.isShiftDown=!1)}),this.transmitter=t}start(){"undefined"!=typeof document&&(document.addEventListener("keydown",this.onKeyDown,{passive:!0,capture:!0}),document.addEventListener("keyup",this.onKeyUp,{passive:!0,capture:!0}),this.reportInterval=setInterval(()=>this.report(),this.REPORT_INTERVAL_MS))}stop(){"undefined"!=typeof document&&(document.removeEventListener("keydown",this.onKeyDown,{capture:!0}),document.removeEventListener("keyup",this.onKeyUp,{capture:!0}),this.reportInterval&&(clearInterval(this.reportInterval),this.reportInterval=null),this.report())}report(){const t=this.tabCount+this.shiftTabCount;if(t<this.MIN_TABS_TO_REPORT)return;const e=this.calculateIntervals(this.tabTimestamps);if(e.length<3)return void this.resetBuffers();const n=this.analyzeIntervals(e),s=this.analyzeBursts(e),i=t>0?this.shiftTabCount/t:0;this.transmitter.send("tab_navigation_metrics",{tabCount:this.tabCount,shiftTabCount:this.shiftTabCount,shiftTabRatio:parseFloat(i.toFixed(4)),intervals:n,bursts:s,timestamp:Date.now()}),this.resetBuffers()}resetBuffers(){this.tabTimestamps=[],this.tabCount=0,this.shiftTabCount=0}calculateIntervals(t){const e=[];for(let n=1;n<t.length;n++){const s=t[n]-t[n-1];s<5e3&&e.push(s)}return e}analyzeIntervals(t){if(0===t.length)return{avg:0,variance:0,cv:0,min:0,samples:0};const e=t.reduce((t,e)=>t+e,0)/t.length,n=t.reduce((t,n)=>t+Math.pow(n-e,2),0)/t.length,s=Math.sqrt(n),i=e>0?s/e:0,r=Math.min(...t);return{avg:parseFloat(e.toFixed(2)),variance:parseFloat(n.toFixed(2)),cv:parseFloat(i.toFixed(4)),min:r,samples:t.length}}analyzeBursts(t){let e=0,n=0,s=0,i=0,r=0;for(const a of t)a<this.BURST_THRESHOLD_MS?(n++,i+=a,r++):(n>=3&&(e++,s+=n),n=0);return n>=3&&(e++,s+=n),{count:e,avgLength:e>0?parseFloat((s/e).toFixed(1)):0,avgInterval:r>0?parseFloat((i/r).toFixed(2)):0}}}class b{constructor(t){n(this,"transmitter"),n(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2e3))}async detect(){try{const t=this.analyzeGPU(),e=this.analyzeHardware(),n=this.analyzeScreen(),s=await this.analyzeMedia(),i=this.benchmarkCanvas();let r=0;"virtual_gpu"!==t.category&&"software_render"!==t.category&&"cloud_gpu"!==t.category||(r+=2),e.cores<=2&&r++,null!==e.memory&&e.memory<=2&&r++,24===e.colorDepth&&r++,1===e.pixelRatio&&r++,n.noTaskbar&&r++,n.isVMResolution&&r++,0===s.cameras&&0===s.microphones&&r++,s.hasBluetooth||s.hasUSB||r++,i.canvasRenderTime>50&&r++;const{classification:a,confidence:o}=this.classify(t,e,r);this.transmitter.send("cloud_environment",{classification:a,confidence:o,signals:{gpu:{renderer:t.renderer,vendor:t.vendor,category:t.category},hardware:e,screen:n,media:s,performance:i},vmIndicatorCount:r,timestamp:Date.now()})}catch(t){}}analyzeGPU(){try{const t=document.createElement("canvas"),e=t.getContext("webgl")||t.getContext("experimental-webgl");if(!e)return{renderer:"unavailable",vendor:"unavailable",category:"unknown"};const n=e.getExtension("WEBGL_debug_renderer_info");if(!n)return{renderer:"no_debug_info",vendor:"no_debug_info",category:"unknown"};const s=e.getParameter(n.UNMASKED_RENDERER_WEBGL)||"",i=e.getParameter(n.UNMASKED_VENDOR_WEBGL)||"";return{renderer:s,vendor:i,category:this.categorizeGPU(s,i)}}catch(t){return{renderer:"error",vendor:"error",category:"unknown"}}}categorizeGPU(t,e){const n=t.toLowerCase(),s=e.toLowerCase();return/swiftshader|llvmpipe|mesa offscreen|softpipe/.test(n)?"software_render":/svga3d|svga|vmware/.test(n)||/virtualbox/.test(n)||/parallels/.test(n)||/qxl|virtio|red hat|spice/.test(n)||/hyper-v|microsoft basic render/i.test(n)||/citrix/.test(n)?"virtual_gpu":/amazon|elastic|aws/.test(n)||/amazon|elastic|aws/.test(s)||/google cloud|gce/.test(n)||/google cloud|gce/.test(s)||/azure/.test(n)||/azure/.test(s)?"cloud_gpu":"physical"}analyzeHardware(){return{cores:navigator.hardwareConcurrency||0,memory:navigator.deviceMemory??null,colorDepth:screen.colorDepth,pixelRatio:window.devicePixelRatio||1}}analyzeScreen(){const t=screen.width,e=screen.height,n=screen.availHeight,s=e===n&&e===window.innerHeight,i=[[800,600],[1024,768],[1280,1024],[1280,800],[1920,1080]].some(([n,s])=>t===n&&e===s&&!(1920===n&&1080===s));return{width:t,height:e,availHeight:n,noTaskbar:s,isVMResolution:i}}async analyzeMedia(){let t=-1,e=-1;try{if(navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices){const n=await navigator.mediaDevices.enumerateDevices();t=n.filter(t=>"videoinput"===t.kind).length,e=n.filter(t=>"audioinput"===t.kind).length}}catch(r){}const n=!!navigator.bluetooth,s=!!navigator.usb;let i=null;try{if(navigator.getBattery){const t=await navigator.getBattery();i=!(t.charging&&1===t.level&&0===t.chargingTime)}}catch(r){}return{cameras:t,microphones:e,hasBluetooth:n,hasUSB:s,hasBattery:i}}benchmarkCanvas(){try{const t=document.createElement("canvas");t.width=200,t.height=200;const e=t.getContext("2d");if(!e)return{canvasRenderTime:-1};const n=performance.now();for(let i=0;i<500;i++)e.fillStyle=`rgb(${i%256},${3*i%256},${7*i%256})`,e.fillRect(13*i%200,7*i%200,10,10);e.getImageData(0,0,1,1);const s=performance.now()-n;return{canvasRenderTime:Math.round(100*s)/100}}catch(t){return{canvasRenderTime:-1}}}classify(t,e,n){return"virtual_gpu"===t.category?24===e.colorDepth?{classification:"rdp_likely",confidence:.85}:{classification:"vm_detected",confidence:.95}:"cloud_gpu"===t.category?{classification:"cloud_likely",confidence:.9}:"software_render"===t.category?{classification:"vm_detected",confidence:.9}:n>=5?{classification:"vm_likely",confidence:.8}:n>=3?{classification:"vm_likely",confidence:.6}:{classification:"physical",confidence:1-.1*n}}}class _{constructor(t){n(this,"transmitter"),n(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2500))}async detect(){var t,e;const n={};let s=0;const i={webdriver:!!navigator.webdriver,languages:(null==(t=navigator.languages)?void 0:t.join(","))||"",platform:navigator.platform||"",hardwareConcurrency:navigator.hardwareConcurrency||0,userAgent:navigator.userAgent||"",pluginsLength:(null==(e=navigator.plugins)?void 0:e.length)??0},r=this.checkIframe(i);r.score>0&&(n.iframe=r.mismatches,s+=r.score);try{const t=await this.checkWorker(i);t.score>0&&(n.worker=t.mismatches,s+=t.score)}catch(a){}s>0&&this.transmitter.send("cross_context_mismatch",{signals:n,score:s,timestamp:Date.now()})}checkIframe(t){var e,n;const s=[];let i=0;try{const r=document.createElement("iframe");r.style.display="none",r.sandbox="allow-same-origin",document.body.appendChild(r);const a=r.contentWindow;if(!a)return document.body.removeChild(r),{score:0,mismatches:[]};const o=a.navigator;o.webdriver!==navigator.webdriver&&(s.push("webdriver_mismatch"),i+=40),navigator.webdriver||!0!==o.webdriver||(s.push("webdriver_spoofed_in_main"),i+=30);((null==(e=o.languages)?void 0:e.join(","))||"")!==t.languages&&(s.push("languages_mismatch"),i+=15),o.platform!==t.platform&&(s.push("platform_mismatch"),i+=15);((null==(n=o.plugins)?void 0:n.length)??0)!==t.pluginsLength&&(s.push("plugins_mismatch"),i+=10),document.body.removeChild(r)}catch(r){}return{score:i,mismatches:s}}checkWorker(t){return new Promise(e=>{try{const n=new Blob(["\n self.onmessage = function() {\n var nav = self.navigator;\n self.postMessage({\n webdriver: !!nav.webdriver,\n languages: (nav.languages || []).join(','),\n platform: nav.platform || '',\n hardwareConcurrency: nav.hardwareConcurrency || 0,\n userAgent: nav.userAgent || ''\n });\n };\n "],{type:"application/javascript"}),s=URL.createObjectURL(n),i=new Worker(s),r=setTimeout(()=>{i.terminate(),URL.revokeObjectURL(s),e({score:0,mismatches:[]})},3e3);i.onmessage=n=>{clearTimeout(r),i.terminate(),URL.revokeObjectURL(s);const a=n.data,o=[];let c=0;a.webdriver!==t.webdriver&&(o.push("worker_webdriver_mismatch"),c+=35),a.languages!==t.languages&&(o.push("worker_languages_mismatch"),c+=15),a.platform!==t.platform&&(o.push("worker_platform_mismatch"),c+=15),a.hardwareConcurrency!==t.hardwareConcurrency&&(o.push("worker_concurrency_mismatch"),c+=10),a.userAgent!==t.userAgent&&(o.push("worker_ua_mismatch"),c+=20),e({score:c,mismatches:o})},i.onerror=()=>{clearTimeout(r),i.terminate(),URL.revokeObjectURL(s),e({score:0,mismatches:[]})},i.postMessage("check")}catch(n){e({score:0,mismatches:[]})}})}}class T{constructor(t){n(this,"transmitter"),n(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2e3))}async detect(){const t={};let e=0;const n=await this.checkBrokenImage();n.suspicious&&(t.brokenImage=n,e+=25);const s=await this.checkClientHints();s.suspicious&&(t.clientHints=s,e+=20);const i=this.checkCDPMouseSignature();i.suspicious&&(t.cdpMouse=i,e+=30);const r=this.checkHairlineSupport();r.suspicious&&(t.hairline=r,e+=10);const a=this.checkExtraFrameworks();a.length>0&&(t.extraFrameworks=a,e+=20);(await this.checkWorkerCDP()).suspicious&&(t.workerCDP=!0,e+=35),e>0&&this.transmitter.send("headless_probe",{signals:t,score:e,timestamp:Date.now()})}checkBrokenImage(){return new Promise(t=>{try{const e=document.createElement("img");e.src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==___invalid";const n=setTimeout(()=>{t({suspicious:!1,width:-1,height:-1})},2e3);e.onerror=()=>{clearTimeout(n);const s=e.width,i=e.height;t({suspicious:0===s&&0===i,width:s,height:i})},e.onload=()=>{clearTimeout(n),t({suspicious:!1,width:e.width,height:e.height})},e.style.position="absolute",e.style.left="-9999px",document.body.appendChild(e),setTimeout(()=>{try{document.body.removeChild(e)}catch(t){}},100)}catch(e){t({suspicious:!1,width:-1,height:-1})}})}async checkClientHints(){const t=[];try{const e=navigator.userAgentData;if(!e)return{suspicious:!1,mismatches:[]};const n=navigator.userAgent,s=(e.brands||[]).map(t=>t.brand);/Chrome\/\d/.test(n)&&!s.some(t=>/Chromium|Google Chrome|Chrome/.test(t))&&t.push("ua_chrome_no_brand"),e.platform&&(/Windows/.test(n)&&"Windows"!==e.platform&&t.push("ua_windows_brand_mismatch"),/Macintosh/.test(n)&&"macOS"!==e.platform&&t.push("ua_mac_brand_mismatch"),/Linux/.test(n)&&!/Linux|Android|ChromeOS/.test(e.platform)&&t.push("ua_linux_brand_mismatch")),/Mobile/.test(n)&&!1===e.mobile&&t.push("ua_mobile_brand_mismatch")}catch(e){}return{suspicious:t.length>0,mismatches:t}}checkCDPMouseSignature(){let t=0,e=0,n=!1;try{const s=[],i=n=>{s.push(n),e++,0===n.movementX&&0===n.movementY&&t++};document.addEventListener("mousemove",i,{passive:!0}),setTimeout(()=>{document.removeEventListener("mousemove",i)},5e3),e>10&&t/e>.9&&(n=!0)}catch(s){}return{suspicious:n,zeroMovementCount:t,totalEvents:e}}checkHairlineSupport(){try{const t=document.createElement("div");t.style.border=".5px solid transparent",t.style.position="absolute",t.style.left="-9999px",document.body.appendChild(t);const e=t.offsetHeight;return document.body.removeChild(t),{suspicious:0===e,offsetHeight:e}}catch(t){return{suspicious:!1,offsetHeight:-1}}}checkExtraFrameworks(){const t=[];try{const n=window.external;if(n&&"function"==typeof n.toString)try{const e=n.toString();/Sequentum/i.test(e)&&t.push("sequentum")}catch(e){}const s=["__webdriver_script_fn","__webdriver_script_func","__webdriver_evaluate","__selenium_evaluate","__fxdriver_evaluate","__driver_evaluate","__webdriver_unwrapped","__selenium_unwrapped","__fxdriver_unwrapped","__driver_unwrapped","_Selenium_IDE_Recorder","_selenium","calledSelenium","_WEBDRIVER_ELEM_CACHE","ChromeDriverw","driver-hierarchical","__$webdriverAsyncExecutor","__lastWatirAlert","__lastWatirConfirm","__lastWatirPrompt","_WEBDRIVER_ELEM_CACHE","webdriver","_phantom","__nightmare","_selenium"];for(const e of s)(e in document||e in window)&&t.push(`global_${e}`);const i=Object.getOwnPropertyNames(navigator);for(const e of i)/webdriver|selenium|puppeteer|playwright|phantom/i.test(e)&&t.push(`nav_${e}`)}catch(e){}return t}checkWorkerCDP(){return new Promise(t=>{try{const e=new Blob(["\n self.onmessage = function() {\n var detected = false;\n try {\n var marker = {};\n Object.defineProperty(marker, 'stack', {\n get: function() { detected = true; return ''; }\n });\n console.debug(marker);\n } catch(e) {}\n self.postMessage({ cdp: detected });\n };\n "],{type:"application/javascript"}),n=URL.createObjectURL(e),s=new Worker(n),i=setTimeout(()=>{s.terminate(),URL.revokeObjectURL(n),t({suspicious:!1})},3e3);s.onmessage=e=>{clearTimeout(i),s.terminate(),URL.revokeObjectURL(n),t({suspicious:!0===e.data.cdp})},s.onerror=()=>{clearTimeout(i),s.terminate(),URL.revokeObjectURL(n),t({suspicious:!1})},s.postMessage("check")}catch(e){t({suspicious:!1})}})}}class k{constructor(t){n(this,"transmitter"),n(this,"hasRun",!1),n(this,"injectedScriptCount",0),n(this,"cspViolations",[]),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,this.startDOMObserver(),this.startCSPMonitor(),setTimeout(()=>this.detect(),1500))}detect(){const t={};let e=0;try{const n=this.checkNativeFunctionIntegrity();n.issues.length>0&&(t.nativeFunctionIntegrity=n.issues,e+=25)}catch(n){}try{const n=this.checkPropertyOverrides();n.issues.length>0&&(t.propertyOverrides=n.issues,e+=30)}catch(n){}this.injectedScriptCount>0&&(t.domScriptInjection={count:this.injectedScriptCount},e+=20),this.cspViolations.length>0&&(t.cspViolations=this.cspViolations.slice(0,10),e+=15);try{const n=this.checkGlobalPollution();n.length>0&&(t.globalPollution=n,e+=20)}catch(n){}try{const n=this.checkPrototypeIntegrity();n.length>0&&(t.prototypeIntegrity=n,e+=20)}catch(n){}e>0&&this.transmitter.send("script_injection",{signals:t,score:e,timestamp:Date.now()})}checkNativeFunctionIntegrity(){const t=[];try{const e=Object.getOwnPropertyDescriptor(navigator,"webdriver");if(e&&(!0===e.configurable&&t.push("webdriver_descriptor_configurable"),e.get)){const n=Function.prototype.toString.call(e.get);/\[native code\]/.test(n)||t.push("webdriver_non_native_getter")}}catch(e){}try{const e=["userAgent","platform","languages","hardwareConcurrency"];for(const n of e){const e=Object.getOwnPropertyDescriptor(Navigator.prototype,n);if(e&&e.get){const s=Function.prototype.toString.call(e.get);/\[native code\]/.test(s)||t.push(`navigator_${n}_non_native`)}}}catch(e){}try{const e=Function.prototype.toString.call(Function.prototype.toString);/\[native code\]/.test(e)||t.push("function_tostring_overridden")}catch(e){}return{issues:t}}checkPropertyOverrides(){const t=[];try{"[object Navigator]"!==Object.prototype.toString.call(navigator)&&t.push("navigator_proxy_or_spoofed")}catch(e){}try{if(navigator.plugins){"[object PluginArray]"!==Object.prototype.toString.call(navigator.plugins)&&t.push("plugins_spoofed"),Array.isArray(navigator.plugins)&&t.push("plugins_is_array")}}catch(e){}try{if(navigator.mimeTypes){"[object MimeTypeArray]"!==Object.prototype.toString.call(navigator.mimeTypes)&&t.push("mimetypes_spoofed")}}catch(e){}try{const e=Function.prototype.toString.call(Object.getOwnPropertyDescriptor);/\[native code\]/.test(e)||t.push("getOwnPropertyDescriptor_overridden")}catch(e){}return{issues:t}}startDOMObserver(){try{if("undefined"==typeof MutationObserver)return;const t=new MutationObserver(t=>{for(const e of t)for(let t=0;t<e.addedNodes.length;t++){const n=e.addedNodes[t];if("SCRIPT"===n.nodeName){n.src||this.injectedScriptCount++}}});t.observe(document.documentElement,{childList:!0,subtree:!0}),setTimeout(()=>{try{t.disconnect()}catch(e){}},1e4)}catch(t){}}startCSPMonitor(){try{const t=t=>{try{const e=`${t.violatedDirective}|${t.blockedURI||"inline"}`;this.cspViolations.push(e)}catch(e){}};document.addEventListener("securitypolicyviolation",t),setTimeout(()=>{try{document.removeEventListener("securitypolicyviolation",t)}catch(e){}},1e4)}catch(t){}}checkGlobalPollution(){const t=[],e=window,n=document,s=[["__webdriver_evaluate",()=>!!n.__webdriver_evaluate],["__selenium_evaluate",()=>!!n.__selenium_evaluate],["__webdriver_script_function",()=>!!n.__webdriver_script_function],["__webdriver_script_func",()=>!!n.__webdriver_script_func],["__webdriver_script_fn",()=>!!n.__webdriver_script_fn],["_Selenium_IDE_Recorder",()=>!!e._Selenium_IDE_Recorder],["__lastWatirAlert",()=>!!e.__lastWatirAlert],["__lastWatirConfirm",()=>!!e.__lastWatirConfirm],["__lastWatirPrompt",()=>!!e.__lastWatirPrompt],["_phantom",()=>!!e._phantom],["callPhantom",()=>!!e.callPhantom],["__nightmare",()=>!!e.__nightmare],["Buffer",()=>"function"==typeof e.Buffer&&"function"==typeof e.Buffer.alloc],["process",()=>!!e.process&&!!e.process.versions],["global_redefined",()=>!!e.global&&e.global!==e&&"object"==typeof e.global],["window_emit",()=>"function"==typeof e.emit]];for(const[r,a]of s)try{a()&&t.push(r)}catch(i){}try{const e=Object.keys(document);for(const n of e)/^cdc_|^__cdc_/.test(n)&&t.push(`cdc:${n}`)}catch(i){}try{const e=Object.keys(window);for(const n of e)/^cdc_|^__cdc_/.test(n)&&t.push(`cdc_window:${n}`)}catch(i){}return t}checkPrototypeIntegrity(){const t=[];try{const e=HTMLElement.prototype,n=Object.getOwnPropertyNames(e);for(const s of n)/^__selenium|^__webdriver|^__playwright|^__puppeteer/.test(s)&&t.push(`htmlelement_proto_${s}`)}catch(e){}try{const e=document.createElement("div");e instanceof HTMLDivElement||t.push("createElement_not_genuine");"[object HTMLDivElement]"!==Object.prototype.toString.call(e)&&t.push("createElement_wrong_tostring")}catch(e){}try{const e=new Event("test");e instanceof Event||t.push("event_not_instance");"[object Event]"!==Object.prototype.toString.call(e)&&t.push("event_wrong_prototype")}catch(e){}try{const e=Function.prototype.toString.call(document.createElement);/\[native code\]/.test(e)||t.push("createElement_overridden")}catch(e){}return t}}class C{constructor(t){n(this,"transmitter"),n(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2e3))}async detect(){try{if("undefined"==typeof Worker||"undefined"==typeof Blob)return;const e={webdriver:!!navigator.webdriver,userAgent:navigator.userAgent||"",platform:navigator.platform||"",languages:JSON.stringify(navigator.languages||[]),hardwareConcurrency:navigator.hardwareConcurrency||0,dateNow:Date.now(),perfNow:performance.now(),toStringNative:!1};try{e.toStringNative=/\[native code\]/.test(Function.prototype.toString.call(Array.prototype.push))}catch(t){e.toStringNative=!1}const n=await this.runWorker(e);if(!n)return;const s={};let i=0;const r=[];e.webdriver||!0!==n.webdriver?n.webdriver!==e.webdriver&&(r.push("webdriver_mismatch"),i+=30):(r.push("webdriver_spoofed"),i+=40),n.userAgent!==e.userAgent&&(r.push("userAgent_mismatch"),i+=30),n.platform!==e.platform&&(r.push("platform_mismatch"),i+=30),n.languages!==e.languages&&(r.push("languages_mismatch"),i+=30),n.hardwareConcurrency!==e.hardwareConcurrency&&(r.push("hardwareConcurrency_mismatch"),i+=30),r.length>0&&(s.navigatorMismatch=r);const a=n.benchmarkMs;"number"==typeof a&&(a<1||a>500)&&(s.benchmarkAnomaly={benchmarkMs:a,reason:a<1?"abnormally_fast":"abnormally_slow"},i+=20),!1===n.cryptoEntropy&&(s.cryptoMock={entropy:!1,values:n.cryptoValues},i+=15);const o=Math.abs(n.dateNow-e.dateNow);if(o>1e3&&(s.timeManipulation={mainDateNow:e.dateNow,workerDateNow:n.dateNow,deltaMs:o},i+=15),!n.toStringNative||!e.toStringNative){const t=[];n.toStringNative||t.push("worker_tampered"),e.toStringNative||t.push("main_tampered"),s.toStringTampering=t,i+=20}i>0&&this.transmitter.send("worker_integrity",{signals:s,score:i,timestamp:Date.now()})}catch(t){}}runWorker(t){return new Promise(e=>{try{const n=new Blob(["\n self.onmessage = function(e) {\n var results = {};\n\n // 1. Navigator check\n try {\n results.webdriver = !!navigator.webdriver;\n results.userAgent = navigator.userAgent || '';\n results.platform = navigator.platform || '';\n results.languages = JSON.stringify(navigator.languages || []);\n results.hardwareConcurrency = navigator.hardwareConcurrency || 0;\n } catch(ex) {\n results.webdriver = false;\n results.userAgent = '';\n results.platform = '';\n results.languages = '[]';\n results.hardwareConcurrency = 0;\n }\n\n // 2. Performance benchmark\n try {\n var start = performance.now();\n var sum = 0;\n for (var i = 0; i < 1000000; i++) sum += i;\n results.benchmarkMs = performance.now() - start;\n } catch(ex) {\n results.benchmarkMs = -1;\n }\n\n // 3. Crypto check\n try {\n var arr = new Uint32Array(4);\n crypto.getRandomValues(arr);\n results.cryptoEntropy = arr[0] !== arr[1] && arr[1] !== arr[2] && arr[0] !== 0;\n results.cryptoValues = Array.from(arr);\n } catch(ex) {\n results.cryptoEntropy = false;\n results.cryptoValues = [];\n }\n\n // 4. Time check\n results.dateNow = Date.now();\n results.perfNow = performance.now();\n\n // 5. toString integrity\n try {\n results.toStringNative = /\\[native code\\]/.test(\n Function.prototype.toString.call(Array.prototype.push)\n );\n } catch(ex) {\n results.toStringNative = false;\n }\n\n self.postMessage(results);\n };\n "],{type:"application/javascript"}),s=URL.createObjectURL(n),i=new Worker(s),r=setTimeout(()=>{i.terminate(),URL.revokeObjectURL(s),e(null)},5e3);i.onmessage=t=>{clearTimeout(r),i.terminate(),URL.revokeObjectURL(s),e(t.data)},i.onerror=()=>{clearTimeout(r),i.terminate(),URL.revokeObjectURL(s),e(null)},i.postMessage({mainValues:t})}catch(n){e(null)}})}}const E="__aie_token";class S{constructor(t){n(this,"config"),n(this,"renewTimer",null),n(this,"verified",!1),this.config=t}async start(){const t=this.getToken();if(t&&!this.isExpired(t))return this.verified=!0,this.scheduleRenewal(t),this.revealContent(),this.config.debug,!0;this.hideContent();const e=await this.solveChallenge();return e?(this.verified=!0,this.revealContent()):this.config.insertHoneypot&&this.insertHoneypotData(),e}isVerified(){return this.verified}stop(){this.renewTimer&&(clearTimeout(this.renewTimer),this.renewTimer=null)}async solveChallenge(){try{const t=await fetch(`${this.config.apiBase}/crawl-protect/challenge`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":this.config.clientId}});if(!t.ok)return!1;const{id:e,challenges:n}=await t.json(),s=[];for(const c of n)if("math"===c.type){const t="add"===c.op?c.a+c.b:c.a*c.b;s.push(String(t))}else if("crypto"===c.type){const t=await this.sha256(c.nonce);s.push(t.slice(0,8))}const i=s.join(":"),r=await this.getFingerprint(),a=await fetch(`${this.config.apiBase}/crawl-protect/verify`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":this.config.clientId},body:JSON.stringify({id:e,solution:i,fingerprint:r}),credentials:"include"});if(!a.ok)return!1;const o=await a.json();return!(!o.success||!o.token)&&(this.setToken(o.token),this.scheduleRenewal(o.token),this.config.debug,!0)}catch(t){return this.config.debug,!1}}hideContent(){var t;if(null==(t=this.config.protectSelectors)?void 0:t.length)for(const e of this.config.protectSelectors){document.querySelectorAll(e).forEach(t=>{t.dataset.aieOrigDisplay=t.style.display,t.style.display="none"})}}revealContent(){var t;if(null==(t=this.config.protectSelectors)?void 0:t.length)for(const e of this.config.protectSelectors){document.querySelectorAll(e).forEach(t=>{t.style.display=t.dataset.aieOrigDisplay||"",delete t.dataset.aieOrigDisplay})}}insertHoneypotData(){const t=document.createElement("div");t.style.cssText="position:absolute;left:-9999px;top:-9999px;opacity:0;pointer-events:none;",t.setAttribute("aria-hidden","true"),t.innerHTML='\n <span class="price" data-aie-honeypot="1">₩999,999,999</span>\n <span class="stock" data-aie-honeypot="1">재고: 0개</span>\n <a href="mailto:honeypot@aientrophy.com" data-aie-honeypot="1">contact</a>\n ',document.body.appendChild(t)}getToken(){const t=document.cookie.match(new RegExp(`(?:^|; )${E}=([^;]*)`));return t?decodeURIComponent(t[1]):null}setToken(t){const e=new Date(Date.now()+18e5).toUTCString();document.cookie=`${E}=${encodeURIComponent(t)};path=/;expires=${e};SameSite=None;Secure`}isExpired(t){try{const[e]=t.split("."),n=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return Date.now()>n.exp}catch{return!0}}scheduleRenewal(t){try{const[e]=t.split("."),n=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/"))),s=n.exp-3e5-Date.now();s>0&&(this.renewTimer=setTimeout(()=>this.solveChallenge(),s))}catch{}}async sha256(t){const e=new TextEncoder,n=await crypto.subtle.digest("SHA-256",e.encode(t));return Array.from(new Uint8Array(n)).map(t=>t.toString(16).padStart(2,"0")).join("")}async getFingerprint(){const t=[navigator.userAgent,navigator.language,screen.width+"x"+screen.height,Intl.DateTimeFormat().resolvedOptions().timeZone];return this.sha256(t.join("|"))}}const D=new class{constructor(){n(this,"transmitter"),n(this,"behaviorCollector"),n(this,"rapidClickDetector"),n(this,"honeypot"),n(this,"mouseTracker"),n(this,"canvasFingerprinter"),n(this,"inputTracker"),n(this,"challengeHandler"),n(this,"invisibleInteraction"),n(this,"automationDetector"),n(this,"sessionAnalyzer"),n(this,"tabNavigationAnalyzer"),n(this,"cloudEnvironmentDetector"),n(this,"crossContextDetector"),n(this,"headlessProbeDetector"),n(this,"scriptInjectionDetector"),n(this,"workerIntegrityDetector"),n(this,"crawlProtect",null),n(this,"initialized",!1),n(this,"wasmService"),n(this,"callbackManager"),this.transmitter=new o,this.wasmService=new p,this.callbackManager=new a,this.transmitter.setCallbackManager(this.callbackManager),this.behaviorCollector=new c(this.transmitter),this.rapidClickDetector=new l(this.transmitter),this.honeypot=new h(this.transmitter),this.mouseTracker=new u(this.transmitter,this.wasmService),this.canvasFingerprinter=new m(this.transmitter,this.wasmService),this.inputTracker=new d(this.transmitter),this.invisibleInteraction=new y(this.transmitter),this.automationDetector=new f(this.transmitter),this.sessionAnalyzer=new w(this.transmitter),this.tabNavigationAnalyzer=new v(this.transmitter),this.cloudEnvironmentDetector=new b(this.transmitter),this.crossContextDetector=new _(this.transmitter),this.headlessProbeDetector=new T(this.transmitter),this.scriptInjectionDetector=new k(this.transmitter),this.workerIntegrityDetector=new C(this.transmitter)}async init(t){var e,n;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 g(s),this.challengeHandler.setCallbackManager(this.callbackManager),!1!==(null==(e=t.serverConfig)?void 0:e.captchaEnabled)&&this.challengeHandler.start();((null==(n=t.serverConfig)?void 0:n.devtoolsDetection)??!t.debug)&&Promise.resolve().then(()=>P).then(({AntiDebug:t})=>{t.start(),t.setOnDevtoolsMaxed(()=>{this.transmitter.send("devtools_force_close",{reason:"devtools_threshold_exceeded",detectionCount:3,maxThreat:!0})}),Promise.resolve().then(()=>O).then(({ConsoleDetector:t})=>{new t(()=>{this.transmitter.send("devtools_open",{detected:!0})}).start()})}),t.crawlProtect&&(this.crawlProtect=new S({apiBase:s,clientId:t.clientKey,protectSelectors:t.crawlProtect.protectSelectors,insertHoneypot:t.crawlProtect.insertHoneypot,debug:t.debug}),this.crawlProtect.start().catch(e=>{t.debug})),this.initialized=!0,t.debug,this.callbackManager.emit("ready")}catch(i){this.callbackManager.emit("error",{code:"INIT_ERROR",message:"SecuritySDK initialization failed",details:null==i?void 0:i.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.behaviorCollector.start(),this.honeypot.start(),this.mouseTracker.start(),this.canvasFingerprinter.start(),this.inputTracker.start(),this.invisibleInteraction.start(),this.automationDetector.start(),this.sessionAnalyzer.start(),this.tabNavigationAnalyzer.start(),this.cloudEnvironmentDetector.start(),this.crossContextDetector.start(),this.headlessProbeDetector.start(),this.scriptInjectionDetector.start(),this.workerIntegrityDetector.start()}};"undefined"!=typeof window&&(window.SecuritySDK=D);const A={};let M=0;let R=!1,x=null;class I{static start(){this.saveConsole(),this.disableConsole(),this.preventDevTools(),this.blockDevToolsKeys()}static stop(){this.intervalId&&clearInterval(this.intervalId)}static setOnDevtoolsMaxed(t){x=t}static reportDevtoolsDetection(){R||(M++,M>=3&&(R=!0,this.handleDevtoolsMaxed()))}static getOriginalConsole(){return A}static handleDevtoolsMaxed(){if(x)try{x()}catch(t){}try{alert("개발자 도구가 탐지되었습니다.\n보안 정책에 의해 브라우저가 종료됩니다.")}catch(t){}try{document.documentElement.innerHTML=""}catch(t){}try{window.open("","_self"),window.close()}catch(t){}setTimeout(()=>{try{window.location.href="about:blank"}catch(t){}},100)}static saveConsole(){const t=["log","debug","info","warn","error","table","trace","dir","clear"];try{const e=window.console;if(!e)return;for(const n of t)"function"==typeof e[n]&&(A[n]=e[n].bind(e))}catch(e){}}static preventDevTools(){this.intervalId=setInterval(()=>{this.debuggerCheck()},this.checkInterval)}static debuggerCheck(){!function(){try{(function(){}).constructor("debugger")()}catch(t){}}()}static blockDevToolsKeys(){document.addEventListener("keydown",t=>{"F12"!==t.key?t.ctrlKey&&t.shiftKey&&["I","i","J","j","C","c"].includes(t.key)?t.preventDefault():!t.ctrlKey||"u"!==t.key&&"U"!==t.key||t.preventDefault():t.preventDefault()},!0)}static disableConsole(){const t=()=>{},e=["log","debug","info","warn","error","table","trace","dir"];try{const n=window.console;if(!n)return;for(const s of e)n[s]&&(n[s]=t)}catch(n){}}}n(I,"checkInterval",1e3),n(I,"intervalId");const P=Object.freeze(Object.defineProperty({__proto__:null,AntiDebug:I},Symbol.toStringTag,{value:"Module"}));const O=Object.freeze(Object.defineProperty({__proto__:null,ConsoleDetector:class{constructor(t){n(this,"onDetect"),n(this,"intervals",[]),n(this,"detected",!1),this.onDetect=t}isMobile(){return navigator.maxTouchPoints>0||/Mobile|Android|iPhone|iPad/i.test(navigator.userAgent)}start(){this.isMobile()||(this.startGetterTrap(),this.startSizeDetection())}stop(){for(const t of this.intervals)clearInterval(t);this.intervals=[]}triggerDetect(){this.detected||(this.detected=!0,this.onDetect(),I.reportDevtoolsDetection(),setTimeout(()=>{this.detected=!1},2e3))}startGetterTrap(){const t=I.getOriginalConsole(),e=t.log,n=t.clear;if(!e)return;const s=document.createElement("div");Object.defineProperty(s,"id",{get:()=>(this.triggerDetect(),"")});const i=/./;i.toString=()=>(this.triggerDetect(),"");const r=setInterval(()=>{try{e(s),e(i),n&&n()}catch(t){}},1500);this.intervals.push(r)}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=D,Object.defineProperty(t,Symbol.toStringTag,{value:"Module"})});
@@ -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)try{await this.initECDH()}catch(t){await this.initRSA()}}static async initECDH(){const t=await window.crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),e=await window.crypto.subtle.exportKey("raw",t.publicKey);this.ecdhPublicKeyBase64=this.arrayBufferToBase64(e);const i=(window.__securitySDKEndpoint||"").replace(/\/events$/,""),n=await fetch(`${i}/key-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientPublicKey:this.ecdhPublicKeyBase64})});if(!n.ok)throw new Error("Key exchange failed");const{serverPublicKey:s,salt:r}=await n.json(),a=this.base64ToArrayBuffer(s),o=await window.crypto.subtle.importKey("raw",a,{name:"ECDH",namedCurve:"P-256"},!1,[]),c=await window.crypto.subtle.deriveBits({name:"ECDH",public:o},t.privateKey,256),l=await window.crypto.subtle.importKey("raw",c,"HKDF",!1,["deriveKey"]),h=this.base64ToArrayBuffer(r);this.sessionKey=await window.crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:h,info:(new TextEncoder).encode("aientrophy-session-enc")},l,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),this.protocolVersion=2}static async initRSA(){this.sessionKey=await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]);const t=await this.importRSAPublicKey(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),this.protocolVersion=1}static async encrypt(t){this.sessionKey||await this.init();const e=JSON.stringify(t),i=(new TextEncoder).encode(e),n=window.crypto.getRandomValues(new Uint8Array(12)),s=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:n},this.sessionKey,i),r=new Uint8Array(s),a=r.slice(0,r.length-16),o=r.slice(r.length-16),c={ek:2===this.protocolVersion?this.ecdhPublicKeyBase64:this.encryptedSessionKey,d:this.arrayBufferToBase64(a.buffer),iv:this.arrayBufferToBase64(n.buffer),tag:this.arrayBufferToBase64(o.buffer)};return 2===this.protocolVersion&&(c.v=2),c}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),n=this.base64ToArrayBuffer(t.tag),s=new Uint8Array(e.byteLength+n.byteLength);s.set(new Uint8Array(e),0),s.set(new Uint8Array(n),e.byteLength);const r=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:i},this.sessionKey,s),a=(new TextDecoder).decode(r);return JSON.parse(a)}static setEndpoint(t){window.__securitySDKEndpoint=t}static async importRSAPublicKey(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 n=0,s=t.length;n<s;n++)i[n]=t.charCodeAt(n);return e}static arrayBufferToBase64(t){let e="";const i=new Uint8Array(t),n=i.byteLength;for(let s=0;s<n;s++)e+=String.fromCharCode(i[s]);return window.btoa(e)}static base64ToArrayBuffer(t){const e=window.atob(t),i=e.length,n=new Uint8Array(i);for(let s=0;s<i;s++)n[s]=e.charCodeAt(s);return n.buffer}}__publicField(CryptoUtils,"sessionKey",null),__publicField(CryptoUtils,"ecdhPublicKeyBase64",null),__publicField(CryptoUtils,"encryptedSessionKey",null),__publicField(CryptoUtils,"protocolVersion",2);const THREAT_EVENTS=new Set(["rapid_click","honeypot_triggered","devtools_open","invisible_interaction","integrity_violation","dom_mutation","behavior_metrics","behavior_analysis","input_metrics","keystroke_dynamics","environmental_integrity","init_signals","automation_detected","cross_context_mismatch","headless_probe","script_injection","worker_integrity"]);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 n=i.filter(t=>t.handler!==e);0===n.length?this.handlers.delete(t):this.handlers.set(t,n)}emit(t,...e){this.callHandlers(t,e);const i=t.indexOf(":");if(-1!==i){const n=t.substring(0,i);this.callHandlers(n,e)}this.callConfigCallback(t,e)}emitChallenge(t){return new Promise(e=>{let i=!1;const n=t=>{i||(i=!0,e(t))},s=this.handlers.has("challenge")&&this.handlers.get("challenge").length>0,r=!!this.configCallbacks.onChallenge;s||r?(this.callHandlers("challenge",[t,n]),this.configCallbacks.onChallenge&&this.safeCall(this.configCallbacks.onChallenge,[t,n]),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 n=[];for(let s=0;s<i.length;s++)this.safeCall(i[s].handler,e),i[s].once&&n.push(s);for(let s=n.length-1;s>=0;s--)i.splice(n[s],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",20),__publicField(this,"flushInterval",5e3),__publicField(this,"intervalId"),__publicField(this,"responseHandler",null),__publicField(this,"callbackManager",null),__publicField(this,"flushing",!1),__publicField(this,"pendingFlush",!1),__publicField(this,"backoffMs",0),__publicField(this,"maxBackoffMs",6e4),__publicField(this,"_lastBackoffStart",0),this.startFlushInterval()}setConfig(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)??"",CryptoUtils.setEndpoint(t.endpoint)}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 n={type:t,data:e,timestamp:i};this.callbackManager.emit(`threat:${t}`,n)}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.backoffMs>0){const t=Date.now();if(this._lastBackoffStart||(this._lastBackoffStart=t),t-this._lastBackoffStart<this.backoffMs)return;this._lastBackoffStart=0}if(this.flushing)return void(this.pendingFlush=!0);this.flushing=!0;const t=this.buffer;this.buffer=[];try{let n;if(this.encryptionRequired){const e=await CryptoUtils.encrypt(t);n=JSON.stringify(e)}else n=JSON.stringify(t);const s={"Content-Type":"application/json","x-client-key":this.clientKey};this.currentNonce&&(s["x-request-nonce"]=this.currentNonce,this.currentNonce="");try{const i=await fetch(this.endpoint,{method:"POST",body:n,headers:s,keepalive:!0});if(429===i.status)return this.buffer=t.concat(this.buffer).slice(0,500),this.backoffMs=0===this.backoffMs?5e3:Math.min(2*this.backoffMs,this.maxBackoffMs),void(this._lastBackoffStart=Date.now());if(this.backoffMs=0,i.ok&&this.callbackManager&&this.callbackManager.emit("allow",{action:"allow"}),i.ok)try{const t=await i.json();let e=t;this.encryptionRequired&&(e=await CryptoUtils.decrypt(t)),(null==e?void 0:e.nonce)&&(this.currentNonce=e.nonce),this.responseHandler&&this.responseHandler(e)}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 BehaviorCollector{constructor(t){__publicField(this,"transmitter"),__publicField(this,"isCollecting",!1),this.transmitter=t}start(){this.isCollecting||(this.isCollecting=!0)}stop(){this.isCollecting=!1}}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,n={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:n,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 n=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",n),this.element.addEventListener("focus",n),this.element.addEventListener("click",n),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",50),__publicField(this,"SAMPLE_INTERVAL",100),__publicField(this,"SEND_COOLDOWN",5e3),__publicField(this,"lastSampleTime",0),__publicField(this,"lastSendTime",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.buffer.length>=this.BUFFER_SIZE&&e-this.lastSendTime>=this.SEND_COOLDOWN&&(this.analyze(),this.lastSendTime=e))}),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<20)return;const t=this.wasmService.calculateEntropy(this.buffer),e=this.calculateSpeedVariance(),i=this.buffer.map(t=>({x:t.x,y:t.y,t:t.time}));this.transmitter.send("behavior_metrics",{entropy:t,speedVariance:e,sampleSize:this.buffer.length,timestamp:Date.now(),rawTrajectory:i})}calculateSpeedVariance(){const t=[];for(let i=1;i<this.buffer.length;i++){const e=this.buffer[i-1],n=this.buffer[i],s=Math.sqrt(Math.pow(n.x-e.x,2)+Math.pow(n.y-e.y,2)),r=n.time-e.time;r>0&&t.push(s/r)}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),__publicField(this,"rawKeystrokes",[]),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.rawKeystrokes=[],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.rawKeystrokes.push({code:t.code,t:i,type:"down"}),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,this.rawKeystrokes.push({code:t.code,t:i,type:"up"});const n=this.keyPressTimes.get(t.code);if(n){const e=i-n;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()<5e3||(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=0)}reportKeystrokeDynamics(t){const e=this.average(this.flightTimes),i=this.variance(this.flightTimes,e),n=this.average(this.dwellTimes),s=this.variance(this.dwellTimes,n);this.transmitter.send("input_metrics",{element:t.id||t.tagName,flight:{avg:e,variance:i,samples:this.flightTimes.length},dwell:{avg:n,variance:s},isMobile:this.isMobile,timestamp:Date.now(),rawKeystrokes:[...this.rawKeystrokes]}),this.flightTimes=[],this.dwellTimes=[],this.rawKeystrokes=[]}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(),n=await WebAssembly.instantiate(t,i);this.instance=n.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 n=this.wasmModule.__new(i,0),s=new Float64Array(this.memory.buffer,n,e);for(let e=0;e<t.length;e++)s[2*e]=t[e].x,s[2*e+1]=t[e].y;return this.wasmModule.calculateEntropy(n,e)}catch(n){return 0}}simpleHash(t){if(!this.instance||!this.wasmModule)return 0;try{const e=(new TextEncoder).encode(t),i=e.length,n=this.wasmModule.__new(i,0);return new Uint8Array(this.memory.buffer,n,i).set(e),this.wasmModule.simpleHash(n,i)}catch(e){return 0}}}class CanvasFingerprinter{constructor(t,e){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof document||setTimeout(async()=>{const t=await this.generateFingerprint(),e=this.collectWebGLFingerprint(),i=this.collectAudioFingerprint();this.transmitter.send("fingerprint_collected",{hash:t,webgl:e,audio:i}),this.hasRun=!0},500)}async 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();return await this.sha256(i)}catch(t){return"error"}}async sha256(t){const e=(new TextEncoder).encode(t),i=await window.crypto.subtle.digest("SHA-256",e),n=new Uint8Array(i);return Array.from(n).map(t=>t.toString(16).padStart(2,"0")).join("")}collectWebGLFingerprint(){try{const t=document.createElement("canvas"),e=t.getContext("webgl")||t.getContext("experimental-webgl");if(!e)return{available:!1};const i=e,n={available:!0},s=i.getExtension("WEBGL_debug_renderer_info");return s&&(n.renderer=i.getParameter(s.UNMASKED_RENDERER_WEBGL),n.vendor=i.getParameter(s.UNMASKED_VENDOR_WEBGL)),n.maxTextureSize=i.getParameter(i.MAX_TEXTURE_SIZE),n.maxViewportDims=Array.from(i.getParameter(i.MAX_VIEWPORT_DIMS)),n.maxRenderbufferSize=i.getParameter(i.MAX_RENDERBUFFER_SIZE),n.maxVertexAttribs=i.getParameter(i.MAX_VERTEX_ATTRIBS),n.extensions=(i.getSupportedExtensions()||[]).length,n}catch(t){return{available:!1,error:!0}}}collectAudioFingerprint(){try{const t=window.AudioContext||window.webkitAudioContext;if(!t)return{available:!1};const e=new t,i={available:!0,sampleRate:e.sampleRate,state:e.state,maxChannels:e.destination.maxChannelCount};return e.close(),i}catch(t){return{available:!1}}}}class ChallengeHandler{constructor(t){__publicField(this,"originalFetch"),__publicField(this,"endpoint"),__publicField(this,"callbackManager",null),__publicField(this,"challengeInProgress",null),this.endpoint=t,this.originalFetch=window.fetch.bind(window)}setCallbackManager(t){this.callbackManager=t}start(){window.fetch=async(t,e)=>{var i;const n=await this.originalFetch(t,e);if(403===n.status){const r=n.clone();try{const s=await r.json();if("challenge"===s.action&&"captcha"===(null==(i=s.metadata)?void 0:i.type)){const i={action:"challenge",score:s.score,metadata:s.metadata};if(this.callbackManager){if(await this.callbackManager.emitChallenge(i))return this.originalFetch(t,e)}this.challengeInProgress||(this.challengeInProgress=this.showCaptchaModal().finally(()=>{this.challengeInProgress=null}));return await this.challengeInProgress?this.originalFetch(t,e):n}"block"===s.action&&this.callbackManager&&this.callbackManager.emit("block",{action:"block",score:s.score,metadata:s.metadata})}catch(s){}}return n}}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"}),n=document.createElement("div");n.style.background="white",n.style.padding="20px",n.style.borderRadius="8px",n.style.boxShadow="0 4px 12px rgba(0,0,0,0.2)",n.style.textAlign="center",n.style.fontFamily="system-ui, sans-serif";const s=document.createElement("h3");s.textContent="Security Check",s.style.margin="0 0 16px 0";const r=document.createElement("p");r.textContent="Unusual activity detected. Please verify you are human.",r.style.marginBottom="16px",r.style.fontSize="14px",r.style.color="#666";const a=document.createElement("div");a.innerHTML="Loading...",a.style.marginBottom="16px";const o=document.createElement("input");o.type="text",o.placeholder="Enter details",o.style.padding="8px",o.style.marginRight="8px",o.style.border="1px solid #ddd",o.style.borderRadius="4px";const c=document.createElement("button");c.textContent="Verify",c.style.padding="8px 16px",c.style.background="#007bff",c.style.color="white",c.style.border="none",c.style.borderRadius="4px",c.style.cursor="pointer";const l=document.createElement("p");l.style.color="red",l.style.fontSize="12px",l.style.display="none",n.appendChild(s),n.appendChild(r),n.appendChild(a),n.appendChild(o),n.appendChild(c),n.appendChild(l),i.appendChild(n),document.body.appendChild(e);let h="";const u=async()=>{try{const t=await this.originalFetch(`${this.endpoint}/challenge`),e=await t.json();h=e.id,a.innerHTML=e.svg}catch(t){a.textContent="Error loading CAPTCHA"}},d=async()=>{l.style.display="none",c.textContent="Verifying...";try{const i=o.value,n=await this.originalFetch(`${this.endpoint}/challenge/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:h,answer:i})});(await n.json()).success?(document.body.removeChild(e),t(!0)):(l.textContent="Incorrect, try again.",l.style.display="block",c.textContent="Verify",o.value="",u())}catch(i){l.textContent="System error.",l.style.display="block",c.textContent="Verify"}};c.onclick=d,o.onkeydown=t=>{"Enter"===t.key&&d()},u()})}}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 n=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:n.top,left:n.left,width:n.width,height:n.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,n;const s=window.getComputedStyle(t);if("none"===s.display)return"display:none";if("hidden"===s.visibility)return"visibility:hidden";if("0"===s.opacity)return"opacity:0";const r=t.getBoundingClientRect();if(r.width<=0||r.height<=0)return"zero_size";const a=r.right<0||r.left>window.innerWidth,o=r.bottom<0||r.top>window.innerHeight;if(a||o)return"off_screen";if(e instanceof MouseEvent||e instanceof TouchEvent){let s,r;if(e instanceof MouseEvent?(s=e.clientX,r=e.clientY):(s=(null==(i=e.touches[0])?void 0:i.clientX)||0,r=(null==(n=e.touches[0])?void 0:n.clientY)||0),s>=0&&s<=window.innerWidth&&r>=0&&r<=window.innerHeight){const i=document.elementFromPoint(s,r);if(i&&i!==t&&!t.contains(i)&&!i.contains(t)&&0===s&&0===r&&e.isTrusted)return null}}return null}}class AutomationDetector{constructor(t){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(setTimeout(()=>this.detect(),1500),this.hasRun=!0)}detect(){var t,e;const i={};let n=0;!0===navigator.webdriver&&(i.webdriver=!0,n+=40);try{this.detectCDP()&&(i.cdp=!0,n+=50)}catch(c){}const s=this.detectAutomationGlobals();s.length>0&&(i.automationGlobals=s,n+=30);const r=this.checkWebGL();r.suspicious&&(i.webgl=r,n+=25);const a=this.checkInconsistencies();a.length>0&&(i.inconsistencies=a,n+=15);const o=this.checkHeadless();o.score>0&&(i.headless=o.flags,n+=o.score),n>0&&this.transmitter.send("automation_detected",{signals:i,score:n,timestamp:Date.now()}),this.transmitter.send("init_signals",{webdriver:!!navigator.webdriver,plugins:(null==(t=navigator.plugins)?void 0:t.length)??0,languages:(null==(e=navigator.languages)?void 0:e.length)??0,platform:navigator.platform,hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:navigator.deviceMemory,maxTouchPoints:navigator.maxTouchPoints,webglRenderer:r.renderer,webglVendor:r.vendor,timestamp:Date.now()})}detectCDP(){const t=console.debug;return console.debug=t,!1}detectAutomationGlobals(){const t=[],e=[["selenium",()=>!!window._selenium],["selenium_unwrapped",()=>!!document.__selenium_unwrapped],["driver_evaluate",()=>!!document.__driver_evaluate],["webdriver_evaluate",()=>!!document.__webdriver_evaluate],["driver_unwrapped",()=>!!document.__driver_unwrapped],["fxdriver",()=>!!document.__fxdriver_evaluate],["playwright",()=>!!window.__playwright],["playwright_binding",()=>!!window.__playwright__binding__],["pwInitScripts",()=>!!window.__pwInitScripts],["puppeteer",()=>!!window.__puppeteer_evaluation_script__],["phantom",()=>!!window.callPhantom||!!window._phantom],["nightmare",()=>!!window.__nightmare],["cdc",()=>Object.keys(document).some(t=>t.startsWith("cdc_")||t.startsWith("$cdc_"))]];for(const[n,s]of e)try{s()&&t.push(n)}catch(i){}return t}checkWebGL(){try{const t=document.createElement("canvas"),e=t.getContext("webgl")||t.getContext("experimental-webgl");if(!e)return{suspicious:!1,renderer:"unavailable",vendor:"unavailable"};const i=e.getExtension("WEBGL_debug_renderer_info");if(!i)return{suspicious:!1,renderer:"no_debug_info",vendor:"no_debug_info"};const n=e.getParameter(i.UNMASKED_RENDERER_WEBGL)||"",s=e.getParameter(i.UNMASKED_VENDOR_WEBGL)||"";return{suspicious:/SwiftShader/i.test(n)||/Mesa OffScreen/i.test(n)||/llvmpipe/i.test(n),renderer:n,vendor:s}}catch(t){return{suspicious:!1,renderer:"error",vendor:"error"}}}checkInconsistencies(){const t=[];try{const e=navigator.userAgent,i=navigator.platform;/Windows/.test(e)&&/Mac/.test(i)&&t.push("ua_platform_mismatch_win_mac"),/Macintosh/.test(e)&&/Win/.test(i)&&t.push("ua_platform_mismatch_mac_win"),/Mobile|Android|iPhone/.test(e)&&0===navigator.maxTouchPoints&&t.push("mobile_ua_no_touch"),/Chrome/.test(e)&&navigator.plugins&&0===navigator.plugins.length&&t.push("chrome_no_plugins"),navigator.languages&&0!==navigator.languages.length||t.push("no_languages")}catch(e){}return t}checkHeadless(){const t=[];let e=0;try{if(/HeadlessChrome/.test(navigator.userAgent)&&(t.push("headless_ua"),e+=40),/Chrome/.test(navigator.userAgent)&&!window.chrome&&(t.push("chrome_ua_no_chrome_obj"),e+=15),window.screen&&800===window.screen.width&&600===window.screen.height&&(t.push("default_screen_size"),e+=10),"Notification"in window){"denied"===window.Notification.permission&&navigator.userAgent.includes("Chrome")&&(t.push("notification_denied_default"),e+=5)}const i=navigator.connection;i&&0===i.rtt&&(t.push("zero_rtt"),e+=10)}catch(i){}return{score:e,flags:t}}}class SessionAnalyzer{constructor(t){__publicField(this,"transmitter"),__publicField(this,"sessionStart",0),__publicField(this,"pageTransitions",[]),__publicField(this,"interactionTimestamps",[]),__publicField(this,"lastPageUrl",""),__publicField(this,"formStartTimes",new Map),__publicField(this,"reportInterval",null),this.transmitter=t}start(){if("undefined"==typeof window)return;this.sessionStart=Date.now(),this.lastPageUrl=window.location.href;["mousedown","keydown","touchstart","scroll"].forEach(t=>{document.addEventListener(t,()=>{this.interactionTimestamps.push(Date.now()),this.interactionTimestamps.length>500&&this.interactionTimestamps.shift()},{passive:!0,capture:!0})}),this.observeNavigation(),this.observeForms(),this.reportInterval=setInterval(()=>this.report(),15e3)}observeNavigation(){const t=history.pushState,e=history.replaceState,i=this;history.pushState=function(e,n,s){t.call(this,e,n,s),i.onPageTransition()},history.replaceState=function(t,n,s){e.call(this,t,n,s),i.onPageTransition()},window.addEventListener("popstate",()=>this.onPageTransition())}onPageTransition(){const t=Date.now(),e=window.location.href;e!==this.lastPageUrl&&(this.pageTransitions.push(t),this.lastPageUrl=e)}observeForms(){document.addEventListener("focus",t=>{const e=t.target;if("INPUT"===e.tagName||"TEXTAREA"===e.tagName||"SELECT"===e.tagName){const t=e.closest("form"),i=(null==t?void 0:t.id)||(null==t?void 0:t.action)||"anonymous_form";this.formStartTimes.has(i)||this.formStartTimes.set(i,Date.now())}},{capture:!0}),document.addEventListener("submit",t=>{const e=t.target,i=e.id||e.action||"anonymous_form",n=this.formStartTimes.get(i);if(n){const t=Date.now()-n;this.transmitter.send("session_metrics",{type:"form_completion",formId:i,duration:t,timestamp:Date.now()}),this.formStartTimes.delete(i)}},{capture:!0})}report(){const t=Date.now(),e=t-this.sessionStart;if(this.interactionTimestamps.length<10)return;const i=this.calculateIntervals(this.interactionTimestamps),n=this.analyzeTimingDistribution(i),s=this.analyzePageTransitions();this.transmitter.send("session_metrics",{type:"session_analysis",sessionDuration:e,totalInteractions:this.interactionTimestamps.length,pageTransitions:this.pageTransitions.length,timing:n,pages:s,timestamp:t})}calculateIntervals(t){const e=[];for(let i=1;i<t.length;i++)e.push(t[i]-t[i-1]);return e}analyzeTimingDistribution(t){if(t.length<5)return{samples:t.length};const e=t.reduce((t,e)=>t+e,0)/t.length,i=t.reduce((t,i)=>t+Math.pow(i-e,2),0)/t.length,n=Math.sqrt(i),s=e>0?n/e:0,r=this.shannonEntropy(t,50),a=this.autocorrelation(t);return{mean:Math.round(e),stdDev:Math.round(n),cv:parseFloat(s.toFixed(4)),entropy:parseFloat(r.toFixed(4)),autocorrelation:parseFloat(a.toFixed(4)),samples:t.length}}analyzePageTransitions(){if(this.pageTransitions.length<2)return{count:this.pageTransitions.length};const t=this.calculateIntervals(this.pageTransitions),e=t.reduce((t,e)=>t+e,0)/t.length,i=t.reduce((t,i)=>t+Math.pow(i-e,2),0)/t.length,n=e>0?Math.sqrt(i)/e:0;return{count:this.pageTransitions.length,avgInterval:Math.round(e),cv:parseFloat(n.toFixed(4))}}shannonEntropy(t,e){const i=new Map;for(const r of t){const t=Math.floor(r/e);i.set(t,(i.get(t)||0)+1)}const n=t.length;let s=0;for(const r of i.values()){const t=r/n;t>0&&(s-=t*Math.log2(t))}return s}autocorrelation(t){if(t.length<3)return 0;const e=t.reduce((t,e)=>t+e,0)/t.length;let i=0,n=0;for(let s=0;s<t.length-1;s++)i+=(t[s]-e)*(t[s+1]-e);for(let s=0;s<t.length;s++)n+=Math.pow(t[s]-e,2);return 0===n?0:i/n}}class TabNavigationAnalyzer{constructor(t){__publicField(this,"transmitter"),__publicField(this,"tabTimestamps",[]),__publicField(this,"shiftTabCount",0),__publicField(this,"tabCount",0),__publicField(this,"isShiftDown",!1),__publicField(this,"BURST_THRESHOLD_MS",80),__publicField(this,"reportInterval",null),__publicField(this,"REPORT_INTERVAL_MS",1e4),__publicField(this,"MIN_TABS_TO_REPORT",5),__publicField(this,"TAB_TRIGGER_COUNT",20),__publicField(this,"onKeyDown",t=>{if("Shift"!==t.key){if("Tab"===t.key){const t=Date.now();this.isShiftDown?this.shiftTabCount++:(this.tabCount++,this.tabTimestamps.push(t),this.tabTimestamps.length>100&&this.tabTimestamps.shift()),this.tabCount+this.shiftTabCount>=this.TAB_TRIGGER_COUNT&&this.report()}}else this.isShiftDown=!0}),__publicField(this,"onKeyUp",t=>{"Shift"===t.key&&(this.isShiftDown=!1)}),this.transmitter=t}start(){"undefined"!=typeof document&&(document.addEventListener("keydown",this.onKeyDown,{passive:!0,capture:!0}),document.addEventListener("keyup",this.onKeyUp,{passive:!0,capture:!0}),this.reportInterval=setInterval(()=>this.report(),this.REPORT_INTERVAL_MS))}stop(){"undefined"!=typeof document&&(document.removeEventListener("keydown",this.onKeyDown,{capture:!0}),document.removeEventListener("keyup",this.onKeyUp,{capture:!0}),this.reportInterval&&(clearInterval(this.reportInterval),this.reportInterval=null),this.report())}report(){const t=this.tabCount+this.shiftTabCount;if(t<this.MIN_TABS_TO_REPORT)return;const e=this.calculateIntervals(this.tabTimestamps);if(e.length<3)return void this.resetBuffers();const i=this.analyzeIntervals(e),n=this.analyzeBursts(e),s=t>0?this.shiftTabCount/t:0;this.transmitter.send("tab_navigation_metrics",{tabCount:this.tabCount,shiftTabCount:this.shiftTabCount,shiftTabRatio:parseFloat(s.toFixed(4)),intervals:i,bursts:n,timestamp:Date.now()}),this.resetBuffers()}resetBuffers(){this.tabTimestamps=[],this.tabCount=0,this.shiftTabCount=0}calculateIntervals(t){const e=[];for(let i=1;i<t.length;i++){const n=t[i]-t[i-1];n<5e3&&e.push(n)}return e}analyzeIntervals(t){if(0===t.length)return{avg:0,variance:0,cv:0,min:0,samples:0};const e=t.reduce((t,e)=>t+e,0)/t.length,i=t.reduce((t,i)=>t+Math.pow(i-e,2),0)/t.length,n=Math.sqrt(i),s=e>0?n/e:0,r=Math.min(...t);return{avg:parseFloat(e.toFixed(2)),variance:parseFloat(i.toFixed(2)),cv:parseFloat(s.toFixed(4)),min:r,samples:t.length}}analyzeBursts(t){let e=0,i=0,n=0,s=0,r=0;for(const a of t)a<this.BURST_THRESHOLD_MS?(i++,s+=a,r++):(i>=3&&(e++,n+=i),i=0);return i>=3&&(e++,n+=i),{count:e,avgLength:e>0?parseFloat((n/e).toFixed(1)):0,avgInterval:r>0?parseFloat((s/r).toFixed(2)):0}}}class CloudEnvironmentDetector{constructor(t){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2e3))}async detect(){try{const t=this.analyzeGPU(),e=this.analyzeHardware(),i=this.analyzeScreen(),n=await this.analyzeMedia(),s=this.benchmarkCanvas();let r=0;"virtual_gpu"!==t.category&&"software_render"!==t.category&&"cloud_gpu"!==t.category||(r+=2),e.cores<=2&&r++,null!==e.memory&&e.memory<=2&&r++,24===e.colorDepth&&r++,1===e.pixelRatio&&r++,i.noTaskbar&&r++,i.isVMResolution&&r++,0===n.cameras&&0===n.microphones&&r++,n.hasBluetooth||n.hasUSB||r++,s.canvasRenderTime>50&&r++;const{classification:a,confidence:o}=this.classify(t,e,r);this.transmitter.send("cloud_environment",{classification:a,confidence:o,signals:{gpu:{renderer:t.renderer,vendor:t.vendor,category:t.category},hardware:e,screen:i,media:n,performance:s},vmIndicatorCount:r,timestamp:Date.now()})}catch(t){}}analyzeGPU(){try{const t=document.createElement("canvas"),e=t.getContext("webgl")||t.getContext("experimental-webgl");if(!e)return{renderer:"unavailable",vendor:"unavailable",category:"unknown"};const i=e.getExtension("WEBGL_debug_renderer_info");if(!i)return{renderer:"no_debug_info",vendor:"no_debug_info",category:"unknown"};const n=e.getParameter(i.UNMASKED_RENDERER_WEBGL)||"",s=e.getParameter(i.UNMASKED_VENDOR_WEBGL)||"";return{renderer:n,vendor:s,category:this.categorizeGPU(n,s)}}catch(t){return{renderer:"error",vendor:"error",category:"unknown"}}}categorizeGPU(t,e){const i=t.toLowerCase(),n=e.toLowerCase();return/swiftshader|llvmpipe|mesa offscreen|softpipe/.test(i)?"software_render":/svga3d|svga|vmware/.test(i)||/virtualbox/.test(i)||/parallels/.test(i)||/qxl|virtio|red hat|spice/.test(i)||/hyper-v|microsoft basic render/i.test(i)||/citrix/.test(i)?"virtual_gpu":/amazon|elastic|aws/.test(i)||/amazon|elastic|aws/.test(n)||/google cloud|gce/.test(i)||/google cloud|gce/.test(n)||/azure/.test(i)||/azure/.test(n)?"cloud_gpu":"physical"}analyzeHardware(){return{cores:navigator.hardwareConcurrency||0,memory:navigator.deviceMemory??null,colorDepth:screen.colorDepth,pixelRatio:window.devicePixelRatio||1}}analyzeScreen(){const t=screen.width,e=screen.height,i=screen.availHeight,n=e===i&&e===window.innerHeight,s=[[800,600],[1024,768],[1280,1024],[1280,800],[1920,1080]].some(([i,n])=>t===i&&e===n&&!(1920===i&&1080===n));return{width:t,height:e,availHeight:i,noTaskbar:n,isVMResolution:s}}async analyzeMedia(){let t=-1,e=-1;try{if(navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices){const i=await navigator.mediaDevices.enumerateDevices();t=i.filter(t=>"videoinput"===t.kind).length,e=i.filter(t=>"audioinput"===t.kind).length}}catch(r){}const i=!!navigator.bluetooth,n=!!navigator.usb;let s=null;try{if(navigator.getBattery){const t=await navigator.getBattery();s=!(t.charging&&1===t.level&&0===t.chargingTime)}}catch(r){}return{cameras:t,microphones:e,hasBluetooth:i,hasUSB:n,hasBattery:s}}benchmarkCanvas(){try{const t=document.createElement("canvas");t.width=200,t.height=200;const e=t.getContext("2d");if(!e)return{canvasRenderTime:-1};const i=performance.now();for(let s=0;s<500;s++)e.fillStyle=`rgb(${s%256},${3*s%256},${7*s%256})`,e.fillRect(13*s%200,7*s%200,10,10);e.getImageData(0,0,1,1);const n=performance.now()-i;return{canvasRenderTime:Math.round(100*n)/100}}catch(t){return{canvasRenderTime:-1}}}classify(t,e,i){return"virtual_gpu"===t.category?24===e.colorDepth?{classification:"rdp_likely",confidence:.85}:{classification:"vm_detected",confidence:.95}:"cloud_gpu"===t.category?{classification:"cloud_likely",confidence:.9}:"software_render"===t.category?{classification:"vm_detected",confidence:.9}:i>=5?{classification:"vm_likely",confidence:.8}:i>=3?{classification:"vm_likely",confidence:.6}:{classification:"physical",confidence:1-.1*i}}}class CrossContextDetector{constructor(t){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2500))}async detect(){var t,e;const i={};let n=0;const s={webdriver:!!navigator.webdriver,languages:(null==(t=navigator.languages)?void 0:t.join(","))||"",platform:navigator.platform||"",hardwareConcurrency:navigator.hardwareConcurrency||0,userAgent:navigator.userAgent||"",pluginsLength:(null==(e=navigator.plugins)?void 0:e.length)??0},r=this.checkIframe(s);r.score>0&&(i.iframe=r.mismatches,n+=r.score);try{const t=await this.checkWorker(s);t.score>0&&(i.worker=t.mismatches,n+=t.score)}catch(a){}n>0&&this.transmitter.send("cross_context_mismatch",{signals:i,score:n,timestamp:Date.now()})}checkIframe(t){var e,i;const n=[];let s=0;try{const r=document.createElement("iframe");r.style.display="none",r.sandbox="allow-same-origin",document.body.appendChild(r);const a=r.contentWindow;if(!a)return document.body.removeChild(r),{score:0,mismatches:[]};const o=a.navigator;o.webdriver!==navigator.webdriver&&(n.push("webdriver_mismatch"),s+=40),navigator.webdriver||!0!==o.webdriver||(n.push("webdriver_spoofed_in_main"),s+=30);((null==(e=o.languages)?void 0:e.join(","))||"")!==t.languages&&(n.push("languages_mismatch"),s+=15),o.platform!==t.platform&&(n.push("platform_mismatch"),s+=15);((null==(i=o.plugins)?void 0:i.length)??0)!==t.pluginsLength&&(n.push("plugins_mismatch"),s+=10),document.body.removeChild(r)}catch(r){}return{score:s,mismatches:n}}checkWorker(t){return new Promise(e=>{try{const i=new Blob(["\n self.onmessage = function() {\n var nav = self.navigator;\n self.postMessage({\n webdriver: !!nav.webdriver,\n languages: (nav.languages || []).join(','),\n platform: nav.platform || '',\n hardwareConcurrency: nav.hardwareConcurrency || 0,\n userAgent: nav.userAgent || ''\n });\n };\n "],{type:"application/javascript"}),n=URL.createObjectURL(i),s=new Worker(n),r=setTimeout(()=>{s.terminate(),URL.revokeObjectURL(n),e({score:0,mismatches:[]})},3e3);s.onmessage=i=>{clearTimeout(r),s.terminate(),URL.revokeObjectURL(n);const a=i.data,o=[];let c=0;a.webdriver!==t.webdriver&&(o.push("worker_webdriver_mismatch"),c+=35),a.languages!==t.languages&&(o.push("worker_languages_mismatch"),c+=15),a.platform!==t.platform&&(o.push("worker_platform_mismatch"),c+=15),a.hardwareConcurrency!==t.hardwareConcurrency&&(o.push("worker_concurrency_mismatch"),c+=10),a.userAgent!==t.userAgent&&(o.push("worker_ua_mismatch"),c+=20),e({score:c,mismatches:o})},s.onerror=()=>{clearTimeout(r),s.terminate(),URL.revokeObjectURL(n),e({score:0,mismatches:[]})},s.postMessage("check")}catch(i){e({score:0,mismatches:[]})}})}}class HeadlessProbeDetector{constructor(t){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2e3))}async detect(){const t={};let e=0;const i=await this.checkBrokenImage();i.suspicious&&(t.brokenImage=i,e+=25);const n=await this.checkClientHints();n.suspicious&&(t.clientHints=n,e+=20);const s=this.checkCDPMouseSignature();s.suspicious&&(t.cdpMouse=s,e+=30);const r=this.checkHairlineSupport();r.suspicious&&(t.hairline=r,e+=10);const a=this.checkExtraFrameworks();a.length>0&&(t.extraFrameworks=a,e+=20);(await this.checkWorkerCDP()).suspicious&&(t.workerCDP=!0,e+=35),e>0&&this.transmitter.send("headless_probe",{signals:t,score:e,timestamp:Date.now()})}checkBrokenImage(){return new Promise(t=>{try{const e=document.createElement("img");e.src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==___invalid";const i=setTimeout(()=>{t({suspicious:!1,width:-1,height:-1})},2e3);e.onerror=()=>{clearTimeout(i);const n=e.width,s=e.height;t({suspicious:0===n&&0===s,width:n,height:s})},e.onload=()=>{clearTimeout(i),t({suspicious:!1,width:e.width,height:e.height})},e.style.position="absolute",e.style.left="-9999px",document.body.appendChild(e),setTimeout(()=>{try{document.body.removeChild(e)}catch(t){}},100)}catch(e){t({suspicious:!1,width:-1,height:-1})}})}async checkClientHints(){const t=[];try{const e=navigator.userAgentData;if(!e)return{suspicious:!1,mismatches:[]};const i=navigator.userAgent,n=(e.brands||[]).map(t=>t.brand);/Chrome\/\d/.test(i)&&!n.some(t=>/Chromium|Google Chrome|Chrome/.test(t))&&t.push("ua_chrome_no_brand"),e.platform&&(/Windows/.test(i)&&"Windows"!==e.platform&&t.push("ua_windows_brand_mismatch"),/Macintosh/.test(i)&&"macOS"!==e.platform&&t.push("ua_mac_brand_mismatch"),/Linux/.test(i)&&!/Linux|Android|ChromeOS/.test(e.platform)&&t.push("ua_linux_brand_mismatch")),/Mobile/.test(i)&&!1===e.mobile&&t.push("ua_mobile_brand_mismatch")}catch(e){}return{suspicious:t.length>0,mismatches:t}}checkCDPMouseSignature(){let t=0,e=0,i=!1;try{const n=[],s=i=>{n.push(i),e++,0===i.movementX&&0===i.movementY&&t++};document.addEventListener("mousemove",s,{passive:!0}),setTimeout(()=>{document.removeEventListener("mousemove",s)},5e3),e>10&&t/e>.9&&(i=!0)}catch(n){}return{suspicious:i,zeroMovementCount:t,totalEvents:e}}checkHairlineSupport(){try{const t=document.createElement("div");t.style.border=".5px solid transparent",t.style.position="absolute",t.style.left="-9999px",document.body.appendChild(t);const e=t.offsetHeight;return document.body.removeChild(t),{suspicious:0===e,offsetHeight:e}}catch(t){return{suspicious:!1,offsetHeight:-1}}}checkExtraFrameworks(){const t=[];try{const i=window.external;if(i&&"function"==typeof i.toString)try{const e=i.toString();/Sequentum/i.test(e)&&t.push("sequentum")}catch(e){}const n=["__webdriver_script_fn","__webdriver_script_func","__webdriver_evaluate","__selenium_evaluate","__fxdriver_evaluate","__driver_evaluate","__webdriver_unwrapped","__selenium_unwrapped","__fxdriver_unwrapped","__driver_unwrapped","_Selenium_IDE_Recorder","_selenium","calledSelenium","_WEBDRIVER_ELEM_CACHE","ChromeDriverw","driver-hierarchical","__$webdriverAsyncExecutor","__lastWatirAlert","__lastWatirConfirm","__lastWatirPrompt","_WEBDRIVER_ELEM_CACHE","webdriver","_phantom","__nightmare","_selenium"];for(const e of n)(e in document||e in window)&&t.push(`global_${e}`);const s=Object.getOwnPropertyNames(navigator);for(const e of s)/webdriver|selenium|puppeteer|playwright|phantom/i.test(e)&&t.push(`nav_${e}`)}catch(e){}return t}checkWorkerCDP(){return new Promise(t=>{try{const e=new Blob(["\n self.onmessage = function() {\n var detected = false;\n try {\n var marker = {};\n Object.defineProperty(marker, 'stack', {\n get: function() { detected = true; return ''; }\n });\n console.debug(marker);\n } catch(e) {}\n self.postMessage({ cdp: detected });\n };\n "],{type:"application/javascript"}),i=URL.createObjectURL(e),n=new Worker(i),s=setTimeout(()=>{n.terminate(),URL.revokeObjectURL(i),t({suspicious:!1})},3e3);n.onmessage=e=>{clearTimeout(s),n.terminate(),URL.revokeObjectURL(i),t({suspicious:!0===e.data.cdp})},n.onerror=()=>{clearTimeout(s),n.terminate(),URL.revokeObjectURL(i),t({suspicious:!1})},n.postMessage("check")}catch(e){t({suspicious:!1})}})}}class ScriptInjectionDetector{constructor(t){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),__publicField(this,"injectedScriptCount",0),__publicField(this,"cspViolations",[]),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,this.startDOMObserver(),this.startCSPMonitor(),setTimeout(()=>this.detect(),1500))}detect(){const t={};let e=0;try{const i=this.checkNativeFunctionIntegrity();i.issues.length>0&&(t.nativeFunctionIntegrity=i.issues,e+=25)}catch(i){}try{const i=this.checkPropertyOverrides();i.issues.length>0&&(t.propertyOverrides=i.issues,e+=30)}catch(i){}this.injectedScriptCount>0&&(t.domScriptInjection={count:this.injectedScriptCount},e+=20),this.cspViolations.length>0&&(t.cspViolations=this.cspViolations.slice(0,10),e+=15);try{const i=this.checkGlobalPollution();i.length>0&&(t.globalPollution=i,e+=20)}catch(i){}try{const i=this.checkPrototypeIntegrity();i.length>0&&(t.prototypeIntegrity=i,e+=20)}catch(i){}e>0&&this.transmitter.send("script_injection",{signals:t,score:e,timestamp:Date.now()})}checkNativeFunctionIntegrity(){const t=[];try{const e=Object.getOwnPropertyDescriptor(navigator,"webdriver");if(e&&(!0===e.configurable&&t.push("webdriver_descriptor_configurable"),e.get)){const i=Function.prototype.toString.call(e.get);/\[native code\]/.test(i)||t.push("webdriver_non_native_getter")}}catch(e){}try{const e=["userAgent","platform","languages","hardwareConcurrency"];for(const i of e){const e=Object.getOwnPropertyDescriptor(Navigator.prototype,i);if(e&&e.get){const n=Function.prototype.toString.call(e.get);/\[native code\]/.test(n)||t.push(`navigator_${i}_non_native`)}}}catch(e){}try{const e=Function.prototype.toString.call(Function.prototype.toString);/\[native code\]/.test(e)||t.push("function_tostring_overridden")}catch(e){}return{issues:t}}checkPropertyOverrides(){const t=[];try{"[object Navigator]"!==Object.prototype.toString.call(navigator)&&t.push("navigator_proxy_or_spoofed")}catch(e){}try{if(navigator.plugins){"[object PluginArray]"!==Object.prototype.toString.call(navigator.plugins)&&t.push("plugins_spoofed"),Array.isArray(navigator.plugins)&&t.push("plugins_is_array")}}catch(e){}try{if(navigator.mimeTypes){"[object MimeTypeArray]"!==Object.prototype.toString.call(navigator.mimeTypes)&&t.push("mimetypes_spoofed")}}catch(e){}try{const e=Function.prototype.toString.call(Object.getOwnPropertyDescriptor);/\[native code\]/.test(e)||t.push("getOwnPropertyDescriptor_overridden")}catch(e){}return{issues:t}}startDOMObserver(){try{if("undefined"==typeof MutationObserver)return;const t=new MutationObserver(t=>{for(const e of t)for(let t=0;t<e.addedNodes.length;t++){const i=e.addedNodes[t];if("SCRIPT"===i.nodeName){i.src||this.injectedScriptCount++}}});t.observe(document.documentElement,{childList:!0,subtree:!0}),setTimeout(()=>{try{t.disconnect()}catch(e){}},1e4)}catch(t){}}startCSPMonitor(){try{const t=t=>{try{const e=`${t.violatedDirective}|${t.blockedURI||"inline"}`;this.cspViolations.push(e)}catch(e){}};document.addEventListener("securitypolicyviolation",t),setTimeout(()=>{try{document.removeEventListener("securitypolicyviolation",t)}catch(e){}},1e4)}catch(t){}}checkGlobalPollution(){const t=[],e=window,i=document,n=[["__webdriver_evaluate",()=>!!i.__webdriver_evaluate],["__selenium_evaluate",()=>!!i.__selenium_evaluate],["__webdriver_script_function",()=>!!i.__webdriver_script_function],["__webdriver_script_func",()=>!!i.__webdriver_script_func],["__webdriver_script_fn",()=>!!i.__webdriver_script_fn],["_Selenium_IDE_Recorder",()=>!!e._Selenium_IDE_Recorder],["__lastWatirAlert",()=>!!e.__lastWatirAlert],["__lastWatirConfirm",()=>!!e.__lastWatirConfirm],["__lastWatirPrompt",()=>!!e.__lastWatirPrompt],["_phantom",()=>!!e._phantom],["callPhantom",()=>!!e.callPhantom],["__nightmare",()=>!!e.__nightmare],["Buffer",()=>"function"==typeof e.Buffer&&"function"==typeof e.Buffer.alloc],["process",()=>!!e.process&&!!e.process.versions],["global_redefined",()=>!!e.global&&e.global!==e&&"object"==typeof e.global],["window_emit",()=>"function"==typeof e.emit]];for(const[r,a]of n)try{a()&&t.push(r)}catch(s){}try{const e=Object.keys(document);for(const i of e)/^cdc_|^__cdc_/.test(i)&&t.push(`cdc:${i}`)}catch(s){}try{const e=Object.keys(window);for(const i of e)/^cdc_|^__cdc_/.test(i)&&t.push(`cdc_window:${i}`)}catch(s){}return t}checkPrototypeIntegrity(){const t=[];try{const e=HTMLElement.prototype,i=Object.getOwnPropertyNames(e);for(const n of i)/^__selenium|^__webdriver|^__playwright|^__puppeteer/.test(n)&&t.push(`htmlelement_proto_${n}`)}catch(e){}try{const e=document.createElement("div");e instanceof HTMLDivElement||t.push("createElement_not_genuine");"[object HTMLDivElement]"!==Object.prototype.toString.call(e)&&t.push("createElement_wrong_tostring")}catch(e){}try{const e=new Event("test");e instanceof Event||t.push("event_not_instance");"[object Event]"!==Object.prototype.toString.call(e)&&t.push("event_wrong_prototype")}catch(e){}try{const e=Function.prototype.toString.call(document.createElement);/\[native code\]/.test(e)||t.push("createElement_overridden")}catch(e){}return t}}class WorkerIntegrityDetector{constructor(t){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2e3))}async detect(){try{if("undefined"==typeof Worker||"undefined"==typeof Blob)return;const e={webdriver:!!navigator.webdriver,userAgent:navigator.userAgent||"",platform:navigator.platform||"",languages:JSON.stringify(navigator.languages||[]),hardwareConcurrency:navigator.hardwareConcurrency||0,dateNow:Date.now(),perfNow:performance.now(),toStringNative:!1};try{e.toStringNative=/\[native code\]/.test(Function.prototype.toString.call(Array.prototype.push))}catch(t){e.toStringNative=!1}const i=await this.runWorker(e);if(!i)return;const n={};let s=0;const r=[];e.webdriver||!0!==i.webdriver?i.webdriver!==e.webdriver&&(r.push("webdriver_mismatch"),s+=30):(r.push("webdriver_spoofed"),s+=40),i.userAgent!==e.userAgent&&(r.push("userAgent_mismatch"),s+=30),i.platform!==e.platform&&(r.push("platform_mismatch"),s+=30),i.languages!==e.languages&&(r.push("languages_mismatch"),s+=30),i.hardwareConcurrency!==e.hardwareConcurrency&&(r.push("hardwareConcurrency_mismatch"),s+=30),r.length>0&&(n.navigatorMismatch=r);const a=i.benchmarkMs;"number"==typeof a&&(a<1||a>500)&&(n.benchmarkAnomaly={benchmarkMs:a,reason:a<1?"abnormally_fast":"abnormally_slow"},s+=20),!1===i.cryptoEntropy&&(n.cryptoMock={entropy:!1,values:i.cryptoValues},s+=15);const o=Math.abs(i.dateNow-e.dateNow);if(o>1e3&&(n.timeManipulation={mainDateNow:e.dateNow,workerDateNow:i.dateNow,deltaMs:o},s+=15),!i.toStringNative||!e.toStringNative){const t=[];i.toStringNative||t.push("worker_tampered"),e.toStringNative||t.push("main_tampered"),n.toStringTampering=t,s+=20}s>0&&this.transmitter.send("worker_integrity",{signals:n,score:s,timestamp:Date.now()})}catch(t){}}runWorker(t){return new Promise(e=>{try{const i=new Blob(["\n self.onmessage = function(e) {\n var results = {};\n\n // 1. Navigator check\n try {\n results.webdriver = !!navigator.webdriver;\n results.userAgent = navigator.userAgent || '';\n results.platform = navigator.platform || '';\n results.languages = JSON.stringify(navigator.languages || []);\n results.hardwareConcurrency = navigator.hardwareConcurrency || 0;\n } catch(ex) {\n results.webdriver = false;\n results.userAgent = '';\n results.platform = '';\n results.languages = '[]';\n results.hardwareConcurrency = 0;\n }\n\n // 2. Performance benchmark\n try {\n var start = performance.now();\n var sum = 0;\n for (var i = 0; i < 1000000; i++) sum += i;\n results.benchmarkMs = performance.now() - start;\n } catch(ex) {\n results.benchmarkMs = -1;\n }\n\n // 3. Crypto check\n try {\n var arr = new Uint32Array(4);\n crypto.getRandomValues(arr);\n results.cryptoEntropy = arr[0] !== arr[1] && arr[1] !== arr[2] && arr[0] !== 0;\n results.cryptoValues = Array.from(arr);\n } catch(ex) {\n results.cryptoEntropy = false;\n results.cryptoValues = [];\n }\n\n // 4. Time check\n results.dateNow = Date.now();\n results.perfNow = performance.now();\n\n // 5. toString integrity\n try {\n results.toStringNative = /\\[native code\\]/.test(\n Function.prototype.toString.call(Array.prototype.push)\n );\n } catch(ex) {\n results.toStringNative = false;\n }\n\n self.postMessage(results);\n };\n "],{type:"application/javascript"}),n=URL.createObjectURL(i),s=new Worker(n),r=setTimeout(()=>{s.terminate(),URL.revokeObjectURL(n),e(null)},5e3);s.onmessage=t=>{clearTimeout(r),s.terminate(),URL.revokeObjectURL(n),e(t.data)},s.onerror=()=>{clearTimeout(r),s.terminate(),URL.revokeObjectURL(n),e(null)},s.postMessage({mainValues:t})}catch(i){e(null)}})}}class CrawlProtect{constructor(t){__publicField(this,"config"),__publicField(this,"renewTimer",null),__publicField(this,"verified",!1),this.config=t}async start(){const t=this.getToken();if(t&&!this.isExpired(t))return this.verified=!0,this.scheduleRenewal(t),this.revealContent(),this.config.debug,!0;this.hideContent();const e=await this.solveChallenge();return e?(this.verified=!0,this.revealContent()):this.config.insertHoneypot&&this.insertHoneypotData(),e}isVerified(){return this.verified}stop(){this.renewTimer&&(clearTimeout(this.renewTimer),this.renewTimer=null)}async solveChallenge(){try{const t=await fetch(`${this.config.apiBase}/crawl-protect/challenge`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":this.config.clientId}});if(!t.ok)return!1;const{id:e,challenges:i}=await t.json(),n=[];for(const c of i)if("math"===c.type){const t="add"===c.op?c.a+c.b:c.a*c.b;n.push(String(t))}else if("crypto"===c.type){const t=await this.sha256(c.nonce);n.push(t.slice(0,8))}const s=n.join(":"),r=await this.getFingerprint(),a=await fetch(`${this.config.apiBase}/crawl-protect/verify`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":this.config.clientId},body:JSON.stringify({id:e,solution:s,fingerprint:r}),credentials:"include"});if(!a.ok)return!1;const o=await a.json();return!(!o.success||!o.token)&&(this.setToken(o.token),this.scheduleRenewal(o.token),this.config.debug,!0)}catch(t){return this.config.debug,!1}}hideContent(){var t;if(null==(t=this.config.protectSelectors)?void 0:t.length)for(const e of this.config.protectSelectors){document.querySelectorAll(e).forEach(t=>{t.dataset.aieOrigDisplay=t.style.display,t.style.display="none"})}}revealContent(){var t;if(null==(t=this.config.protectSelectors)?void 0:t.length)for(const e of this.config.protectSelectors){document.querySelectorAll(e).forEach(t=>{t.style.display=t.dataset.aieOrigDisplay||"",delete t.dataset.aieOrigDisplay})}}insertHoneypotData(){const t=document.createElement("div");t.style.cssText="position:absolute;left:-9999px;top:-9999px;opacity:0;pointer-events:none;",t.setAttribute("aria-hidden","true"),t.innerHTML='\n <span class="price" data-aie-honeypot="1">₩999,999,999</span>\n <span class="stock" data-aie-honeypot="1">재고: 0개</span>\n <a href="mailto:honeypot@aientrophy.com" data-aie-honeypot="1">contact</a>\n ',document.body.appendChild(t)}getToken(){const t=document.cookie.match(new RegExp("(?:^|; )__aie_token=([^;]*)"));return t?decodeURIComponent(t[1]):null}setToken(t){const e=new Date(Date.now()+18e5).toUTCString();document.cookie=`__aie_token=${encodeURIComponent(t)};path=/;expires=${e};SameSite=None;Secure`}isExpired(t){try{const[e]=t.split("."),i=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return Date.now()>i.exp}catch{return!0}}scheduleRenewal(t){try{const[e]=t.split("."),i=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/"))),n=i.exp-3e5-Date.now();n>0&&(this.renewTimer=setTimeout(()=>this.solveChallenge(),n))}catch{}}async sha256(t){const e=new TextEncoder,i=await crypto.subtle.digest("SHA-256",e.encode(t));return Array.from(new Uint8Array(i)).map(t=>t.toString(16).padStart(2,"0")).join("")}async getFingerprint(){const t=[navigator.userAgent,navigator.language,screen.width+"x"+screen.height,Intl.DateTimeFormat().resolvedOptions().timeZone];return this.sha256(t.join("|"))}}const securitySDK=new class{constructor(){__publicField(this,"transmitter"),__publicField(this,"behaviorCollector"),__publicField(this,"rapidClickDetector"),__publicField(this,"honeypot"),__publicField(this,"mouseTracker"),__publicField(this,"canvasFingerprinter"),__publicField(this,"inputTracker"),__publicField(this,"challengeHandler"),__publicField(this,"invisibleInteraction"),__publicField(this,"automationDetector"),__publicField(this,"sessionAnalyzer"),__publicField(this,"tabNavigationAnalyzer"),__publicField(this,"cloudEnvironmentDetector"),__publicField(this,"crossContextDetector"),__publicField(this,"headlessProbeDetector"),__publicField(this,"scriptInjectionDetector"),__publicField(this,"workerIntegrityDetector"),__publicField(this,"crawlProtect",null),__publicField(this,"initialized",!1),__publicField(this,"wasmService"),__publicField(this,"callbackManager"),this.transmitter=new Transmitter,this.wasmService=new WasmService,this.callbackManager=new CallbackManager,this.transmitter.setCallbackManager(this.callbackManager),this.behaviorCollector=new BehaviorCollector(this.transmitter),this.rapidClickDetector=new RapidClickDetector(this.transmitter),this.honeypot=new Honeypot(this.transmitter),this.mouseTracker=new MouseTracker(this.transmitter,this.wasmService),this.canvasFingerprinter=new CanvasFingerprinter(this.transmitter,this.wasmService),this.inputTracker=new InputTracker(this.transmitter),this.invisibleInteraction=new InvisibleInteraction(this.transmitter),this.automationDetector=new AutomationDetector(this.transmitter),this.sessionAnalyzer=new SessionAnalyzer(this.transmitter),this.tabNavigationAnalyzer=new TabNavigationAnalyzer(this.transmitter),this.cloudEnvironmentDetector=new CloudEnvironmentDetector(this.transmitter),this.crossContextDetector=new CrossContextDetector(this.transmitter),this.headlessProbeDetector=new HeadlessProbeDetector(this.transmitter),this.scriptInjectionDetector=new ScriptInjectionDetector(this.transmitter),this.workerIntegrityDetector=new WorkerIntegrityDetector(this.transmitter)}async init(t){var e,i;if(this.initialized)return;t.callbacks&&this.callbackManager.setConfigCallbacks(t.callbacks);const n=t.endpoint.replace(/\/events$/,"");try{await this.wasmService.load(n),this.startDetectors(),this.transmitter.setConfig(t),this.challengeHandler=new ChallengeHandler(n),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-JDCTbZps.cjs")).then(({AntiDebug:t})=>{t.start(),t.setOnDevtoolsMaxed(()=>{this.transmitter.send("devtools_force_close",{reason:"devtools_threshold_exceeded",detectionCount:3,maxThreat:!0})}),Promise.resolve().then(()=>require("../console-CSDO1Iwi.cjs")).then(({ConsoleDetector:t})=>{new t(()=>{this.transmitter.send("devtools_open",{detected:!0})}).start()})}),t.crawlProtect&&(this.crawlProtect=new CrawlProtect({apiBase:n,clientId:t.clientKey,protectSelectors:t.crawlProtect.protectSelectors,insertHoneypot:t.crawlProtect.insertHoneypot,debug:t.debug}),this.crawlProtect.start().catch(e=>{t.debug})),this.initialized=!0,t.debug,this.callbackManager.emit("ready")}catch(s){this.callbackManager.emit("error",{code:"INIT_ERROR",message:"SecuritySDK initialization failed",details:null==s?void 0:s.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.behaviorCollector.start(),this.honeypot.start(),this.mouseTracker.start(),this.canvasFingerprinter.start(),this.inputTracker.start(),this.invisibleInteraction.start(),this.automationDetector.start(),this.sessionAnalyzer.start(),this.tabNavigationAnalyzer.start(),this.cloudEnvironmentDetector.start(),this.crossContextDetector.start(),this.headlessProbeDetector.start(),this.scriptInjectionDetector.start(),this.workerIntegrityDetector.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 n=t.replace(/\/events$/,""),s=await fetch(`${n}/sdk/payload?clientKey=${encodeURIComponent(this.config.clientKey)}`);if(s.ok){e=(await s.json()).config||{}}if(e.nonceValidation)try{const t=await fetch(`${n}/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,crawlProtect:this.config.crawlProtect,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)try{await this.initECDH()}catch(t){await this.initRSA()}}static async initECDH(){const t=await window.crypto.subtle.generateKey({name:"ECDH",namedCurve:"P-256"},!0,["deriveBits"]),e=await window.crypto.subtle.exportKey("raw",t.publicKey);this.ecdhPublicKeyBase64=this.arrayBufferToBase64(e);const i=(window.__securitySDKEndpoint||"").replace(/\/events$/,""),n=await fetch(`${i}/key-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientPublicKey:this.ecdhPublicKeyBase64})});if(!n.ok)throw new Error("Key exchange failed");const{serverPublicKey:s,salt:r}=await n.json(),a=this.base64ToArrayBuffer(s),o=await window.crypto.subtle.importKey("raw",a,{name:"ECDH",namedCurve:"P-256"},!1,[]),c=await window.crypto.subtle.deriveBits({name:"ECDH",public:o},t.privateKey,256),l=await window.crypto.subtle.importKey("raw",c,"HKDF",!1,["deriveKey"]),h=this.base64ToArrayBuffer(r);this.sessionKey=await window.crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:h,info:(new TextEncoder).encode("aientrophy-session-enc")},l,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),this.protocolVersion=2}static async initRSA(){this.sessionKey=await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]);const t=await this.importRSAPublicKey(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),this.protocolVersion=1}static async encrypt(t){this.sessionKey||await this.init();const e=JSON.stringify(t),i=(new TextEncoder).encode(e),n=window.crypto.getRandomValues(new Uint8Array(12)),s=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:n},this.sessionKey,i),r=new Uint8Array(s),a=r.slice(0,r.length-16),o=r.slice(r.length-16),c={ek:2===this.protocolVersion?this.ecdhPublicKeyBase64:this.encryptedSessionKey,d:this.arrayBufferToBase64(a.buffer),iv:this.arrayBufferToBase64(n.buffer),tag:this.arrayBufferToBase64(o.buffer)};return 2===this.protocolVersion&&(c.v=2),c}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),n=this.base64ToArrayBuffer(t.tag),s=new Uint8Array(e.byteLength+n.byteLength);s.set(new Uint8Array(e),0),s.set(new Uint8Array(n),e.byteLength);const r=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:i},this.sessionKey,s),a=(new TextDecoder).decode(r);return JSON.parse(a)}static setEndpoint(t){window.__securitySDKEndpoint=t}static async importRSAPublicKey(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 n=0,s=t.length;n<s;n++)i[n]=t.charCodeAt(n);return e}static arrayBufferToBase64(t){let e="";const i=new Uint8Array(t),n=i.byteLength;for(let s=0;s<n;s++)e+=String.fromCharCode(i[s]);return window.btoa(e)}static base64ToArrayBuffer(t){const e=window.atob(t),i=e.length,n=new Uint8Array(i);for(let s=0;s<i;s++)n[s]=e.charCodeAt(s);return n.buffer}}__publicField(CryptoUtils,"sessionKey",null),__publicField(CryptoUtils,"ecdhPublicKeyBase64",null),__publicField(CryptoUtils,"encryptedSessionKey",null),__publicField(CryptoUtils,"protocolVersion",2);const THREAT_EVENTS=new Set(["rapid_click","honeypot_triggered","devtools_open","invisible_interaction","integrity_violation","dom_mutation","behavior_metrics","behavior_analysis","input_metrics","keystroke_dynamics","environmental_integrity","init_signals","automation_detected","cross_context_mismatch","headless_probe","script_injection","worker_integrity"]);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 n=i.filter(t=>t.handler!==e);0===n.length?this.handlers.delete(t):this.handlers.set(t,n)}emit(t,...e){this.callHandlers(t,e);const i=t.indexOf(":");if(-1!==i){const n=t.substring(0,i);this.callHandlers(n,e)}this.callConfigCallback(t,e)}emitChallenge(t){return new Promise(e=>{let i=!1;const n=t=>{i||(i=!0,e(t))},s=this.handlers.has("challenge")&&this.handlers.get("challenge").length>0,r=!!this.configCallbacks.onChallenge;s||r?(this.callHandlers("challenge",[t,n]),this.configCallbacks.onChallenge&&this.safeCall(this.configCallbacks.onChallenge,[t,n]),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 n=[];for(let s=0;s<i.length;s++)this.safeCall(i[s].handler,e),i[s].once&&n.push(s);for(let s=n.length-1;s>=0;s--)i.splice(n[s],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",20),__publicField(this,"flushInterval",5e3),__publicField(this,"intervalId"),__publicField(this,"responseHandler",null),__publicField(this,"callbackManager",null),__publicField(this,"flushing",!1),__publicField(this,"pendingFlush",!1),__publicField(this,"backoffMs",0),__publicField(this,"maxBackoffMs",6e4),__publicField(this,"_lastBackoffStart",0),this.startFlushInterval()}setConfig(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)??"",CryptoUtils.setEndpoint(t.endpoint)}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 n={type:t,data:e,timestamp:i};this.callbackManager.emit(`threat:${t}`,n)}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.backoffMs>0){const t=Date.now();if(this._lastBackoffStart||(this._lastBackoffStart=t),t-this._lastBackoffStart<this.backoffMs)return;this._lastBackoffStart=0}if(this.flushing)return void(this.pendingFlush=!0);this.flushing=!0;const t=this.buffer;this.buffer=[];try{let n;if(this.encryptionRequired){const e=await CryptoUtils.encrypt(t);n=JSON.stringify(e)}else n=JSON.stringify(t);const s={"Content-Type":"application/json","x-client-key":this.clientKey};this.currentNonce&&(s["x-request-nonce"]=this.currentNonce,this.currentNonce="");try{const i=await fetch(this.endpoint,{method:"POST",body:n,headers:s,keepalive:!0});if(429===i.status)return this.buffer=t.concat(this.buffer).slice(0,500),this.backoffMs=0===this.backoffMs?5e3:Math.min(2*this.backoffMs,this.maxBackoffMs),void(this._lastBackoffStart=Date.now());if(this.backoffMs=0,i.ok&&this.callbackManager&&this.callbackManager.emit("allow",{action:"allow"}),i.ok)try{const t=await i.json();let e=t;this.encryptionRequired&&(e=await CryptoUtils.decrypt(t)),(null==e?void 0:e.nonce)&&(this.currentNonce=e.nonce),this.responseHandler&&this.responseHandler(e)}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 BehaviorCollector{constructor(t){__publicField(this,"transmitter"),__publicField(this,"isCollecting",!1),this.transmitter=t}start(){this.isCollecting||(this.isCollecting=!0)}stop(){this.isCollecting=!1}}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,n={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:n,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 n=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",n),this.element.addEventListener("focus",n),this.element.addEventListener("click",n),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",50),__publicField(this,"SAMPLE_INTERVAL",100),__publicField(this,"SEND_COOLDOWN",5e3),__publicField(this,"lastSampleTime",0),__publicField(this,"lastSendTime",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.buffer.length>=this.BUFFER_SIZE&&e-this.lastSendTime>=this.SEND_COOLDOWN&&(this.analyze(),this.lastSendTime=e))}),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<20)return;const t=this.wasmService.calculateEntropy(this.buffer),e=this.calculateSpeedVariance(),i=this.buffer.map(t=>({x:t.x,y:t.y,t:t.time}));this.transmitter.send("behavior_metrics",{entropy:t,speedVariance:e,sampleSize:this.buffer.length,timestamp:Date.now(),rawTrajectory:i})}calculateSpeedVariance(){const t=[];for(let i=1;i<this.buffer.length;i++){const e=this.buffer[i-1],n=this.buffer[i],s=Math.sqrt(Math.pow(n.x-e.x,2)+Math.pow(n.y-e.y,2)),r=n.time-e.time;r>0&&t.push(s/r)}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),__publicField(this,"rawKeystrokes",[]),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.rawKeystrokes=[],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.rawKeystrokes.push({code:t.code,t:i,type:"down"}),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,this.rawKeystrokes.push({code:t.code,t:i,type:"up"});const n=this.keyPressTimes.get(t.code);if(n){const e=i-n;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()<5e3||(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=0)}reportKeystrokeDynamics(t){const e=this.average(this.flightTimes),i=this.variance(this.flightTimes,e),n=this.average(this.dwellTimes),s=this.variance(this.dwellTimes,n);this.transmitter.send("input_metrics",{element:t.id||t.tagName,flight:{avg:e,variance:i,samples:this.flightTimes.length},dwell:{avg:n,variance:s},isMobile:this.isMobile,timestamp:Date.now(),rawKeystrokes:[...this.rawKeystrokes]}),this.flightTimes=[],this.dwellTimes=[],this.rawKeystrokes=[]}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(),n=await WebAssembly.instantiate(t,i);this.instance=n.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 n=this.wasmModule.__new(i,0),s=new Float64Array(this.memory.buffer,n,e);for(let e=0;e<t.length;e++)s[2*e]=t[e].x,s[2*e+1]=t[e].y;return this.wasmModule.calculateEntropy(n,e)}catch(n){return 0}}simpleHash(t){if(!this.instance||!this.wasmModule)return 0;try{const e=(new TextEncoder).encode(t),i=e.length,n=this.wasmModule.__new(i,0);return new Uint8Array(this.memory.buffer,n,i).set(e),this.wasmModule.simpleHash(n,i)}catch(e){return 0}}}class CanvasFingerprinter{constructor(t,e){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof document||setTimeout(async()=>{const t=await this.generateFingerprint(),e=this.collectWebGLFingerprint(),i=this.collectAudioFingerprint();this.transmitter.send("fingerprint_collected",{hash:t,webgl:e,audio:i}),this.hasRun=!0},500)}async 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();return await this.sha256(i)}catch(t){return"error"}}async sha256(t){const e=(new TextEncoder).encode(t),i=await window.crypto.subtle.digest("SHA-256",e),n=new Uint8Array(i);return Array.from(n).map(t=>t.toString(16).padStart(2,"0")).join("")}collectWebGLFingerprint(){try{const t=document.createElement("canvas"),e=t.getContext("webgl")||t.getContext("experimental-webgl");if(!e)return{available:!1};const i=e,n={available:!0},s=i.getExtension("WEBGL_debug_renderer_info");return s&&(n.renderer=i.getParameter(s.UNMASKED_RENDERER_WEBGL),n.vendor=i.getParameter(s.UNMASKED_VENDOR_WEBGL)),n.maxTextureSize=i.getParameter(i.MAX_TEXTURE_SIZE),n.maxViewportDims=Array.from(i.getParameter(i.MAX_VIEWPORT_DIMS)),n.maxRenderbufferSize=i.getParameter(i.MAX_RENDERBUFFER_SIZE),n.maxVertexAttribs=i.getParameter(i.MAX_VERTEX_ATTRIBS),n.extensions=(i.getSupportedExtensions()||[]).length,n}catch(t){return{available:!1,error:!0}}}collectAudioFingerprint(){try{const t=window.AudioContext||window.webkitAudioContext;if(!t)return{available:!1};const e=new t,i={available:!0,sampleRate:e.sampleRate,state:e.state,maxChannels:e.destination.maxChannelCount};return e.close(),i}catch(t){return{available:!1}}}}class ChallengeHandler{constructor(t){__publicField(this,"originalFetch"),__publicField(this,"endpoint"),__publicField(this,"callbackManager",null),__publicField(this,"challengeInProgress",null),this.endpoint=t,this.originalFetch=window.fetch.bind(window)}setCallbackManager(t){this.callbackManager=t}start(){window.fetch=async(t,e)=>{var i;const n=await this.originalFetch(t,e);if(403===n.status){const r=n.clone();try{const s=await r.json();if("challenge"===s.action&&"captcha"===(null==(i=s.metadata)?void 0:i.type)){const i={action:"challenge",score:s.score,metadata:s.metadata};if(this.callbackManager){if(await this.callbackManager.emitChallenge(i))return this.originalFetch(t,e)}this.challengeInProgress||(this.challengeInProgress=this.showCaptchaModal().finally(()=>{this.challengeInProgress=null}));return await this.challengeInProgress?this.originalFetch(t,e):n}"block"===s.action&&this.callbackManager&&this.callbackManager.emit("block",{action:"block",score:s.score,metadata:s.metadata})}catch(s){}}return n}}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"}),n=document.createElement("div");n.style.background="white",n.style.padding="20px",n.style.borderRadius="8px",n.style.boxShadow="0 4px 12px rgba(0,0,0,0.2)",n.style.textAlign="center",n.style.fontFamily="system-ui, sans-serif";const s=document.createElement("h3");s.textContent="Security Check",s.style.margin="0 0 16px 0";const r=document.createElement("p");r.textContent="Unusual activity detected. Please verify you are human.",r.style.marginBottom="16px",r.style.fontSize="14px",r.style.color="#666";const a=document.createElement("div");a.innerHTML="Loading...",a.style.marginBottom="16px";const o=document.createElement("input");o.type="text",o.placeholder="Enter details",o.style.padding="8px",o.style.marginRight="8px",o.style.border="1px solid #ddd",o.style.borderRadius="4px";const c=document.createElement("button");c.textContent="Verify",c.style.padding="8px 16px",c.style.background="#007bff",c.style.color="white",c.style.border="none",c.style.borderRadius="4px",c.style.cursor="pointer";const l=document.createElement("p");l.style.color="red",l.style.fontSize="12px",l.style.display="none",n.appendChild(s),n.appendChild(r),n.appendChild(a),n.appendChild(o),n.appendChild(c),n.appendChild(l),i.appendChild(n),document.body.appendChild(e);let h="";const u=async()=>{try{const t=await this.originalFetch(`${this.endpoint}/challenge`),e=await t.json();h=e.id,a.innerHTML=e.svg}catch(t){a.textContent="Error loading CAPTCHA"}},d=async()=>{l.style.display="none",c.textContent="Verifying...";try{const i=o.value,n=await this.originalFetch(`${this.endpoint}/challenge/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:h,answer:i})});(await n.json()).success?(document.body.removeChild(e),t(!0)):(l.textContent="Incorrect, try again.",l.style.display="block",c.textContent="Verify",o.value="",u())}catch(i){l.textContent="System error.",l.style.display="block",c.textContent="Verify"}};c.onclick=d,o.onkeydown=t=>{"Enter"===t.key&&d()},u()})}}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 n=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:n.top,left:n.left,width:n.width,height:n.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,n;const s=window.getComputedStyle(t);if("none"===s.display)return"display:none";if("hidden"===s.visibility)return"visibility:hidden";if("0"===s.opacity)return"opacity:0";const r=t.getBoundingClientRect();if(r.width<=0||r.height<=0)return"zero_size";const a=r.right<0||r.left>window.innerWidth,o=r.bottom<0||r.top>window.innerHeight;if(a||o)return"off_screen";if(e instanceof MouseEvent||e instanceof TouchEvent){let s,r;if(e instanceof MouseEvent?(s=e.clientX,r=e.clientY):(s=(null==(i=e.touches[0])?void 0:i.clientX)||0,r=(null==(n=e.touches[0])?void 0:n.clientY)||0),s>=0&&s<=window.innerWidth&&r>=0&&r<=window.innerHeight){const i=document.elementFromPoint(s,r);if(i&&i!==t&&!t.contains(i)&&!i.contains(t)&&0===s&&0===r&&e.isTrusted)return null}}return null}}class AutomationDetector{constructor(t){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(setTimeout(()=>this.detect(),1500),this.hasRun=!0)}detect(){var t,e;const i={};let n=0;!0===navigator.webdriver&&(i.webdriver=!0,n+=40);try{this.detectCDP()&&(i.cdp=!0,n+=50)}catch(c){}const s=this.detectAutomationGlobals();s.length>0&&(i.automationGlobals=s,n+=30);const r=this.checkWebGL();r.suspicious&&(i.webgl=r,n+=25);const a=this.checkInconsistencies();a.length>0&&(i.inconsistencies=a,n+=15);const o=this.checkHeadless();o.score>0&&(i.headless=o.flags,n+=o.score),n>0&&this.transmitter.send("automation_detected",{signals:i,score:n,timestamp:Date.now()}),this.transmitter.send("init_signals",{webdriver:!!navigator.webdriver,plugins:(null==(t=navigator.plugins)?void 0:t.length)??0,languages:(null==(e=navigator.languages)?void 0:e.length)??0,platform:navigator.platform,hardwareConcurrency:navigator.hardwareConcurrency,deviceMemory:navigator.deviceMemory,maxTouchPoints:navigator.maxTouchPoints,webglRenderer:r.renderer,webglVendor:r.vendor,timestamp:Date.now()})}detectCDP(){const t=console.debug;return console.debug=t,!1}detectAutomationGlobals(){const t=[],e=[["selenium",()=>!!window._selenium],["selenium_unwrapped",()=>!!document.__selenium_unwrapped],["driver_evaluate",()=>!!document.__driver_evaluate],["webdriver_evaluate",()=>!!document.__webdriver_evaluate],["driver_unwrapped",()=>!!document.__driver_unwrapped],["fxdriver",()=>!!document.__fxdriver_evaluate],["playwright",()=>!!window.__playwright],["playwright_binding",()=>!!window.__playwright__binding__],["pwInitScripts",()=>!!window.__pwInitScripts],["puppeteer",()=>!!window.__puppeteer_evaluation_script__],["phantom",()=>!!window.callPhantom||!!window._phantom],["nightmare",()=>!!window.__nightmare],["cdc",()=>Object.keys(document).some(t=>t.startsWith("cdc_")||t.startsWith("$cdc_"))]];for(const[n,s]of e)try{s()&&t.push(n)}catch(i){}return t}checkWebGL(){try{const t=document.createElement("canvas"),e=t.getContext("webgl")||t.getContext("experimental-webgl");if(!e)return{suspicious:!1,renderer:"unavailable",vendor:"unavailable"};const i=e.getExtension("WEBGL_debug_renderer_info");if(!i)return{suspicious:!1,renderer:"no_debug_info",vendor:"no_debug_info"};const n=e.getParameter(i.UNMASKED_RENDERER_WEBGL)||"",s=e.getParameter(i.UNMASKED_VENDOR_WEBGL)||"";return{suspicious:/SwiftShader/i.test(n)||/Mesa OffScreen/i.test(n)||/llvmpipe/i.test(n),renderer:n,vendor:s}}catch(t){return{suspicious:!1,renderer:"error",vendor:"error"}}}checkInconsistencies(){const t=[];try{const e=navigator.userAgent,i=navigator.platform;/Windows/.test(e)&&/Mac/.test(i)&&t.push("ua_platform_mismatch_win_mac"),/Macintosh/.test(e)&&/Win/.test(i)&&t.push("ua_platform_mismatch_mac_win"),/Mobile|Android|iPhone/.test(e)&&0===navigator.maxTouchPoints&&t.push("mobile_ua_no_touch"),/Chrome/.test(e)&&navigator.plugins&&0===navigator.plugins.length&&t.push("chrome_no_plugins"),navigator.languages&&0!==navigator.languages.length||t.push("no_languages")}catch(e){}return t}checkHeadless(){const t=[];let e=0;try{if(/HeadlessChrome/.test(navigator.userAgent)&&(t.push("headless_ua"),e+=40),/Chrome/.test(navigator.userAgent)&&!window.chrome&&(t.push("chrome_ua_no_chrome_obj"),e+=15),window.screen&&800===window.screen.width&&600===window.screen.height&&(t.push("default_screen_size"),e+=10),"Notification"in window){"denied"===window.Notification.permission&&navigator.userAgent.includes("Chrome")&&(t.push("notification_denied_default"),e+=5)}const i=navigator.connection;i&&0===i.rtt&&(t.push("zero_rtt"),e+=10)}catch(i){}return{score:e,flags:t}}}class SessionAnalyzer{constructor(t){__publicField(this,"transmitter"),__publicField(this,"sessionStart",0),__publicField(this,"pageTransitions",[]),__publicField(this,"interactionTimestamps",[]),__publicField(this,"lastPageUrl",""),__publicField(this,"formStartTimes",new Map),__publicField(this,"reportInterval",null),this.transmitter=t}start(){if("undefined"==typeof window)return;this.sessionStart=Date.now(),this.lastPageUrl=window.location.href;["mousedown","keydown","touchstart","scroll"].forEach(t=>{document.addEventListener(t,()=>{this.interactionTimestamps.push(Date.now()),this.interactionTimestamps.length>500&&this.interactionTimestamps.shift()},{passive:!0,capture:!0})}),this.observeNavigation(),this.observeForms(),this.reportInterval=setInterval(()=>this.report(),15e3)}observeNavigation(){const t=history.pushState,e=history.replaceState,i=this;history.pushState=function(e,n,s){t.call(this,e,n,s),i.onPageTransition()},history.replaceState=function(t,n,s){e.call(this,t,n,s),i.onPageTransition()},window.addEventListener("popstate",()=>this.onPageTransition())}onPageTransition(){const t=Date.now(),e=window.location.href;e!==this.lastPageUrl&&(this.pageTransitions.push(t),this.lastPageUrl=e)}observeForms(){document.addEventListener("focus",t=>{const e=t.target;if("INPUT"===e.tagName||"TEXTAREA"===e.tagName||"SELECT"===e.tagName){const t=e.closest("form"),i=(null==t?void 0:t.id)||(null==t?void 0:t.action)||"anonymous_form";this.formStartTimes.has(i)||this.formStartTimes.set(i,Date.now())}},{capture:!0}),document.addEventListener("submit",t=>{const e=t.target,i=e.id||e.action||"anonymous_form",n=this.formStartTimes.get(i);if(n){const t=Date.now()-n;this.transmitter.send("session_metrics",{type:"form_completion",formId:i,duration:t,timestamp:Date.now()}),this.formStartTimes.delete(i)}},{capture:!0})}report(){const t=Date.now(),e=t-this.sessionStart;if(this.interactionTimestamps.length<10)return;const i=this.calculateIntervals(this.interactionTimestamps),n=this.analyzeTimingDistribution(i),s=this.analyzePageTransitions();this.transmitter.send("session_metrics",{type:"session_analysis",sessionDuration:e,totalInteractions:this.interactionTimestamps.length,pageTransitions:this.pageTransitions.length,timing:n,pages:s,timestamp:t})}calculateIntervals(t){const e=[];for(let i=1;i<t.length;i++)e.push(t[i]-t[i-1]);return e}analyzeTimingDistribution(t){if(t.length<5)return{samples:t.length};const e=t.reduce((t,e)=>t+e,0)/t.length,i=t.reduce((t,i)=>t+Math.pow(i-e,2),0)/t.length,n=Math.sqrt(i),s=e>0?n/e:0,r=this.shannonEntropy(t,50),a=this.autocorrelation(t);return{mean:Math.round(e),stdDev:Math.round(n),cv:parseFloat(s.toFixed(4)),entropy:parseFloat(r.toFixed(4)),autocorrelation:parseFloat(a.toFixed(4)),samples:t.length}}analyzePageTransitions(){if(this.pageTransitions.length<2)return{count:this.pageTransitions.length};const t=this.calculateIntervals(this.pageTransitions),e=t.reduce((t,e)=>t+e,0)/t.length,i=t.reduce((t,i)=>t+Math.pow(i-e,2),0)/t.length,n=e>0?Math.sqrt(i)/e:0;return{count:this.pageTransitions.length,avgInterval:Math.round(e),cv:parseFloat(n.toFixed(4))}}shannonEntropy(t,e){const i=new Map;for(const r of t){const t=Math.floor(r/e);i.set(t,(i.get(t)||0)+1)}const n=t.length;let s=0;for(const r of i.values()){const t=r/n;t>0&&(s-=t*Math.log2(t))}return s}autocorrelation(t){if(t.length<3)return 0;const e=t.reduce((t,e)=>t+e,0)/t.length;let i=0,n=0;for(let s=0;s<t.length-1;s++)i+=(t[s]-e)*(t[s+1]-e);for(let s=0;s<t.length;s++)n+=Math.pow(t[s]-e,2);return 0===n?0:i/n}}class TabNavigationAnalyzer{constructor(t){__publicField(this,"transmitter"),__publicField(this,"tabTimestamps",[]),__publicField(this,"shiftTabCount",0),__publicField(this,"tabCount",0),__publicField(this,"isShiftDown",!1),__publicField(this,"BURST_THRESHOLD_MS",80),__publicField(this,"reportInterval",null),__publicField(this,"REPORT_INTERVAL_MS",1e4),__publicField(this,"MIN_TABS_TO_REPORT",5),__publicField(this,"TAB_TRIGGER_COUNT",20),__publicField(this,"onKeyDown",t=>{if("Shift"!==t.key){if("Tab"===t.key){const t=Date.now();this.isShiftDown?this.shiftTabCount++:(this.tabCount++,this.tabTimestamps.push(t),this.tabTimestamps.length>100&&this.tabTimestamps.shift()),this.tabCount+this.shiftTabCount>=this.TAB_TRIGGER_COUNT&&this.report()}}else this.isShiftDown=!0}),__publicField(this,"onKeyUp",t=>{"Shift"===t.key&&(this.isShiftDown=!1)}),this.transmitter=t}start(){"undefined"!=typeof document&&(document.addEventListener("keydown",this.onKeyDown,{passive:!0,capture:!0}),document.addEventListener("keyup",this.onKeyUp,{passive:!0,capture:!0}),this.reportInterval=setInterval(()=>this.report(),this.REPORT_INTERVAL_MS))}stop(){"undefined"!=typeof document&&(document.removeEventListener("keydown",this.onKeyDown,{capture:!0}),document.removeEventListener("keyup",this.onKeyUp,{capture:!0}),this.reportInterval&&(clearInterval(this.reportInterval),this.reportInterval=null),this.report())}report(){const t=this.tabCount+this.shiftTabCount;if(t<this.MIN_TABS_TO_REPORT)return;const e=this.calculateIntervals(this.tabTimestamps);if(e.length<3)return void this.resetBuffers();const i=this.analyzeIntervals(e),n=this.analyzeBursts(e),s=t>0?this.shiftTabCount/t:0;this.transmitter.send("tab_navigation_metrics",{tabCount:this.tabCount,shiftTabCount:this.shiftTabCount,shiftTabRatio:parseFloat(s.toFixed(4)),intervals:i,bursts:n,timestamp:Date.now()}),this.resetBuffers()}resetBuffers(){this.tabTimestamps=[],this.tabCount=0,this.shiftTabCount=0}calculateIntervals(t){const e=[];for(let i=1;i<t.length;i++){const n=t[i]-t[i-1];n<5e3&&e.push(n)}return e}analyzeIntervals(t){if(0===t.length)return{avg:0,variance:0,cv:0,min:0,samples:0};const e=t.reduce((t,e)=>t+e,0)/t.length,i=t.reduce((t,i)=>t+Math.pow(i-e,2),0)/t.length,n=Math.sqrt(i),s=e>0?n/e:0,r=Math.min(...t);return{avg:parseFloat(e.toFixed(2)),variance:parseFloat(i.toFixed(2)),cv:parseFloat(s.toFixed(4)),min:r,samples:t.length}}analyzeBursts(t){let e=0,i=0,n=0,s=0,r=0;for(const a of t)a<this.BURST_THRESHOLD_MS?(i++,s+=a,r++):(i>=3&&(e++,n+=i),i=0);return i>=3&&(e++,n+=i),{count:e,avgLength:e>0?parseFloat((n/e).toFixed(1)):0,avgInterval:r>0?parseFloat((s/r).toFixed(2)):0}}}class CloudEnvironmentDetector{constructor(t){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2e3))}async detect(){try{const t=this.analyzeGPU(),e=this.analyzeHardware(),i=this.analyzeScreen(),n=await this.analyzeMedia(),s=this.benchmarkCanvas();let r=0;"virtual_gpu"!==t.category&&"software_render"!==t.category&&"cloud_gpu"!==t.category||(r+=2),e.cores<=2&&r++,null!==e.memory&&e.memory<=2&&r++,24===e.colorDepth&&r++,1===e.pixelRatio&&r++,i.noTaskbar&&r++,i.isVMResolution&&r++,0===n.cameras&&0===n.microphones&&r++,n.hasBluetooth||n.hasUSB||r++,s.canvasRenderTime>50&&r++;const{classification:a,confidence:o}=this.classify(t,e,r);this.transmitter.send("cloud_environment",{classification:a,confidence:o,signals:{gpu:{renderer:t.renderer,vendor:t.vendor,category:t.category},hardware:e,screen:i,media:n,performance:s},vmIndicatorCount:r,timestamp:Date.now()})}catch(t){}}analyzeGPU(){try{const t=document.createElement("canvas"),e=t.getContext("webgl")||t.getContext("experimental-webgl");if(!e)return{renderer:"unavailable",vendor:"unavailable",category:"unknown"};const i=e.getExtension("WEBGL_debug_renderer_info");if(!i)return{renderer:"no_debug_info",vendor:"no_debug_info",category:"unknown"};const n=e.getParameter(i.UNMASKED_RENDERER_WEBGL)||"",s=e.getParameter(i.UNMASKED_VENDOR_WEBGL)||"";return{renderer:n,vendor:s,category:this.categorizeGPU(n,s)}}catch(t){return{renderer:"error",vendor:"error",category:"unknown"}}}categorizeGPU(t,e){const i=t.toLowerCase(),n=e.toLowerCase();return/swiftshader|llvmpipe|mesa offscreen|softpipe/.test(i)?"software_render":/svga3d|svga|vmware/.test(i)||/virtualbox/.test(i)||/parallels/.test(i)||/qxl|virtio|red hat|spice/.test(i)||/hyper-v|microsoft basic render/i.test(i)||/citrix/.test(i)?"virtual_gpu":/amazon|elastic|aws/.test(i)||/amazon|elastic|aws/.test(n)||/google cloud|gce/.test(i)||/google cloud|gce/.test(n)||/azure/.test(i)||/azure/.test(n)?"cloud_gpu":"physical"}analyzeHardware(){return{cores:navigator.hardwareConcurrency||0,memory:navigator.deviceMemory??null,colorDepth:screen.colorDepth,pixelRatio:window.devicePixelRatio||1}}analyzeScreen(){const t=screen.width,e=screen.height,i=screen.availHeight,n=e===i&&e===window.innerHeight,s=[[800,600],[1024,768],[1280,1024],[1280,800],[1920,1080]].some(([i,n])=>t===i&&e===n&&!(1920===i&&1080===n));return{width:t,height:e,availHeight:i,noTaskbar:n,isVMResolution:s}}async analyzeMedia(){let t=-1,e=-1;try{if(navigator.mediaDevices&&navigator.mediaDevices.enumerateDevices){const i=await navigator.mediaDevices.enumerateDevices();t=i.filter(t=>"videoinput"===t.kind).length,e=i.filter(t=>"audioinput"===t.kind).length}}catch(r){}const i=!!navigator.bluetooth,n=!!navigator.usb;let s=null;try{if(navigator.getBattery){const t=await navigator.getBattery();s=!(t.charging&&1===t.level&&0===t.chargingTime)}}catch(r){}return{cameras:t,microphones:e,hasBluetooth:i,hasUSB:n,hasBattery:s}}benchmarkCanvas(){try{const t=document.createElement("canvas");t.width=200,t.height=200;const e=t.getContext("2d");if(!e)return{canvasRenderTime:-1};const i=performance.now();for(let s=0;s<500;s++)e.fillStyle=`rgb(${s%256},${3*s%256},${7*s%256})`,e.fillRect(13*s%200,7*s%200,10,10);e.getImageData(0,0,1,1);const n=performance.now()-i;return{canvasRenderTime:Math.round(100*n)/100}}catch(t){return{canvasRenderTime:-1}}}classify(t,e,i){return"virtual_gpu"===t.category?24===e.colorDepth?{classification:"rdp_likely",confidence:.85}:{classification:"vm_detected",confidence:.95}:"cloud_gpu"===t.category?{classification:"cloud_likely",confidence:.9}:"software_render"===t.category?{classification:"vm_detected",confidence:.9}:i>=5?{classification:"vm_likely",confidence:.8}:i>=3?{classification:"vm_likely",confidence:.6}:{classification:"physical",confidence:1-.1*i}}}class CrossContextDetector{constructor(t){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2500))}async detect(){var t,e;const i={};let n=0;const s={webdriver:!!navigator.webdriver,languages:(null==(t=navigator.languages)?void 0:t.join(","))||"",platform:navigator.platform||"",hardwareConcurrency:navigator.hardwareConcurrency||0,userAgent:navigator.userAgent||"",pluginsLength:(null==(e=navigator.plugins)?void 0:e.length)??0},r=this.checkIframe(s);r.score>0&&(i.iframe=r.mismatches,n+=r.score);try{const t=await this.checkWorker(s);t.score>0&&(i.worker=t.mismatches,n+=t.score)}catch(a){}n>0&&this.transmitter.send("cross_context_mismatch",{signals:i,score:n,timestamp:Date.now()})}checkIframe(t){var e,i;const n=[];let s=0;try{const r=document.createElement("iframe");r.style.display="none",r.sandbox="allow-same-origin",document.body.appendChild(r);const a=r.contentWindow;if(!a)return document.body.removeChild(r),{score:0,mismatches:[]};const o=a.navigator;o.webdriver!==navigator.webdriver&&(n.push("webdriver_mismatch"),s+=40),navigator.webdriver||!0!==o.webdriver||(n.push("webdriver_spoofed_in_main"),s+=30);((null==(e=o.languages)?void 0:e.join(","))||"")!==t.languages&&(n.push("languages_mismatch"),s+=15),o.platform!==t.platform&&(n.push("platform_mismatch"),s+=15);((null==(i=o.plugins)?void 0:i.length)??0)!==t.pluginsLength&&(n.push("plugins_mismatch"),s+=10),document.body.removeChild(r)}catch(r){}return{score:s,mismatches:n}}checkWorker(t){return new Promise(e=>{try{const i=new Blob(["\n self.onmessage = function() {\n var nav = self.navigator;\n self.postMessage({\n webdriver: !!nav.webdriver,\n languages: (nav.languages || []).join(','),\n platform: nav.platform || '',\n hardwareConcurrency: nav.hardwareConcurrency || 0,\n userAgent: nav.userAgent || ''\n });\n };\n "],{type:"application/javascript"}),n=URL.createObjectURL(i),s=new Worker(n),r=setTimeout(()=>{s.terminate(),URL.revokeObjectURL(n),e({score:0,mismatches:[]})},3e3);s.onmessage=i=>{clearTimeout(r),s.terminate(),URL.revokeObjectURL(n);const a=i.data,o=[];let c=0;a.webdriver!==t.webdriver&&(o.push("worker_webdriver_mismatch"),c+=35),a.languages!==t.languages&&(o.push("worker_languages_mismatch"),c+=15),a.platform!==t.platform&&(o.push("worker_platform_mismatch"),c+=15),a.hardwareConcurrency!==t.hardwareConcurrency&&(o.push("worker_concurrency_mismatch"),c+=10),a.userAgent!==t.userAgent&&(o.push("worker_ua_mismatch"),c+=20),e({score:c,mismatches:o})},s.onerror=()=>{clearTimeout(r),s.terminate(),URL.revokeObjectURL(n),e({score:0,mismatches:[]})},s.postMessage("check")}catch(i){e({score:0,mismatches:[]})}})}}class HeadlessProbeDetector{constructor(t){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2e3))}async detect(){const t={};let e=0;const i=await this.checkBrokenImage();i.suspicious&&(t.brokenImage=i,e+=25);const n=await this.checkClientHints();n.suspicious&&(t.clientHints=n,e+=20);const s=this.checkCDPMouseSignature();s.suspicious&&(t.cdpMouse=s,e+=30);const r=this.checkHairlineSupport();r.suspicious&&(t.hairline=r,e+=10);const a=this.checkExtraFrameworks();a.length>0&&(t.extraFrameworks=a,e+=20);(await this.checkWorkerCDP()).suspicious&&(t.workerCDP=!0,e+=35),e>0&&this.transmitter.send("headless_probe",{signals:t,score:e,timestamp:Date.now()})}checkBrokenImage(){return new Promise(t=>{try{const e=document.createElement("img");e.src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==___invalid";const i=setTimeout(()=>{t({suspicious:!1,width:-1,height:-1})},2e3);e.onerror=()=>{clearTimeout(i);const n=e.width,s=e.height;t({suspicious:0===n&&0===s,width:n,height:s})},e.onload=()=>{clearTimeout(i),t({suspicious:!1,width:e.width,height:e.height})},e.style.position="absolute",e.style.left="-9999px",document.body.appendChild(e),setTimeout(()=>{try{document.body.removeChild(e)}catch(t){}},100)}catch(e){t({suspicious:!1,width:-1,height:-1})}})}async checkClientHints(){const t=[];try{const e=navigator.userAgentData;if(!e)return{suspicious:!1,mismatches:[]};const i=navigator.userAgent,n=(e.brands||[]).map(t=>t.brand);/Chrome\/\d/.test(i)&&!n.some(t=>/Chromium|Google Chrome|Chrome/.test(t))&&t.push("ua_chrome_no_brand"),e.platform&&(/Windows/.test(i)&&"Windows"!==e.platform&&t.push("ua_windows_brand_mismatch"),/Macintosh/.test(i)&&"macOS"!==e.platform&&t.push("ua_mac_brand_mismatch"),/Linux/.test(i)&&!/Linux|Android|ChromeOS/.test(e.platform)&&t.push("ua_linux_brand_mismatch")),/Mobile/.test(i)&&!1===e.mobile&&t.push("ua_mobile_brand_mismatch")}catch(e){}return{suspicious:t.length>0,mismatches:t}}checkCDPMouseSignature(){let t=0,e=0,i=!1;try{const n=[],s=i=>{n.push(i),e++,0===i.movementX&&0===i.movementY&&t++};document.addEventListener("mousemove",s,{passive:!0}),setTimeout(()=>{document.removeEventListener("mousemove",s)},5e3),e>10&&t/e>.9&&(i=!0)}catch(n){}return{suspicious:i,zeroMovementCount:t,totalEvents:e}}checkHairlineSupport(){try{const t=document.createElement("div");t.style.border=".5px solid transparent",t.style.position="absolute",t.style.left="-9999px",document.body.appendChild(t);const e=t.offsetHeight;return document.body.removeChild(t),{suspicious:0===e,offsetHeight:e}}catch(t){return{suspicious:!1,offsetHeight:-1}}}checkExtraFrameworks(){const t=[];try{const i=window.external;if(i&&"function"==typeof i.toString)try{const e=i.toString();/Sequentum/i.test(e)&&t.push("sequentum")}catch(e){}const n=["__webdriver_script_fn","__webdriver_script_func","__webdriver_evaluate","__selenium_evaluate","__fxdriver_evaluate","__driver_evaluate","__webdriver_unwrapped","__selenium_unwrapped","__fxdriver_unwrapped","__driver_unwrapped","_Selenium_IDE_Recorder","_selenium","calledSelenium","_WEBDRIVER_ELEM_CACHE","ChromeDriverw","driver-hierarchical","__$webdriverAsyncExecutor","__lastWatirAlert","__lastWatirConfirm","__lastWatirPrompt","_WEBDRIVER_ELEM_CACHE","webdriver","_phantom","__nightmare","_selenium"];for(const e of n)(e in document||e in window)&&t.push(`global_${e}`);const s=Object.getOwnPropertyNames(navigator);for(const e of s)/webdriver|selenium|puppeteer|playwright|phantom/i.test(e)&&t.push(`nav_${e}`)}catch(e){}return t}checkWorkerCDP(){return new Promise(t=>{try{const e=new Blob(["\n self.onmessage = function() {\n var detected = false;\n try {\n var marker = {};\n Object.defineProperty(marker, 'stack', {\n get: function() { detected = true; return ''; }\n });\n console.debug(marker);\n } catch(e) {}\n self.postMessage({ cdp: detected });\n };\n "],{type:"application/javascript"}),i=URL.createObjectURL(e),n=new Worker(i),s=setTimeout(()=>{n.terminate(),URL.revokeObjectURL(i),t({suspicious:!1})},3e3);n.onmessage=e=>{clearTimeout(s),n.terminate(),URL.revokeObjectURL(i),t({suspicious:!0===e.data.cdp})},n.onerror=()=>{clearTimeout(s),n.terminate(),URL.revokeObjectURL(i),t({suspicious:!1})},n.postMessage("check")}catch(e){t({suspicious:!1})}})}}class ScriptInjectionDetector{constructor(t){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),__publicField(this,"injectedScriptCount",0),__publicField(this,"cspViolations",[]),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,this.startDOMObserver(),this.startCSPMonitor(),setTimeout(()=>this.detect(),1500))}detect(){const t={};let e=0;try{const i=this.checkNativeFunctionIntegrity();i.issues.length>0&&(t.nativeFunctionIntegrity=i.issues,e+=25)}catch(i){}try{const i=this.checkPropertyOverrides();i.issues.length>0&&(t.propertyOverrides=i.issues,e+=30)}catch(i){}this.injectedScriptCount>0&&(t.domScriptInjection={count:this.injectedScriptCount},e+=20),this.cspViolations.length>0&&(t.cspViolations=this.cspViolations.slice(0,10),e+=15);try{const i=this.checkGlobalPollution();i.length>0&&(t.globalPollution=i,e+=20)}catch(i){}try{const i=this.checkPrototypeIntegrity();i.length>0&&(t.prototypeIntegrity=i,e+=20)}catch(i){}e>0&&this.transmitter.send("script_injection",{signals:t,score:e,timestamp:Date.now()})}checkNativeFunctionIntegrity(){const t=[];try{const e=Object.getOwnPropertyDescriptor(navigator,"webdriver");if(e&&(!0===e.configurable&&t.push("webdriver_descriptor_configurable"),e.get)){const i=Function.prototype.toString.call(e.get);/\[native code\]/.test(i)||t.push("webdriver_non_native_getter")}}catch(e){}try{const e=["userAgent","platform","languages","hardwareConcurrency"];for(const i of e){const e=Object.getOwnPropertyDescriptor(Navigator.prototype,i);if(e&&e.get){const n=Function.prototype.toString.call(e.get);/\[native code\]/.test(n)||t.push(`navigator_${i}_non_native`)}}}catch(e){}try{const e=Function.prototype.toString.call(Function.prototype.toString);/\[native code\]/.test(e)||t.push("function_tostring_overridden")}catch(e){}return{issues:t}}checkPropertyOverrides(){const t=[];try{"[object Navigator]"!==Object.prototype.toString.call(navigator)&&t.push("navigator_proxy_or_spoofed")}catch(e){}try{if(navigator.plugins){"[object PluginArray]"!==Object.prototype.toString.call(navigator.plugins)&&t.push("plugins_spoofed"),Array.isArray(navigator.plugins)&&t.push("plugins_is_array")}}catch(e){}try{if(navigator.mimeTypes){"[object MimeTypeArray]"!==Object.prototype.toString.call(navigator.mimeTypes)&&t.push("mimetypes_spoofed")}}catch(e){}try{const e=Function.prototype.toString.call(Object.getOwnPropertyDescriptor);/\[native code\]/.test(e)||t.push("getOwnPropertyDescriptor_overridden")}catch(e){}return{issues:t}}startDOMObserver(){try{if("undefined"==typeof MutationObserver)return;const t=new MutationObserver(t=>{for(const e of t)for(let t=0;t<e.addedNodes.length;t++){const i=e.addedNodes[t];if("SCRIPT"===i.nodeName){i.src||this.injectedScriptCount++}}});t.observe(document.documentElement,{childList:!0,subtree:!0}),setTimeout(()=>{try{t.disconnect()}catch(e){}},1e4)}catch(t){}}startCSPMonitor(){try{const t=t=>{try{const e=`${t.violatedDirective}|${t.blockedURI||"inline"}`;this.cspViolations.push(e)}catch(e){}};document.addEventListener("securitypolicyviolation",t),setTimeout(()=>{try{document.removeEventListener("securitypolicyviolation",t)}catch(e){}},1e4)}catch(t){}}checkGlobalPollution(){const t=[],e=window,i=document,n=[["__webdriver_evaluate",()=>!!i.__webdriver_evaluate],["__selenium_evaluate",()=>!!i.__selenium_evaluate],["__webdriver_script_function",()=>!!i.__webdriver_script_function],["__webdriver_script_func",()=>!!i.__webdriver_script_func],["__webdriver_script_fn",()=>!!i.__webdriver_script_fn],["_Selenium_IDE_Recorder",()=>!!e._Selenium_IDE_Recorder],["__lastWatirAlert",()=>!!e.__lastWatirAlert],["__lastWatirConfirm",()=>!!e.__lastWatirConfirm],["__lastWatirPrompt",()=>!!e.__lastWatirPrompt],["_phantom",()=>!!e._phantom],["callPhantom",()=>!!e.callPhantom],["__nightmare",()=>!!e.__nightmare],["Buffer",()=>"function"==typeof e.Buffer&&"function"==typeof e.Buffer.alloc],["process",()=>!!e.process&&!!e.process.versions],["global_redefined",()=>!!e.global&&e.global!==e&&"object"==typeof e.global],["window_emit",()=>"function"==typeof e.emit]];for(const[r,a]of n)try{a()&&t.push(r)}catch(s){}try{const e=Object.keys(document);for(const i of e)/^cdc_|^__cdc_/.test(i)&&t.push(`cdc:${i}`)}catch(s){}try{const e=Object.keys(window);for(const i of e)/^cdc_|^__cdc_/.test(i)&&t.push(`cdc_window:${i}`)}catch(s){}return t}checkPrototypeIntegrity(){const t=[];try{const e=HTMLElement.prototype,i=Object.getOwnPropertyNames(e);for(const n of i)/^__selenium|^__webdriver|^__playwright|^__puppeteer/.test(n)&&t.push(`htmlelement_proto_${n}`)}catch(e){}try{const e=document.createElement("div");e instanceof HTMLDivElement||t.push("createElement_not_genuine");"[object HTMLDivElement]"!==Object.prototype.toString.call(e)&&t.push("createElement_wrong_tostring")}catch(e){}try{const e=new Event("test");e instanceof Event||t.push("event_not_instance");"[object Event]"!==Object.prototype.toString.call(e)&&t.push("event_wrong_prototype")}catch(e){}try{const e=Function.prototype.toString.call(document.createElement);/\[native code\]/.test(e)||t.push("createElement_overridden")}catch(e){}return t}}class WorkerIntegrityDetector{constructor(t){__publicField(this,"transmitter"),__publicField(this,"hasRun",!1),this.transmitter=t}start(){this.hasRun||"undefined"==typeof window||(this.hasRun=!0,setTimeout(()=>this.detect(),2e3))}async detect(){try{if("undefined"==typeof Worker||"undefined"==typeof Blob)return;const e={webdriver:!!navigator.webdriver,userAgent:navigator.userAgent||"",platform:navigator.platform||"",languages:JSON.stringify(navigator.languages||[]),hardwareConcurrency:navigator.hardwareConcurrency||0,dateNow:Date.now(),perfNow:performance.now(),toStringNative:!1};try{e.toStringNative=/\[native code\]/.test(Function.prototype.toString.call(Array.prototype.push))}catch(t){e.toStringNative=!1}const i=await this.runWorker(e);if(!i)return;const n={};let s=0;const r=[];e.webdriver||!0!==i.webdriver?i.webdriver!==e.webdriver&&(r.push("webdriver_mismatch"),s+=30):(r.push("webdriver_spoofed"),s+=40),i.userAgent!==e.userAgent&&(r.push("userAgent_mismatch"),s+=30),i.platform!==e.platform&&(r.push("platform_mismatch"),s+=30),i.languages!==e.languages&&(r.push("languages_mismatch"),s+=30),i.hardwareConcurrency!==e.hardwareConcurrency&&(r.push("hardwareConcurrency_mismatch"),s+=30),r.length>0&&(n.navigatorMismatch=r);const a=i.benchmarkMs;"number"==typeof a&&(a<1||a>500)&&(n.benchmarkAnomaly={benchmarkMs:a,reason:a<1?"abnormally_fast":"abnormally_slow"},s+=20),!1===i.cryptoEntropy&&(n.cryptoMock={entropy:!1,values:i.cryptoValues},s+=15);const o=Math.abs(i.dateNow-e.dateNow);if(o>1e3&&(n.timeManipulation={mainDateNow:e.dateNow,workerDateNow:i.dateNow,deltaMs:o},s+=15),!i.toStringNative||!e.toStringNative){const t=[];i.toStringNative||t.push("worker_tampered"),e.toStringNative||t.push("main_tampered"),n.toStringTampering=t,s+=20}s>0&&this.transmitter.send("worker_integrity",{signals:n,score:s,timestamp:Date.now()})}catch(t){}}runWorker(t){return new Promise(e=>{try{const i=new Blob(["\n self.onmessage = function(e) {\n var results = {};\n\n // 1. Navigator check\n try {\n results.webdriver = !!navigator.webdriver;\n results.userAgent = navigator.userAgent || '';\n results.platform = navigator.platform || '';\n results.languages = JSON.stringify(navigator.languages || []);\n results.hardwareConcurrency = navigator.hardwareConcurrency || 0;\n } catch(ex) {\n results.webdriver = false;\n results.userAgent = '';\n results.platform = '';\n results.languages = '[]';\n results.hardwareConcurrency = 0;\n }\n\n // 2. Performance benchmark\n try {\n var start = performance.now();\n var sum = 0;\n for (var i = 0; i < 1000000; i++) sum += i;\n results.benchmarkMs = performance.now() - start;\n } catch(ex) {\n results.benchmarkMs = -1;\n }\n\n // 3. Crypto check\n try {\n var arr = new Uint32Array(4);\n crypto.getRandomValues(arr);\n results.cryptoEntropy = arr[0] !== arr[1] && arr[1] !== arr[2] && arr[0] !== 0;\n results.cryptoValues = Array.from(arr);\n } catch(ex) {\n results.cryptoEntropy = false;\n results.cryptoValues = [];\n }\n\n // 4. Time check\n results.dateNow = Date.now();\n results.perfNow = performance.now();\n\n // 5. toString integrity\n try {\n results.toStringNative = /\\[native code\\]/.test(\n Function.prototype.toString.call(Array.prototype.push)\n );\n } catch(ex) {\n results.toStringNative = false;\n }\n\n self.postMessage(results);\n };\n "],{type:"application/javascript"}),n=URL.createObjectURL(i),s=new Worker(n),r=setTimeout(()=>{s.terminate(),URL.revokeObjectURL(n),e(null)},5e3);s.onmessage=t=>{clearTimeout(r),s.terminate(),URL.revokeObjectURL(n),e(t.data)},s.onerror=()=>{clearTimeout(r),s.terminate(),URL.revokeObjectURL(n),e(null)},s.postMessage({mainValues:t})}catch(i){e(null)}})}}class CrawlProtect{constructor(t){__publicField(this,"config"),__publicField(this,"renewTimer",null),__publicField(this,"verified",!1),this.config=t}async start(){const t=this.getToken();if(t&&!this.isExpired(t))return this.verified=!0,this.scheduleRenewal(t),this.revealContent(),this.config.debug,!0;this.hideContent();const e=await this.solveChallenge();return e?(this.verified=!0,this.revealContent()):this.config.insertHoneypot&&this.insertHoneypotData(),e}isVerified(){return this.verified}stop(){this.renewTimer&&(clearTimeout(this.renewTimer),this.renewTimer=null)}async solveChallenge(){try{const t=await fetch(`${this.config.apiBase}/crawl-protect/challenge`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":this.config.clientId}});if(!t.ok)return!1;const{id:e,challenges:i}=await t.json(),n=[];for(const c of i)if("math"===c.type){const t="add"===c.op?c.a+c.b:c.a*c.b;n.push(String(t))}else if("crypto"===c.type){const t=await this.sha256(c.nonce);n.push(t.slice(0,8))}const s=n.join(":"),r=await this.getFingerprint(),a=await fetch(`${this.config.apiBase}/crawl-protect/verify`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":this.config.clientId},body:JSON.stringify({id:e,solution:s,fingerprint:r}),credentials:"include"});if(!a.ok)return!1;const o=await a.json();return!(!o.success||!o.token)&&(this.setToken(o.token),this.scheduleRenewal(o.token),this.config.debug,!0)}catch(t){return this.config.debug,!1}}hideContent(){var t;if(null==(t=this.config.protectSelectors)?void 0:t.length)for(const e of this.config.protectSelectors){document.querySelectorAll(e).forEach(t=>{t.dataset.aieOrigDisplay=t.style.display,t.style.display="none"})}}revealContent(){var t;if(null==(t=this.config.protectSelectors)?void 0:t.length)for(const e of this.config.protectSelectors){document.querySelectorAll(e).forEach(t=>{t.style.display=t.dataset.aieOrigDisplay||"",delete t.dataset.aieOrigDisplay})}}insertHoneypotData(){const t=document.createElement("div");t.style.cssText="position:absolute;left:-9999px;top:-9999px;opacity:0;pointer-events:none;",t.setAttribute("aria-hidden","true"),t.innerHTML='\n <span class="price" data-aie-honeypot="1">₩999,999,999</span>\n <span class="stock" data-aie-honeypot="1">재고: 0개</span>\n <a href="mailto:honeypot@aientrophy.com" data-aie-honeypot="1">contact</a>\n ',document.body.appendChild(t)}getToken(){const t=document.cookie.match(new RegExp("(?:^|; )__aie_token=([^;]*)"));return t?decodeURIComponent(t[1]):null}setToken(t){const e=new Date(Date.now()+18e5).toUTCString();document.cookie=`__aie_token=${encodeURIComponent(t)};path=/;expires=${e};SameSite=None;Secure`}isExpired(t){try{const[e]=t.split("."),i=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/")));return Date.now()>i.exp}catch{return!0}}scheduleRenewal(t){try{const[e]=t.split("."),i=JSON.parse(atob(e.replace(/-/g,"+").replace(/_/g,"/"))),n=i.exp-3e5-Date.now();n>0&&(this.renewTimer=setTimeout(()=>this.solveChallenge(),n))}catch{}}async sha256(t){const e=new TextEncoder,i=await crypto.subtle.digest("SHA-256",e.encode(t));return Array.from(new Uint8Array(i)).map(t=>t.toString(16).padStart(2,"0")).join("")}async getFingerprint(){const t=[navigator.userAgent,navigator.language,screen.width+"x"+screen.height,Intl.DateTimeFormat().resolvedOptions().timeZone];return this.sha256(t.join("|"))}}const securitySDK=new class{constructor(){__publicField(this,"transmitter"),__publicField(this,"behaviorCollector"),__publicField(this,"rapidClickDetector"),__publicField(this,"honeypot"),__publicField(this,"mouseTracker"),__publicField(this,"canvasFingerprinter"),__publicField(this,"inputTracker"),__publicField(this,"challengeHandler"),__publicField(this,"invisibleInteraction"),__publicField(this,"automationDetector"),__publicField(this,"sessionAnalyzer"),__publicField(this,"tabNavigationAnalyzer"),__publicField(this,"cloudEnvironmentDetector"),__publicField(this,"crossContextDetector"),__publicField(this,"headlessProbeDetector"),__publicField(this,"scriptInjectionDetector"),__publicField(this,"workerIntegrityDetector"),__publicField(this,"crawlProtect",null),__publicField(this,"initialized",!1),__publicField(this,"wasmService"),__publicField(this,"callbackManager"),this.transmitter=new Transmitter,this.wasmService=new WasmService,this.callbackManager=new CallbackManager,this.transmitter.setCallbackManager(this.callbackManager),this.behaviorCollector=new BehaviorCollector(this.transmitter),this.rapidClickDetector=new RapidClickDetector(this.transmitter),this.honeypot=new Honeypot(this.transmitter),this.mouseTracker=new MouseTracker(this.transmitter,this.wasmService),this.canvasFingerprinter=new CanvasFingerprinter(this.transmitter,this.wasmService),this.inputTracker=new InputTracker(this.transmitter),this.invisibleInteraction=new InvisibleInteraction(this.transmitter),this.automationDetector=new AutomationDetector(this.transmitter),this.sessionAnalyzer=new SessionAnalyzer(this.transmitter),this.tabNavigationAnalyzer=new TabNavigationAnalyzer(this.transmitter),this.cloudEnvironmentDetector=new CloudEnvironmentDetector(this.transmitter),this.crossContextDetector=new CrossContextDetector(this.transmitter),this.headlessProbeDetector=new HeadlessProbeDetector(this.transmitter),this.scriptInjectionDetector=new ScriptInjectionDetector(this.transmitter),this.workerIntegrityDetector=new WorkerIntegrityDetector(this.transmitter)}async init(t){var e,i;if(this.initialized)return;t.callbacks&&this.callbackManager.setConfigCallbacks(t.callbacks);const n=t.endpoint.replace(/\/events$/,"");try{await this.wasmService.load(n),this.startDetectors(),this.transmitter.setConfig(t),this.challengeHandler=new ChallengeHandler(n),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-JDCTbZps.cjs")).then(({AntiDebug:t})=>{t.start(),t.setOnDevtoolsMaxed(()=>{this.transmitter.send("devtools_force_close",{reason:"devtools_threshold_exceeded",detectionCount:3,maxThreat:!0})}),Promise.resolve().then(()=>require("../console-C5Os11uw.cjs")).then(({ConsoleDetector:t})=>{new t(()=>{this.transmitter.send("devtools_open",{detected:!0})}).start()})}),t.crawlProtect&&(this.crawlProtect=new CrawlProtect({apiBase:n,clientId:t.clientKey,protectSelectors:t.crawlProtect.protectSelectors,insertHoneypot:t.crawlProtect.insertHoneypot,debug:t.debug}),this.crawlProtect.start().catch(e=>{t.debug})),this.initialized=!0,t.debug,this.callbackManager.emit("ready")}catch(s){this.callbackManager.emit("error",{code:"INIT_ERROR",message:"SecuritySDK initialization failed",details:null==s?void 0:s.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.behaviorCollector.start(),this.honeypot.start(),this.mouseTracker.start(),this.canvasFingerprinter.start(),this.inputTracker.start(),this.invisibleInteraction.start(),this.automationDetector.start(),this.sessionAnalyzer.start(),this.tabNavigationAnalyzer.start(),this.cloudEnvironmentDetector.start(),this.crossContextDetector.start(),this.headlessProbeDetector.start(),this.scriptInjectionDetector.start(),this.workerIntegrityDetector.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 n=t.replace(/\/events$/,""),s=await fetch(`${n}/sdk/payload?clientKey=${encodeURIComponent(this.config.clientKey)}`);if(s.ok){e=(await s.json()).config||{}}if(e.nonceValidation)try{const t=await fetch(`${n}/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,crawlProtect:this.config.crawlProtect,serverConfig:e})}on(t,e){securitySDK.on(t,e)}off(t,e){securitySDK.off(t,e)}once(t,e){securitySDK.once(t,e)}};
@@ -3108,7 +3108,7 @@ class SecuritySDK {
3108
3108
  maxThreat: true
3109
3109
  });
3110
3110
  });
3111
- import("../console-En5NiLnf.js").then(({ ConsoleDetector }) => {
3111
+ import("../console-CIQML1V3.js").then(({ ConsoleDetector }) => {
3112
3112
  new ConsoleDetector(() => {
3113
3113
  this.transmitter.send("devtools_open", { detected: true });
3114
3114
  }).start();
@@ -1,8 +1,8 @@
1
1
  {
2
- "generated": "2026-03-20T07:17:00.562Z",
2
+ "generated": "2026-04-02T01:03:45.796Z",
3
3
  "algorithm": "sha384",
4
4
  "hashes": {
5
- "core.js": "sha384-xJbvsg7i3+S9/U65mr/X1xSf4pXP+gDpxLIc6FhvSJyXi8yoahzQAn9VE8s49HaZ",
5
+ "core.js": "sha384-EGS3F3gsBIHx0nWyUc+i54g1eThhHPmxHG9IqBsQX3u1z81N+ipEmSzxi+qasNmD",
6
6
  "core.wasm": "sha384-fPJjZg5frGy3uptl1c6t4ekPOoQRQPquQVQEbrMf09T7mCur5iJVX4gGqkRfu93q",
7
7
  "loader.js": "sha384-0v1eaWmQUDG7Xzh8ujnAFroO2azUb0n547CCqAL1opB0WUltJC8WMyV8e1XoKf2R"
8
8
  }
@@ -14,6 +14,7 @@ export declare class ConsoleDetector {
14
14
  private intervals;
15
15
  private detected;
16
16
  constructor(onDetect: () => void);
17
+ private isMobile;
17
18
  start(): void;
18
19
  stop(): void;
19
20
  private triggerDetect;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aientrophy/sdk",
3
- "version": "0.3.4",
3
+ "version": "0.3.5",
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",
@@ -1 +0,0 @@
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 antiDebug=require("./anti-debug-JDCTbZps.cjs");exports.ConsoleDetector=class{constructor(t){__publicField(this,"onDetect"),__publicField(this,"intervals",[]),__publicField(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(),antiDebug.AntiDebug.reportDevtoolsDetection(),setTimeout(()=>{this.detected=!1},2e3))}startGetterTrap(){const t=antiDebug.AntiDebug.getOriginalConsole(),e=t.log,i=t.clear;if(!e)return;const r=document.createElement("div");Object.defineProperty(r,"id",{get:()=>(this.triggerDetect(),"")});const n=/./;n.toString=()=>(this.triggerDetect(),"");const o=setInterval(()=>{try{e(r),e(n),i&&i()}catch(t){}},1500);this.intervals.push(o)}startSizeDetection(){if(navigator.maxTouchPoints>0||/Mobile|Android|iPhone|iPad/i.test(navigator.userAgent))return;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)}};