@aientrophy/sdk 0.3.2 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/anti-debug-BWiEU1_V.cjs +1 -0
- package/dist/{anti-debug-CZyDVzB-.js → anti-debug-Cf0ePnTv.js} +63 -20
- package/dist/console-DYd8RaPC.cjs +1 -0
- package/dist/{console-ZtBun_Tc.js → console-n38-3CrG.js} +2 -1
- package/dist/core.js +1 -1
- package/dist/npm/index.cjs.js +1 -1
- package/dist/npm/index.es.js +528 -3
- package/dist/sri-hashes.json +2 -2
- package/dist/types/core/index.d.ts +2 -0
- package/dist/types/detectors/ScriptInjectionDetector.d.ts +56 -0
- package/dist/types/detectors/WorkerIntegrityDetector.d.ts +26 -0
- package/dist/types/protection/anti-debug.d.ts +7 -6
- package/package.json +1 -1
- package/dist/anti-debug-u8v02mI_.cjs +0 -1
- package/dist/console-C5WWu7ZB.cjs +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var __defProp=Object.defineProperty,__publicField=(e,t,o)=>((e,t,o)=>t in e?__defProp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o)(e,"symbol"!=typeof t?t+"":t,o);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _originalConsole={};let _devtoolsDetectionCount=0;let _devtoolsHandled=!1,_onDevtoolsMaxed=null;class AntiDebug{static start(){this.saveConsole(),this.disableConsole(),this.preventDevTools(),this.blockDevToolsKeys()}static stop(){this.intervalId&&clearInterval(this.intervalId)}static setOnDevtoolsMaxed(e){_onDevtoolsMaxed=e}static reportDevtoolsDetection(){_devtoolsHandled||(_devtoolsDetectionCount++,_devtoolsDetectionCount>=3&&(_devtoolsHandled=!0,this.handleDevtoolsMaxed()))}static getOriginalConsole(){return _originalConsole}static handleDevtoolsMaxed(){if(_onDevtoolsMaxed)try{_onDevtoolsMaxed()}catch(e){}try{alert("개발자 도구가 탐지되었습니다.\n보안 정책에 의해 브라우저가 종료됩니다.")}catch(e){}try{document.documentElement.innerHTML=""}catch(e){}try{window.open("","_self"),window.close()}catch(e){}setTimeout(()=>{try{window.location.href="about:blank"}catch(e){}},100)}static saveConsole(){const e=["log","debug","info","warn","error","table","trace","dir","clear"];try{const t=window.console;if(!t)return;for(const o of e)"function"==typeof t[o]&&(_originalConsole[o]=t[o].bind(t))}catch(t){}}static preventDevTools(){this.intervalId=setInterval(()=>{this.debuggerCheck()},this.checkInterval)}static debuggerCheck(){!function(){try{(function(){}).constructor("debugger")()}catch(e){}}()}static blockDevToolsKeys(){document.addEventListener("keydown",e=>{"F12"!==e.key?e.ctrlKey&&e.shiftKey&&["I","i","J","j","C","c"].includes(e.key)?e.preventDefault():!e.ctrlKey||"u"!==e.key&&"U"!==e.key||e.preventDefault():e.preventDefault()},!0),document.addEventListener("contextmenu",e=>{e.preventDefault()},!0)}static disableConsole(){const e=()=>{},t=["log","debug","info","warn","error","table","trace","dir"];try{const o=window.console;if(!o)return;for(const n of t)o[n]&&(o[n]=e)}catch(o){}}}__publicField(AntiDebug,"checkInterval",1e3),__publicField(AntiDebug,"intervalId"),exports.AntiDebug=AntiDebug;
|
|
@@ -2,21 +2,66 @@ var __defProp = Object.defineProperty;
|
|
|
2
2
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
3
3
|
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
4
4
|
const _originalConsole = {};
|
|
5
|
+
let _devtoolsDetectionCount = 0;
|
|
6
|
+
const DEVTOOLS_ALERT_THRESHOLD = 3;
|
|
7
|
+
let _devtoolsHandled = false;
|
|
8
|
+
let _onDevtoolsMaxed = null;
|
|
5
9
|
class AntiDebug {
|
|
6
10
|
static start() {
|
|
7
11
|
this.saveConsole();
|
|
8
12
|
this.disableConsole();
|
|
9
13
|
this.preventDevTools();
|
|
14
|
+
this.blockDevToolsKeys();
|
|
10
15
|
}
|
|
11
16
|
static stop() {
|
|
12
17
|
if (this.intervalId) {
|
|
13
18
|
clearInterval(this.intervalId);
|
|
14
19
|
}
|
|
15
20
|
}
|
|
21
|
+
/** Set callback for when DevTools detection exceeds threshold (called by SDK core). */
|
|
22
|
+
static setOnDevtoolsMaxed(callback) {
|
|
23
|
+
_onDevtoolsMaxed = callback;
|
|
24
|
+
}
|
|
25
|
+
/** Called by ConsoleDetector or size detection when DevTools is detected. */
|
|
26
|
+
static reportDevtoolsDetection() {
|
|
27
|
+
if (_devtoolsHandled) return;
|
|
28
|
+
_devtoolsDetectionCount++;
|
|
29
|
+
if (_devtoolsDetectionCount >= DEVTOOLS_ALERT_THRESHOLD) {
|
|
30
|
+
_devtoolsHandled = true;
|
|
31
|
+
this.handleDevtoolsMaxed();
|
|
32
|
+
}
|
|
33
|
+
}
|
|
16
34
|
/** Returns saved original console methods (bound to console). */
|
|
17
35
|
static getOriginalConsole() {
|
|
18
36
|
return _originalConsole;
|
|
19
37
|
}
|
|
38
|
+
static handleDevtoolsMaxed() {
|
|
39
|
+
if (_onDevtoolsMaxed) {
|
|
40
|
+
try {
|
|
41
|
+
_onDevtoolsMaxed();
|
|
42
|
+
} catch (_) {
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
try {
|
|
46
|
+
alert("개발자 도구가 탐지되었습니다.\n보안 정책에 의해 브라우저가 종료됩니다.");
|
|
47
|
+
} catch (_) {
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
document.documentElement.innerHTML = "";
|
|
51
|
+
} catch (_) {
|
|
52
|
+
}
|
|
53
|
+
try {
|
|
54
|
+
window.open("", "_self");
|
|
55
|
+
window.close();
|
|
56
|
+
} catch (_) {
|
|
57
|
+
}
|
|
58
|
+
setTimeout(() => {
|
|
59
|
+
try {
|
|
60
|
+
window.location.href = "about:blank";
|
|
61
|
+
} catch (_) {
|
|
62
|
+
}
|
|
63
|
+
}, 100);
|
|
64
|
+
}
|
|
20
65
|
static saveConsole() {
|
|
21
66
|
const methods = ["log", "debug", "info", "warn", "error", "table", "trace", "dir", "clear"];
|
|
22
67
|
try {
|
|
@@ -33,7 +78,6 @@ class AntiDebug {
|
|
|
33
78
|
static preventDevTools() {
|
|
34
79
|
this.intervalId = setInterval(() => {
|
|
35
80
|
this.debuggerCheck();
|
|
36
|
-
this.devtoolsCloseCheck();
|
|
37
81
|
}, this.checkInterval);
|
|
38
82
|
}
|
|
39
83
|
static debuggerCheck() {
|
|
@@ -51,26 +95,25 @@ class AntiDebug {
|
|
|
51
95
|
})();
|
|
52
96
|
})();
|
|
53
97
|
}
|
|
54
|
-
/**
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
if (navigator.maxTouchPoints > 0 || /Mobile|Android|iPhone|iPad/i.test(navigator.userAgent)) {
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
const threshold = 100;
|
|
64
|
-
const start = performance.now();
|
|
65
|
-
(function() {
|
|
66
|
-
}).constructor("debugger")();
|
|
67
|
-
const elapsed = performance.now() - start;
|
|
68
|
-
if (elapsed > threshold) {
|
|
69
|
-
try {
|
|
70
|
-
document.body.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100vh;font-family:sans-serif;background:#111;color:#fff"><div style="text-align:center"><h2 style="margin-bottom:12px">⚠ 보안 경고</h2><p style="color:#999">개발자 도구가 감지되었습니다.<br>페이지를 계속 이용하려면 개발자 도구를 닫아주세요.</p></div></div>';
|
|
71
|
-
} catch (_) {
|
|
98
|
+
/** Block F12, Ctrl+Shift+I/J/C, Ctrl+U and right-click */
|
|
99
|
+
static blockDevToolsKeys() {
|
|
100
|
+
document.addEventListener("keydown", (e) => {
|
|
101
|
+
if (e.key === "F12") {
|
|
102
|
+
e.preventDefault();
|
|
103
|
+
return;
|
|
72
104
|
}
|
|
73
|
-
|
|
105
|
+
if (e.ctrlKey && e.shiftKey && ["I", "i", "J", "j", "C", "c"].includes(e.key)) {
|
|
106
|
+
e.preventDefault();
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
if (e.ctrlKey && (e.key === "u" || e.key === "U")) {
|
|
110
|
+
e.preventDefault();
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
}, true);
|
|
114
|
+
document.addEventListener("contextmenu", (e) => {
|
|
115
|
+
e.preventDefault();
|
|
116
|
+
}, true);
|
|
74
117
|
}
|
|
75
118
|
static disableConsole() {
|
|
76
119
|
const noop = () => {
|
|
@@ -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-BWiEU1_V.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},5e3))}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)}};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
var __defProp = Object.defineProperty;
|
|
2
2
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
3
3
|
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
4
|
-
import { AntiDebug } from "./anti-debug-
|
|
4
|
+
import { AntiDebug } from "./anti-debug-Cf0ePnTv.js";
|
|
5
5
|
class ConsoleDetector {
|
|
6
6
|
constructor(onDetect) {
|
|
7
7
|
__publicField(this, "onDetect");
|
|
@@ -23,6 +23,7 @@ class ConsoleDetector {
|
|
|
23
23
|
if (this.detected) return;
|
|
24
24
|
this.detected = true;
|
|
25
25
|
this.onDetect();
|
|
26
|
+
AntiDebug.reportDevtoolsDetection();
|
|
26
27
|
setTimeout(() => {
|
|
27
28
|
this.detected = false;
|
|
28
29
|
}, 5e3);
|
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,i=(t,i,s)=>((t,i,s)=>i in t?e(t,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):t[i]=s)(t,"symbol"!=typeof i?i+"":i,s);const s="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqbBCvDqyUtfhgI/Lo5pDtn1phwA6qczAyp8N1ZgQ68OTxgbJUGiXV6N67p15bBdME1R4va51P2Czq2IbRby/N+GHTciTaXvmusV8IjnIOGtKlGxWCuKIPrCS+rGjGA2j1irxBbNpqItltFxjhxBGOzsyQAF6LNIz5IKA7sC6cSH8zUyLuFrV96udc801Zc4nCJG64ZljNbDvlVbJJZ6ex5OLLS6AnrVAXpjEDR/MI/I8JvAPe/psHj6EpXgvKrBYMBOH3jzQRzMFoR79jXyGNgPjdy0A+f6RVuEG8H5sUXKeyy+cFvaT+pm6h+t6RPED11tCOwQxYZ2pExhhPxDGeQIDAQAB";class n{static async init(){if(!this.sessionKey)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$/,""),s=await fetch(`${i}/key-exchange`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({clientPublicKey:this.ecdhPublicKeyBase64})});if(!s.ok)throw new Error("Key exchange failed");const{serverPublicKey:n,salt:a}=await s.json(),r=this.base64ToArrayBuffer(n),o=await window.crypto.subtle.importKey("raw",r,{name:"ECDH",namedCurve:"P-256"},!1,[]),c=await window.crypto.subtle.deriveBits({name:"ECDH",public:o},t.privateKey,256),l=await window.crypto.subtle.importKey("raw",c,"HKDF",!1,["deriveKey"]),h=this.base64ToArrayBuffer(a);this.sessionKey=await window.crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:h,info:(new TextEncoder).encode("aientrophy-session-enc")},l,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),this.protocolVersion=2}static async initRSA(){this.sessionKey=await window.crypto.subtle.generateKey({name:"AES-GCM",length:256},!0,["encrypt","decrypt"]);const t=await this.importRSAPublicKey(s),e=await window.crypto.subtle.exportKey("raw",this.sessionKey),i=await window.crypto.subtle.encrypt({name:"RSA-OAEP"},t,e);this.encryptedSessionKey=this.arrayBufferToBase64(i),this.protocolVersion=1}static async encrypt(t){this.sessionKey||await this.init();const e=JSON.stringify(t),i=(new TextEncoder).encode(e),s=window.crypto.getRandomValues(new Uint8Array(12)),n=await window.crypto.subtle.encrypt({name:"AES-GCM",iv:s},this.sessionKey,i),a=new Uint8Array(n),r=a.slice(0,a.length-16),o=a.slice(a.length-16),c={ek:2===this.protocolVersion?this.ecdhPublicKeyBase64:this.encryptedSessionKey,d:this.arrayBufferToBase64(r.buffer),iv:this.arrayBufferToBase64(s.buffer),tag:this.arrayBufferToBase64(o.buffer)};return 2===this.protocolVersion&&(c.v=2),c}static async decrypt(t){if(!this.sessionKey)throw new Error("Session key not initialized");const e=this.base64ToArrayBuffer(t.d),i=this.base64ToArrayBuffer(t.iv),s=this.base64ToArrayBuffer(t.tag),n=new Uint8Array(e.byteLength+s.byteLength);n.set(new Uint8Array(e),0),n.set(new Uint8Array(s),e.byteLength);const a=await window.crypto.subtle.decrypt({name:"AES-GCM",iv:i},this.sessionKey,n),r=(new TextDecoder).decode(a);return JSON.parse(r)}static 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 s=0,n=t.length;s<n;s++)i[s]=t.charCodeAt(s);return e}static arrayBufferToBase64(t){let e="";const i=new Uint8Array(t),s=i.byteLength;for(let n=0;n<s;n++)e+=String.fromCharCode(i[n]);return window.btoa(e)}static base64ToArrayBuffer(t){const e=window.atob(t),i=e.length,s=new Uint8Array(i);for(let n=0;n<i;n++)s[n]=e.charCodeAt(n);return s.buffer}}i(n,"sessionKey",null),i(n,"ecdhPublicKeyBase64",null),i(n,"encryptedSessionKey",null),i(n,"protocolVersion",2);const a=new Set(["rapid_click","honeypot_triggered","devtools_open","invisible_interaction","integrity_violation","dom_mutation","behavior_metrics","behavior_analysis","input_metrics","keystroke_dynamics","environmental_integrity","init_signals","automation_detected","cross_context_mismatch","headless_probe"]);class r{constructor(){i(this,"handlers",new Map),i(this,"configCallbacks",{})}setConfigCallbacks(t){this.configCallbacks=t}on(t,e){this.addHandler(t,e,!1)}once(t,e){this.addHandler(t,e,!0)}off(t,e){const i=this.handlers.get(t);if(!i)return;const s=i.filter(t=>t.handler!==e);0===s.length?this.handlers.delete(t):this.handlers.set(t,s)}emit(t,...e){this.callHandlers(t,e);const i=t.indexOf(":");if(-1!==i){const s=t.substring(0,i);this.callHandlers(s,e)}this.callConfigCallback(t,e)}emitChallenge(t){return new Promise(e=>{let i=!1;const s=t=>{i||(i=!0,e(t))},n=this.handlers.has("challenge")&&this.handlers.get("challenge").length>0,a=!!this.configCallbacks.onChallenge;n||a?(this.callHandlers("challenge",[t,s]),this.configCallbacks.onChallenge&&this.safeCall(this.configCallbacks.onChallenge,[t,s]),setTimeout(()=>{i||(i=!0,e(!1))},5e3)):e(!1)})}addHandler(t,e,i){this.handlers.has(t)||this.handlers.set(t,[]),this.handlers.get(t).push({handler:e,once:i})}callHandlers(t,e){const i=this.handlers.get(t);if(!i||0===i.length)return;const s=[];for(let n=0;n<i.length;n++)this.safeCall(i[n].handler,e),i[n].once&&s.push(n);for(let n=s.length-1;n>=0;n--)i.splice(s[n],1);0===i.length&&this.handlers.delete(t)}callConfigCallback(t,e){if(t.startsWith("threat:")||"threat"===t)return void(t.startsWith("threat:")&&this.configCallbacks.onThreatDetected&&this.safeCall(this.configCallbacks.onThreatDetected,e));const i={ready:"onReady",error:"onError",block:"onBlock",allow:"onAllow"}[t];i&&this.configCallbacks[i]&&this.safeCall(this.configCallbacks[i],e)}safeCall(t,e){try{t(...e)}catch(i){}}}class o{constructor(){i(this,"endpoint",""),i(this,"clientKey",""),i(this,"encryptionRequired",!1),i(this,"currentNonce",""),i(this,"buffer",[]),i(this,"batchSize",20),i(this,"flushInterval",5e3),i(this,"intervalId"),i(this,"responseHandler",null),i(this,"callbackManager",null),i(this,"flushing",!1),i(this,"pendingFlush",!1),i(this,"backoffMs",0),i(this,"maxBackoffMs",6e4),i(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)??"",n.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(a.has(t)){const s={type:t,data:e,timestamp:i};this.callbackManager.emit(`threat:${t}`,s)}else this.callbackManager.emit(`data:${t}`,{type:t,data:e,timestamp:i});this.buffer.length>=this.batchSize&&this.flush()}async flush(){if(0===this.buffer.length||!this.endpoint)return;if(this.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 n.encrypt(t);s=JSON.stringify(e)}else s=JSON.stringify(t);const a={"Content-Type":"application/json","x-client-key":this.clientKey};this.currentNonce&&(a["x-request-nonce"]=this.currentNonce,this.currentNonce="");try{const i=await fetch(this.endpoint,{method:"POST",body:s,headers:a,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 n.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 c{constructor(t){i(this,"transmitter"),i(this,"isCollecting",!1),this.transmitter=t}start(){this.isCollecting||(this.isCollecting=!0)}stop(){this.isCollecting=!1}}class l{constructor(t){i(this,"transmitter"),i(this,"clickHistory",[]),i(this,"THRESHOLD_COUNT",3),i(this,"THRESHOLD_TIME",500),this.transmitter=t,this.init()}init(){document.addEventListener("click",t=>this.handleClick(t),!0)}handleClick(t){const e=Date.now();if(this.clickHistory.push(e),this.clickHistory=this.clickHistory.filter(t=>e-t<=this.THRESHOLD_TIME),this.clickHistory.length>=this.THRESHOLD_COUNT){const i=t.target,s={tagName:i.tagName,id:i.id,className:i.className,x:t.clientX,y:t.clientY};this.transmitter.send("rapid_click",{count:this.clickHistory.length,duration:this.THRESHOLD_TIME,target:s,timestamp:e}),this.clickHistory=[]}}}class h{constructor(t){i(this,"transmitter"),i(this,"element",null),this.transmitter=t}start(){this.element=document.createElement("input"),this.element.type="text";const t=["website","email_confirm","url","homepage","fax_number","address_line_2"],e=t[Math.floor(Math.random()*t.length)],i=Math.random().toString(36).substr(2,5);this.element.id="hp-"+Math.random().toString(36).substr(2,9),this.element.name=`${e}-${i}`,this.element.autocomplete="off",Object.assign(this.element.style,{position:"absolute",opacity:"0",top:"0",left:"-9999px",height:"1px",width:"1px",zIndex:"-1",border:"none"}),this.element.tabIndex=-1,this.element.setAttribute("aria-hidden","true"),this.element.setAttribute("role","presentation");const s=t=>{var e;this.transmitter.send("honeypot_triggered",{eventType:t.type,value:null==(e=this.element)?void 0:e.value,timestamp:Date.now()})};this.element.addEventListener("input",s),this.element.addEventListener("focus",s),this.element.addEventListener("click",s),document.body.appendChild(this.element)}stop(){this.element&&this.element.parentNode&&this.element.parentNode.removeChild(this.element)}}class d{constructor(t,e){i(this,"transmitter"),i(this,"wasmService"),i(this,"buffer",[]),i(this,"BUFFER_SIZE",50),i(this,"SAMPLE_INTERVAL",100),i(this,"SEND_COOLDOWN",5e3),i(this,"lastSampleTime",0),i(this,"lastSendTime",0),i(this,"handleMouseMove",t=>{const e=Date.now();e-this.lastSampleTime<this.SAMPLE_INTERVAL||(this.lastSampleTime=e,this.buffer.push({x:t.clientX,y:t.clientY,time:e}),this.buffer.length>this.BUFFER_SIZE&&this.buffer.shift(),this.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],s=this.buffer[i],n=Math.sqrt(Math.pow(s.x-e.x,2)+Math.pow(s.y-e.y,2)),a=s.time-e.time;a>0&&t.push(n/a)}if(t.length<2)return 1;const e=t.reduce((t,e)=>t+e,0)/t.length;return t.reduce((t,i)=>t+Math.pow(i-e,2),0)/t.length}}class u{constructor(t){i(this,"lastInteractionTime",0),i(this,"lastInteractionType","none"),i(this,"transmitter"),i(this,"isMobile",!1),i(this,"keyPressTimes",new Map),i(this,"lastKeyUpTime",0),i(this,"flightTimes",[]),i(this,"dwellTimes",[]),i(this,"suspiciousFocusCount",0),i(this,"suspiciousFocusResetTimer",null),i(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 s=this.keyPressTimes.get(t.code);if(s){const e=i-s;this.dwellTimes.push(e),this.keyPressTimes.delete(t.code)}this.flightTimes.length>=10&&this.reportKeystrokeDynamics(e)},{passive:!0,capture:!0}),document.addEventListener("blur",t=>{const e=t.target;("INPUT"===e.tagName||"TEXTAREA"===e.tagName)&&this.flightTimes.length>0&&this.reportKeystrokeDynamics(e)},{capture:!0})}checkFocusIntegrity(){const t=Date.now(),e=t-this.lastInteractionTime;performance.now()<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),s=this.average(this.dwellTimes),n=this.variance(this.dwellTimes,s);this.transmitter.send("input_metrics",{element:t.id||t.tagName,flight:{avg:e,variance:i,samples:this.flightTimes.length},dwell:{avg:s,variance:n},isMobile:this.isMobile,timestamp:Date.now(),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 m{constructor(){i(this,"wasmModule",null),i(this,"memory",null),i(this,"instance",null)}async load(t){try{const e=await fetch(`${t}/sdk/core.wasm`);if(!e.ok)throw new Error(`HTTP ${e.status}`);const i={env:{abort:()=>{}}};if(WebAssembly.instantiateStreaming){const t=await WebAssembly.instantiateStreaming(e,i);this.instance=t.instance}else{const t=await e.arrayBuffer(),s=await WebAssembly.instantiate(t,i);this.instance=s.instance}this.wasmModule=this.instance.exports,this.memory=this.wasmModule.memory}catch(e){}}isLoaded(){return!!this.instance}calculateEntropy(t){if(!this.instance||!this.wasmModule)return 0;const e=2*t.length,i=8*e;try{const s=this.wasmModule.__new(i,0),n=new Float64Array(this.memory.buffer,s,e);for(let e=0;e<t.length;e++)n[2*e]=t[e].x,n[2*e+1]=t[e].y;return this.wasmModule.calculateEntropy(s,e)}catch(s){return 0}}simpleHash(t){if(!this.instance||!this.wasmModule)return 0;try{const e=(new TextEncoder).encode(t),i=e.length,s=this.wasmModule.__new(i,0);return new Uint8Array(this.memory.buffer,s,i).set(e),this.wasmModule.simpleHash(s,i)}catch(e){return 0}}}class p{constructor(t,e){i(this,"transmitter"),i(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),s=new Uint8Array(i);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 i=e,s={available:!0},n=i.getExtension("WEBGL_debug_renderer_info");return n&&(s.renderer=i.getParameter(n.UNMASKED_RENDERER_WEBGL),s.vendor=i.getParameter(n.UNMASKED_VENDOR_WEBGL)),s.maxTextureSize=i.getParameter(i.MAX_TEXTURE_SIZE),s.maxViewportDims=Array.from(i.getParameter(i.MAX_VIEWPORT_DIMS)),s.maxRenderbufferSize=i.getParameter(i.MAX_RENDERBUFFER_SIZE),s.maxVertexAttribs=i.getParameter(i.MAX_VERTEX_ATTRIBS),s.extensions=(i.getSupportedExtensions()||[]).length,s}catch(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 g{constructor(t){i(this,"originalFetch"),i(this,"endpoint"),i(this,"callbackManager",null),i(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 s=await this.originalFetch(t,e);if(403===s.status){const a=s.clone();try{const n=await a.json();if("challenge"===n.action&&"captcha"===(null==(i=n.metadata)?void 0:i.type)){const i={action:"challenge",score:n.score,metadata:n.metadata};if(this.callbackManager){if(await this.callbackManager.emitChallenge(i))return this.originalFetch(t,e)}this.challengeInProgress||(this.challengeInProgress=this.showCaptchaModal().finally(()=>{this.challengeInProgress=null}));return await this.challengeInProgress?this.originalFetch(t,e):s}"block"===n.action&&this.callbackManager&&this.callbackManager.emit("block",{action:"block",score:n.score,metadata:n.metadata})}catch(n){}}return s}}async showCaptchaModal(){return new Promise(t=>{const e=document.createElement("div");e.id="sec-sdk-challenge-host",e.style.position="fixed",e.style.top="0",e.style.left="0",e.style.width="100vw",e.style.height="100vh",e.style.zIndex="999999",e.style.backgroundColor="rgba(0,0,0,0.5)",e.style.display="flex",e.style.justifyContent="center",e.style.alignItems="center";const i=e.attachShadow({mode:"open"}),s=document.createElement("div");s.style.background="white",s.style.padding="20px",s.style.borderRadius="8px",s.style.boxShadow="0 4px 12px rgba(0,0,0,0.2)",s.style.textAlign="center",s.style.fontFamily="system-ui, sans-serif";const n=document.createElement("h3");n.textContent="Security Check",n.style.margin="0 0 16px 0";const a=document.createElement("p");a.textContent="Unusual activity detected. Please verify you are human.",a.style.marginBottom="16px",a.style.fontSize="14px",a.style.color="#666";const r=document.createElement("div");r.innerHTML="Loading...",r.style.marginBottom="16px";const o=document.createElement("input");o.type="text",o.placeholder="Enter details",o.style.padding="8px",o.style.marginRight="8px",o.style.border="1px solid #ddd",o.style.borderRadius="4px";const c=document.createElement("button");c.textContent="Verify",c.style.padding="8px 16px",c.style.background="#007bff",c.style.color="white",c.style.border="none",c.style.borderRadius="4px",c.style.cursor="pointer";const l=document.createElement("p");l.style.color="red",l.style.fontSize="12px",l.style.display="none",s.appendChild(n),s.appendChild(a),s.appendChild(r),s.appendChild(o),s.appendChild(c),s.appendChild(l),i.appendChild(s),document.body.appendChild(e);let h="";const d=async()=>{try{const t=await this.originalFetch(`${this.endpoint}/challenge`),e=await t.json();h=e.id,r.innerHTML=e.svg}catch(t){r.textContent="Error loading CAPTCHA"}},u=async()=>{l.style.display="none",c.textContent="Verifying...";try{const i=o.value,s=await this.originalFetch(`${this.endpoint}/challenge/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({id:h,answer:i})});(await s.json()).success?(document.body.removeChild(e),t(!0)):(l.textContent="Incorrect, try again.",l.style.display="block",c.textContent="Verify",o.value="",d())}catch(i){l.textContent="System error.",l.style.display="block",c.textContent="Verify"}};c.onclick=u,o.onkeydown=t=>{"Enter"===t.key&&u()},d()})}}class f{constructor(t){i(this,"transmitter"),i(this,"eventsToWatch",["click","mousedown","keydown","touchstart","focus"]),i(this,"handleEvent",t=>{const e=t.target;if(!(e&&e instanceof HTMLElement))return;if(e===document.body||e===document.documentElement)return;const i=this.checkVisibility(e,t);if(i){const s=e.getBoundingClientRect();this.transmitter.send("invisible_interaction",{type:t.type,target:e.tagName,id:e.id,reason:i,timestamp:Date.now(),isTrusted:t.isTrusted,coordinates:{x:t instanceof MouseEvent?t.clientX:0,y:t instanceof MouseEvent?t.clientY:0},viewport:{width:window.innerWidth,height:window.innerHeight},scroll:{x:window.scrollX,y:window.scrollY},docDim:{width:document.documentElement.scrollWidth,height:document.documentElement.scrollHeight},elementRect:{top:s.top,left:s.left,width:s.width,height:s.height}})}}),this.transmitter=t}start(){this.eventsToWatch.forEach(t=>{document.addEventListener(t,this.handleEvent,{capture:!0,passive:!0})})}stop(){this.eventsToWatch.forEach(t=>{document.removeEventListener(t,this.handleEvent,{capture:!0})})}checkVisibility(t,e){var i,s;const n=window.getComputedStyle(t);if("none"===n.display)return"display:none";if("hidden"===n.visibility)return"visibility:hidden";if("0"===n.opacity)return"opacity:0";const a=t.getBoundingClientRect();if(a.width<=0||a.height<=0)return"zero_size";const r=a.right<0||a.left>window.innerWidth,o=a.bottom<0||a.top>window.innerHeight;if(r||o)return"off_screen";if(e instanceof MouseEvent||e instanceof TouchEvent){let n,a;if(e instanceof MouseEvent?(n=e.clientX,a=e.clientY):(n=(null==(i=e.touches[0])?void 0:i.clientX)||0,a=(null==(s=e.touches[0])?void 0:s.clientY)||0),n>=0&&n<=window.innerWidth&&a>=0&&a<=window.innerHeight){const i=document.elementFromPoint(n,a);if(i&&i!==t&&!t.contains(i)&&!i.contains(t)&&0===n&&0===a&&e.isTrusted)return null}}return null}}class y{constructor(t){i(this,"transmitter"),i(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 s=0;!0===navigator.webdriver&&(i.webdriver=!0,s+=40);try{this.detectCDP()&&(i.cdp=!0,s+=50)}catch(c){}const n=this.detectAutomationGlobals();n.length>0&&(i.automationGlobals=n,s+=30);const a=this.checkWebGL();a.suspicious&&(i.webgl=a,s+=25);const r=this.checkInconsistencies();r.length>0&&(i.inconsistencies=r,s+=15);const o=this.checkHeadless();o.score>0&&(i.headless=o.flags,s+=o.score),s>0&&this.transmitter.send("automation_detected",{signals:i,score:s,timestamp:Date.now()}),this.transmitter.send("init_signals",{webdriver:!!navigator.webdriver,plugins:(null==(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:a.renderer,webglVendor:a.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,n]of e)try{n()&&t.push(s)}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 s=e.getParameter(i.UNMASKED_RENDERER_WEBGL)||"",n=e.getParameter(i.UNMASKED_VENDOR_WEBGL)||"";return{suspicious:/SwiftShader/i.test(s)||/Mesa OffScreen/i.test(s)||/llvmpipe/i.test(s),renderer:s,vendor:n}}catch(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 w{constructor(t){i(this,"transmitter"),i(this,"sessionStart",0),i(this,"pageTransitions",[]),i(this,"interactionTimestamps",[]),i(this,"lastPageUrl",""),i(this,"formStartTimes",new Map),i(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,s,n){t.call(this,e,s,n),i.onPageTransition()},history.replaceState=function(t,s,n){e.call(this,t,s,n),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",s=this.formStartTimes.get(i);if(s){const t=Date.now()-s;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),s=this.analyzeTimingDistribution(i),n=this.analyzePageTransitions();this.transmitter.send("session_metrics",{type:"session_analysis",sessionDuration:e,totalInteractions:this.interactionTimestamps.length,pageTransitions:this.pageTransitions.length,timing:s,pages:n,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,s=Math.sqrt(i),n=e>0?s/e:0,a=this.shannonEntropy(t,50),r=this.autocorrelation(t);return{mean:Math.round(e),stdDev:Math.round(s),cv:parseFloat(n.toFixed(4)),entropy:parseFloat(a.toFixed(4)),autocorrelation:parseFloat(r.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,s=e>0?Math.sqrt(i)/e:0;return{count:this.pageTransitions.length,avgInterval:Math.round(e),cv:parseFloat(s.toFixed(4))}}shannonEntropy(t,e){const i=new Map;for(const a of t){const t=Math.floor(a/e);i.set(t,(i.get(t)||0)+1)}const s=t.length;let n=0;for(const a of i.values()){const t=a/s;t>0&&(n-=t*Math.log2(t))}return n}autocorrelation(t){if(t.length<3)return 0;const e=t.reduce((t,e)=>t+e,0)/t.length;let i=0,s=0;for(let n=0;n<t.length-1;n++)i+=(t[n]-e)*(t[n+1]-e);for(let n=0;n<t.length;n++)s+=Math.pow(t[n]-e,2);return 0===s?0:i/s}}class v{constructor(t){i(this,"transmitter"),i(this,"tabTimestamps",[]),i(this,"shiftTabCount",0),i(this,"tabCount",0),i(this,"isShiftDown",!1),i(this,"BURST_THRESHOLD_MS",80),i(this,"reportInterval",null),i(this,"REPORT_INTERVAL_MS",1e4),i(this,"MIN_TABS_TO_REPORT",5),i(this,"TAB_TRIGGER_COUNT",20),i(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}),i(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),s=this.analyzeBursts(e),n=t>0?this.shiftTabCount/t:0;this.transmitter.send("tab_navigation_metrics",{tabCount:this.tabCount,shiftTabCount:this.shiftTabCount,shiftTabRatio:parseFloat(n.toFixed(4)),intervals:i,bursts:s,timestamp:Date.now()}),this.resetBuffers()}resetBuffers(){this.tabTimestamps=[],this.tabCount=0,this.shiftTabCount=0}calculateIntervals(t){const e=[];for(let i=1;i<t.length;i++){const s=t[i]-t[i-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,i=t.reduce((t,i)=>t+Math.pow(i-e,2),0)/t.length,s=Math.sqrt(i),n=e>0?s/e:0,a=Math.min(...t);return{avg:parseFloat(e.toFixed(2)),variance:parseFloat(i.toFixed(2)),cv:parseFloat(n.toFixed(4)),min:a,samples:t.length}}analyzeBursts(t){let e=0,i=0,s=0,n=0,a=0;for(const r of t)r<this.BURST_THRESHOLD_MS?(i++,n+=r,a++):(i>=3&&(e++,s+=i),i=0);return i>=3&&(e++,s+=i),{count:e,avgLength:e>0?parseFloat((s/e).toFixed(1)):0,avgInterval:a>0?parseFloat((n/a).toFixed(2)):0}}}class b{constructor(t){i(this,"transmitter"),i(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(),s=await this.analyzeMedia(),n=this.benchmarkCanvas();let a=0;"virtual_gpu"!==t.category&&"software_render"!==t.category&&"cloud_gpu"!==t.category||(a+=2),e.cores<=2&&a++,null!==e.memory&&e.memory<=2&&a++,24===e.colorDepth&&a++,1===e.pixelRatio&&a++,i.noTaskbar&&a++,i.isVMResolution&&a++,0===s.cameras&&0===s.microphones&&a++,s.hasBluetooth||s.hasUSB||a++,n.canvasRenderTime>50&&a++;const{classification:r,confidence:o}=this.classify(t,e,a);this.transmitter.send("cloud_environment",{classification:r,confidence:o,signals:{gpu:{renderer:t.renderer,vendor:t.vendor,category:t.category},hardware:e,screen:i,media:s,performance:n},vmIndicatorCount:a,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 s=e.getParameter(i.UNMASKED_RENDERER_WEBGL)||"",n=e.getParameter(i.UNMASKED_VENDOR_WEBGL)||"";return{renderer:s,vendor:n,category:this.categorizeGPU(s,n)}}catch(t){return{renderer:"error",vendor:"error",category:"unknown"}}}categorizeGPU(t,e){const i=t.toLowerCase(),s=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(s)||/google cloud|gce/.test(i)||/google cloud|gce/.test(s)||/azure/.test(i)||/azure/.test(s)?"cloud_gpu":"physical"}analyzeHardware(){return{cores:navigator.hardwareConcurrency||0,memory:navigator.deviceMemory??null,colorDepth:screen.colorDepth,pixelRatio:window.devicePixelRatio||1}}analyzeScreen(){const t=screen.width,e=screen.height,i=screen.availHeight,s=e===i&&e===window.innerHeight,n=[[800,600],[1024,768],[1280,1024],[1280,800],[1920,1080]].some(([i,s])=>t===i&&e===s&&!(1920===i&&1080===s));return{width:t,height:e,availHeight:i,noTaskbar:s,isVMResolution:n}}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(a){}const i=!!navigator.bluetooth,s=!!navigator.usb;let n=null;try{if(navigator.getBattery){const t=await navigator.getBattery();n=!(t.charging&&1===t.level&&0===t.chargingTime)}}catch(a){}return{cameras:t,microphones:e,hasBluetooth:i,hasUSB:s,hasBattery:n}}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 n=0;n<500;n++)e.fillStyle=`rgb(${n%256},${3*n%256},${7*n%256})`,e.fillRect(13*n%200,7*n%200,10,10);e.getImageData(0,0,1,1);const s=performance.now()-i;return{canvasRenderTime:Math.round(100*s)/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 _{constructor(t){i(this,"transmitter"),i(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 s=0;const n={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},a=this.checkIframe(n);a.score>0&&(i.iframe=a.mismatches,s+=a.score);try{const t=await this.checkWorker(n);t.score>0&&(i.worker=t.mismatches,s+=t.score)}catch(r){}s>0&&this.transmitter.send("cross_context_mismatch",{signals:i,score:s,timestamp:Date.now()})}checkIframe(t){var e,i;const s=[];let n=0;try{const a=document.createElement("iframe");a.style.display="none",a.sandbox="allow-same-origin",document.body.appendChild(a);const r=a.contentWindow;if(!r)return document.body.removeChild(a),{score:0,mismatches:[]};const o=r.navigator;o.webdriver!==navigator.webdriver&&(s.push("webdriver_mismatch"),n+=40),navigator.webdriver||!0!==o.webdriver||(s.push("webdriver_spoofed_in_main"),n+=30);((null==(e=o.languages)?void 0:e.join(","))||"")!==t.languages&&(s.push("languages_mismatch"),n+=15),o.platform!==t.platform&&(s.push("platform_mismatch"),n+=15);((null==(i=o.plugins)?void 0:i.length)??0)!==t.pluginsLength&&(s.push("plugins_mismatch"),n+=10),document.body.removeChild(a)}catch(a){}return{score:n,mismatches:s}}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"}),s=URL.createObjectURL(i),n=new Worker(s),a=setTimeout(()=>{n.terminate(),URL.revokeObjectURL(s),e({score:0,mismatches:[]})},3e3);n.onmessage=i=>{clearTimeout(a),n.terminate(),URL.revokeObjectURL(s);const r=i.data,o=[];let c=0;r.webdriver!==t.webdriver&&(o.push("worker_webdriver_mismatch"),c+=35),r.languages!==t.languages&&(o.push("worker_languages_mismatch"),c+=15),r.platform!==t.platform&&(o.push("worker_platform_mismatch"),c+=15),r.hardwareConcurrency!==t.hardwareConcurrency&&(o.push("worker_concurrency_mismatch"),c+=10),r.userAgent!==t.userAgent&&(o.push("worker_ua_mismatch"),c+=20),e({score:c,mismatches:o})},n.onerror=()=>{clearTimeout(a),n.terminate(),URL.revokeObjectURL(s),e({score:0,mismatches:[]})},n.postMessage("check")}catch(i){e({score:0,mismatches:[]})}})}}class T{constructor(t){i(this,"transmitter"),i(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 s=await this.checkClientHints();s.suspicious&&(t.clientHints=s,e+=20);const n=this.checkCDPMouseSignature();n.suspicious&&(t.cdpMouse=n,e+=30);const a=this.checkHairlineSupport();a.suspicious&&(t.hairline=a,e+=10);const r=this.checkExtraFrameworks();r.length>0&&(t.extraFrameworks=r,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 s=e.width,n=e.height;t({suspicious:0===s&&0===n,width:s,height:n})},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,s=(e.brands||[]).map(t=>t.brand);/Chrome\/\d/.test(i)&&!s.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 s=[],n=i=>{s.push(i),e++,0===i.movementX&&0===i.movementY&&t++};document.addEventListener("mousemove",n,{passive:!0}),setTimeout(()=>{document.removeEventListener("mousemove",n)},5e3),e>10&&t/e>.9&&(i=!0)}catch(s){}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 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 n=Object.getOwnPropertyNames(navigator);for(const e of n)/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),s=new Worker(i),n=setTimeout(()=>{s.terminate(),URL.revokeObjectURL(i),t({suspicious:!1})},3e3);s.onmessage=e=>{clearTimeout(n),s.terminate(),URL.revokeObjectURL(i),t({suspicious:!0===e.data.cdp})},s.onerror=()=>{clearTimeout(n),s.terminate(),URL.revokeObjectURL(i),t({suspicious:!1})},s.postMessage("check")}catch(e){t({suspicious:!1})}})}}const k="__aie_token";class C{constructor(t){i(this,"config"),i(this,"renewTimer",null),i(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(),s=[];for(const c of i)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 n=s.join(":"),a=await this.getFingerprint(),r=await fetch(`${this.config.apiBase}/crawl-protect/verify`,{method:"POST",headers:{"Content-Type":"application/json","x-client-id":this.config.clientId},body:JSON.stringify({id:e,solution:n,fingerprint:a}),credentials:"include"});if(!r.ok)return!1;const o=await r.json();return!(!o.success||!o.token)&&(this.setToken(o.token),this.scheduleRenewal(o.token),this.config.debug,!0)}catch(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(`(?:^|; )${k}=([^;]*)`));return t?decodeURIComponent(t[1]):null}setToken(t){const e=new Date(Date.now()+18e5).toUTCString();document.cookie=`${k}=${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,"/"))),s=i.exp-3e5-Date.now();s>0&&(this.renewTimer=setTimeout(()=>this.solveChallenge(),s))}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 E=new class{constructor(){i(this,"transmitter"),i(this,"behaviorCollector"),i(this,"rapidClickDetector"),i(this,"honeypot"),i(this,"mouseTracker"),i(this,"canvasFingerprinter"),i(this,"inputTracker"),i(this,"challengeHandler"),i(this,"invisibleInteraction"),i(this,"automationDetector"),i(this,"sessionAnalyzer"),i(this,"tabNavigationAnalyzer"),i(this,"cloudEnvironmentDetector"),i(this,"crossContextDetector"),i(this,"headlessProbeDetector"),i(this,"crawlProtect",null),i(this,"initialized",!1),i(this,"wasmService"),i(this,"callbackManager"),this.transmitter=new o,this.wasmService=new m,this.callbackManager=new r,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 d(this.transmitter,this.wasmService),this.canvasFingerprinter=new p(this.transmitter,this.wasmService),this.inputTracker=new u(this.transmitter),this.invisibleInteraction=new f(this.transmitter),this.automationDetector=new y(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)}async init(t){var e,i;if(this.initialized)return;t.callbacks&&this.callbackManager.setConfigCallbacks(t.callbacks);const s=t.endpoint.replace(/\/events$/,"");try{await this.wasmService.load(s),this.startDetectors(),this.transmitter.setConfig(t),this.challengeHandler=new g(s),this.challengeHandler.setCallbackManager(this.callbackManager),!1!==(null==(e=t.serverConfig)?void 0:e.captchaEnabled)&&this.challengeHandler.start();((null==(i=t.serverConfig)?void 0:i.devtoolsDetection)??!t.debug)&&Promise.resolve().then(()=>x).then(({AntiDebug:t})=>{t.start(),Promise.resolve().then(()=>M).then(({ConsoleDetector:t})=>{new t(()=>{this.transmitter.send("devtools_open",{detected:!0})}).start()})}),t.crawlProtect&&(this.crawlProtect=new C({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(n){this.callbackManager.emit("error",{code:"INIT_ERROR",message:"SecuritySDK initialization failed",details:null==n?void 0:n.message})}}on(t,e){this.callbackManager.on(t,e)}off(t,e){this.callbackManager.off(t,e)}once(t,e){this.callbackManager.once(t,e)}startDetectors(){this.behaviorCollector.start(),this.honeypot.start(),this.mouseTracker.start(),this.canvasFingerprinter.start(),this.inputTracker.start(),this.invisibleInteraction.start(),this.automationDetector.start(),this.sessionAnalyzer.start(),this.tabNavigationAnalyzer.start(),this.cloudEnvironmentDetector.start(),this.crossContextDetector.start(),this.headlessProbeDetector.start()}};"undefined"!=typeof window&&(window.SecuritySDK=E);const S={};class A{static start(){this.saveConsole(),this.disableConsole(),this.preventDevTools()}static stop(){this.intervalId&&clearInterval(this.intervalId)}static getOriginalConsole(){return S}static saveConsole(){const t=["log","debug","info","warn","error","table","trace","dir","clear"];try{const e=window.console;if(!e)return;for(const i of t)"function"==typeof e[i]&&(S[i]=e[i].bind(e))}catch(e){}}static preventDevTools(){this.intervalId=setInterval(()=>{this.debuggerCheck(),this.devtoolsCloseCheck()},this.checkInterval)}static debuggerCheck(){!function(){try{(function(){}).constructor("debugger")()}catch(t){}}()}static devtoolsCloseCheck(){if(navigator.maxTouchPoints>0||/Mobile|Android|iPhone|iPad/i.test(navigator.userAgent))return;const t=performance.now();(function(){}).constructor("debugger")();if(performance.now()-t>100)try{document.body.innerHTML='<div style="display:flex;align-items:center;justify-content:center;height:100vh;font-family:sans-serif;background:#111;color:#fff"><div style="text-align:center"><h2 style="margin-bottom:12px">⚠ 보안 경고</h2><p style="color:#999">개발자 도구가 감지되었습니다.<br>페이지를 계속 이용하려면 개발자 도구를 닫아주세요.</p></div></div>'}catch(e){}}static disableConsole(){const t=()=>{},e=["log","debug","info","warn","error","table","trace","dir"];try{const i=window.console;if(!i)return;for(const s of e)i[s]&&(i[s]=t)}catch(i){}}}i(A,"checkInterval",1e3),i(A,"intervalId");const x=Object.freeze(Object.defineProperty({__proto__:null,AntiDebug:A},Symbol.toStringTag,{value:"Module"}));const M=Object.freeze(Object.defineProperty({__proto__:null,ConsoleDetector:class{constructor(t){i(this,"onDetect"),i(this,"intervals",[]),i(this,"detected",!1),this.onDetect=t}start(){this.startGetterTrap(),this.startSizeDetection()}stop(){for(const t of this.intervals)clearInterval(t);this.intervals=[]}triggerDetect(){this.detected||(this.detected=!0,this.onDetect(),setTimeout(()=>{this.detected=!1},5e3))}startGetterTrap(){const t=A.getOriginalConsole(),e=t.log,i=t.clear;if(!e)return;const s=document.createElement("div");Object.defineProperty(s,"id",{get:()=>(this.triggerDetect(),"")});const n=/./;n.toString=()=>(this.triggerDetect(),"");const a=setInterval(()=>{try{e(s),e(n),i&&i()}catch(t){}},1500);this.intervals.push(a)}startSizeDetection(){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=E,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),document.addEventListener("contextmenu",t=>{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},5e3))}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"})});
|