UNPKG

@newgenesis/vision

Version:

Professional bot and AI detection library with behavioral analysis, fingerprinting, and adaptive challenges

2 lines 56.4 kB
'use strict';Object.defineProperty(exports,'__esModule',{value:true});/** @license MIT - Sentinel by NewGenesis (https://newgenesis.ai) */ var le=Object.defineProperty;var ne=(u,i)=>{for(var e in i)le(u,e,{get:i[e],enumerable:true});};var se={};ne(se,{API_ENDPOINTS:()=>ue,BEHAVIORAL_THRESHOLDS:()=>w,DEBUG_CONFIG:()=>S,DEFAULT_CHALLENGES:()=>j,DEFAULT_MODULES:()=>Y,DEFAULT_THRESHOLDS:()=>X,FINGERPRINT_FLAGS:()=>E,MODULE_WEIGHTS:()=>O,NETWORK_THRESHOLDS:()=>T,PERFORMANCE_BUDGETS:()=>ce,SESSION_CONFIG:()=>R,TEXT_ANALYSIS_THRESHOLDS:()=>x,VISION_METADATA:()=>he});var X={accept:.4,challenge:.7,block:.7},Y={behavioral:true,fingerprint:true,textAnalysis:false,network:true},j={defaultType:"checkbox",progressive:true,powDifficulty:5},O={behavioral:.35,fingerprint:.3,textAnalysis:.2,network:.15},w={MIN_MOUSE_EVENTS:10,MIN_KEYBOARD_EVENTS:5,MIN_SCROLL_EVENTS:3,MIN_MOUSE_VARIANCE:50,MAX_MOUSE_VARIANCE:5e3,MIN_KEY_TIMING:50,MAX_KEY_TIMING:2e3,KEY_TIMING_VARIANCE_THRESHOLD:30,MIN_MOUSE_VELOCITY:.1,MAX_MOUSE_VELOCITY:10,MIN_FOCUS_EVENTS:1},E={WEBDRIVER_PRESENT:"navigator.webdriver present",CHROME_HEADLESS:"chrome headless detected",PHANTOM_JS:"phantomjs detected",SELENIUM:"selenium detected",CANVAS_NOISE_MISSING:"canvas noise missing",CANVAS_BLOCKED:"canvas fingerprint blocked",WEBGL_UNMASKED:"webgl vendor/renderer unmasked",WEBGL_INCONSISTENT:"webgl inconsistent",PLUGINS_EMPTY:"no plugins detected",LANGUAGES_INCONSISTENT:"languages inconsistent",PLATFORM_MISMATCH:"platform mismatch"},x={MIN_TEXT_LENGTH:50,MIN_LEXICAL_RICHNESS:.3,MAX_LEXICAL_RICHNESS:.8,AI_PERPLEXITY_THRESHOLD:50,AI_CONFIDENCE_THRESHOLD:.7,MIN_PUNCTUATION_RATE:.02,MAX_PUNCTUATION_RATE:.15},T={MAX_REQUEST_JITTER:100,MIN_LATENCY:10,SUSPICIOUS_RTT:500,SUSPICIOUS_DOWNLINK:10},R={DURATION:6e5,STORAGE_KEY:"vision_session"},ce={INIT:100,ANALYSIS:500,FINGERPRINT:200,BEHAVIORAL:100,TEXT_ANALYSIS:1e3},ue={VERIFY:"/api/vision/verify",CHALLENGE:"/api/vision/challenge",REPORT:"/api/vision/report"},he={NAME:"Vision",VERSION:"0.1.0",AUTHOR:"NewGenesis",HOMEPAGE:"https://newgenesis.ai"},S={LOG_PREFIX:"[Vision]",VERBOSE:false,PERFORMANCE_TRACKING:true};var oe=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n))(oe||{}),J=class u{constructor(){this.debugMode=false;this.minLevel=1;}static getInstance(){return u.instance||(u.instance=new u),u.instance}setDebug(i){this.debugMode=i,this.minLevel=i?0:1;}setMinLevel(i){this.minLevel=i;}debug(i,...e){this.debugMode&&this.minLevel<=0&&console.debug(`${S.LOG_PREFIX} [DEBUG]`,i,...e);}info(i,...e){this.minLevel<=1&&console.info(`${S.LOG_PREFIX} [INFO]`,i,...e);}warn(i,...e){this.minLevel<=2&&console.warn(`${S.LOG_PREFIX} [WARN]`,i,...e);}error(i,e,...t){this.minLevel<=3&&console.error(`${S.LOG_PREFIX} [ERROR]`,i,e,...t);}performance(i,e){this.debugMode&&S.PERFORMANCE_TRACKING&&console.log(`${S.LOG_PREFIX} [PERF] ${i}: ${e.toFixed(2)}ms`);}groupStart(i){this.debugMode&&console.group(`${S.LOG_PREFIX} ${i}`);}groupEnd(){this.debugMode&&console.groupEnd();}},o=J.getInstance();var ae={};ne(ae,{calculateMean:()=>M,calculateMedian:()=>de,calculateStdDev:()=>C,calculateVariance:()=>y,calculateVelocity:()=>U,clamp:()=>A,debounce:()=>ge,deepClone:()=>ve,euclideanDistance:()=>re,formatTimestamp:()=>fe,generateHash:()=>V,generateSessionId:()=>Q,getTimestamp:()=>me,isBrowser:()=>I,isDefined:()=>be,isNode:()=>pe,normalizeScore:()=>H,safeJsonParse:()=>Z,safeLocalStorageGet:()=>ee,safeLocalStorageSet:()=>te,throttle:()=>G,weightedAverage:()=>ie});function Q(){return `vision_${Date.now()}_${Math.random().toString(36).substr(2,9)}`}async function V(u){if(typeof window<"u"&&window.crypto&&window.crypto.subtle){let t=new TextEncoder().encode(u),n=await window.crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}let i=0;for(let e=0;e<u.length;e++){let t=u.charCodeAt(e);i=(i<<5)-i+t,i=i&i;}return Math.abs(i).toString(16)}function y(u){if(u.length===0)return 0;let i=u.reduce((n,s)=>n+s,0)/u.length;return u.map(n=>Math.pow(n-i,2)).reduce((n,s)=>n+s,0)/u.length}function C(u){return Math.sqrt(y(u))}function M(u){return u.length===0?0:u.reduce((i,e)=>i+e,0)/u.length}function de(u){if(u.length===0)return 0;let i=[...u].sort((t,n)=>t-n),e=Math.floor(i.length/2);return i.length%2===0?(i[e-1]+i[e])/2:i[e]}function H(u,i,e){if(e===i)return 0;let t=(u-i)/(e-i);return Math.max(0,Math.min(1,t))}function re(u,i,e,t){return Math.sqrt(Math.pow(e-u,2)+Math.pow(t-i,2))}function U(u,i,e,t,n){return n===0?0:re(u,i,e,t)/n}function ge(u,i){let e=null;return function(...n){let s=()=>{e=null,u(...n);};e&&clearTimeout(e),e=setTimeout(s,i);}}function G(u,i){let e=false;return function(...n){e||(u(...n),e=true,setTimeout(()=>e=false,i));}}function I(){return typeof window<"u"&&typeof document<"u"}function pe(){return typeof process<"u"&&process.versions!=null&&process.versions.node!=null}function Z(u,i){try{return JSON.parse(u)}catch{return i}}function ee(u){if(console.warn("\u26A0\uFE0F safeLocalStorageGet is deprecated. Use Supabase services instead."),!I())return null;try{return localStorage.getItem(u)}catch{return null}}function te(u,i){if(console.warn("\u26A0\uFE0F safeLocalStorageSet is deprecated. Use Supabase services instead."),!I())return false;try{return localStorage.setItem(u,i),!0}catch{return false}}function me(){return Date.now()}function fe(u){return new Date(u).toISOString()}function ve(u){return JSON.parse(JSON.stringify(u))}function be(u){return u!=null}function A(u,i,e){return Math.min(Math.max(u,i),e)}function ie(u,i){if(u.length!==i.length||u.length===0)return 0;let e=u.reduce((n,s,r)=>n+s*i[r],0),t=i.reduce((n,s)=>n+s,0);return t===0?0:e/t}var L=class{constructor(i){this.sessionId=i,this.storageKey=`${R.STORAGE_KEY}_${i}`,this.sessionData={sessionId:i,startTime:Date.now(),lastActivity:Date.now(),results:[],metadata:{}};}async init(){o.debug("Initializing SessionManager"),await this.loadFromStorage(),await this.saveToStorage(),o.debug("SessionManager initialized",{sessionId:this.sessionId});}async loadFromStorage(){if(I())try{let i=ee(this.storageKey);if(i){let e=Z(i,this.sessionData),t=Date.now();t-e.lastActivity<R.DURATION?(this.sessionData=e,this.sessionData.lastActivity=t,o.debug("Loaded existing session from storage")):o.debug("Session expired, creating new session");}}catch(i){o.error("Failed to load session from storage",i);}}async saveToStorage(){if(I())try{let i=JSON.stringify(this.sessionData);te(this.storageKey,i),o.debug("Saved session to storage");}catch(i){o.error("Failed to save session to storage",i);}}updateActivity(){this.sessionData.lastActivity=Date.now(),this.saveToStorage();}updateResult(i){this.sessionData.results.push(i),this.updateActivity(),this.saveToStorage(),o.debug("Added result to session",{resultCount:this.sessionData.results.length});}getResults(){return [...this.sessionData.results]}getLatestResult(){return this.sessionData.results.length>0?this.sessionData.results[this.sessionData.results.length-1]:null}getMetadata(){return {...this.sessionData.metadata}}setMetadata(i,e){this.sessionData.metadata[i]=e,this.saveToStorage();}getStats(){let i=this.sessionData.results;if(i.length===0)return {totalDetections:0,averageScore:0,highestScore:0,lowestScore:0,actions:{accept:0,challenge:0,block:0},riskLevels:{low:0,medium:0,high:0,critical:0}};let e=i.map(l=>l.score),t=e.reduce((l,c)=>l+c,0)/e.length,n=Math.max(...e),s=Math.min(...e),r=i.reduce((l,c)=>(l[c.action]++,l),{accept:0,challenge:0,block:0}),a=i.reduce((l,c)=>(l[c.riskLevel]++,l),{low:0,medium:0,high:0,critical:0});return {totalDetections:i.length,averageScore:t,highestScore:n,lowestScore:s,actions:r,riskLevels:a}}isExpired(){return Date.now()-this.sessionData.lastActivity>=R.DURATION}getDuration(){return Date.now()-this.sessionData.startTime}reset(){o.debug("Resetting session"),this.sessionData={sessionId:this.sessionId,startTime:Date.now(),lastActivity:Date.now(),results:[],metadata:{}},this.saveToStorage();}destroy(){if(o.debug("Destroying session"),I())try{localStorage.removeItem(this.storageKey);}catch(i){o.error("Failed to remove session from storage",i);}}getSessionId(){return this.sessionId}getData(){return {...this.sessionData}}};var _=class{constructor(i){this.customWeights={};this.thresholds=i;}async init(){o.debug("Initializing ScoringEngine"),this.validateWeights(),o.debug("ScoringEngine initialized");}calculateCombinedScore(i){o.debug("Calculating combined score",i);let e={...O,...this.customWeights},t=[],n=[];i.behavioral>0&&(t.push(i.behavioral),n.push(e.behavioral)),i.fingerprint>0&&(t.push(i.fingerprint),n.push(e.fingerprint)),i.textAnalysis!==void 0&&i.textAnalysis>0&&(t.push(i.textAnalysis),n.push(e.textAnalysis)),i.network>0&&(t.push(i.network),n.push(e.network));let s=0;return t.length>0&&(s=ie(t,n)),s=A(s,0,1),o.debug(`Combined score: ${s.toFixed(3)}`),s}setCustomWeights(i){this.customWeights=i,o.debug("Custom weights set",i),this.validateWeights();}validateWeights(){let i={...O,...this.customWeights},e=Object.values(i).reduce((t,n)=>t+n,0);Math.abs(e-1)>.01&&o.warn(`Module weights sum to ${e}, should be 1.0`);}calculateConfidence(i){let e=0,t=0;i.behavioral>0&&e++,t++,i.fingerprint>0&&e++,t++,i.textAnalysis!==void 0&&i.textAnalysis>0&&e++,t++,i.network>0&&e++,t++;let n=e/t;return o.debug(`Confidence: ${n.toFixed(2)} (${e}/${t} signals)`),n}adjustScoreWithHistory(i,e){if(e.length===0)return i;let n=(e.reduce((r,a)=>r+a,0)/e.length-.5)*.1,s=A(i+n,0,1);return o.debug(`Score adjusted with history: ${i.toFixed(3)} \u2192 ${s.toFixed(3)}`),s}calculateScoreVariance(i){if(i.length<2)return 0;let e=i.reduce((n,s)=>n+s,0)/i.length;return i.reduce((n,s)=>n+Math.pow(s-e,2),0)/i.length}detectScoreAnomaly(i,e){if(e.length<3)return false;let t=e.reduce((a,l)=>a+l,0)/e.length,n=this.calculateScoreVariance(e),s=Math.sqrt(n),r=Math.abs(i-t)>2*s;return r&&o.warn("Score anomaly detected",{currentScore:i,mean:t,stdDev:s}),r}getRecommendedAction(i){let{accept:e,block:t}=this.thresholds,n,s;if(i<e)n="accept",s=1-i/e;else if(i>=t)n="block",s=(i-t)/(1-t);else {n="challenge";let r=(e+t)/2;s=Math.abs(i-r)/((t-e)/2);}return s=A(s,0,1),{action:n,confidence:s}}reset(){o.debug("Resetting ScoringEngine"),this.customWeights={};}getThresholds(){return {...this.thresholds}}setThresholds(i){this.thresholds={...this.thresholds,...i},o.debug("Thresholds updated",this.thresholds);}};var W=class{constructor(i="adaptive"){this.sessionHistory=new Map;this.mode=i;}updateSession(i,e,t){let n=this.sessionHistory.get(i);n?(n.interactions=e,n.duration=t,n.lastSeen=Date.now()):this.sessionHistory.set(i,{sessionId:i,interactions:e,duration:t,challenges:0,successes:0,lastSeen:Date.now()});}recordChallenge(i,e){let t=this.sessionHistory.get(i);t&&(t.challenges++,e&&t.successes++);}calculateProgressiveScore(i,e,t){let n=this.sessionHistory.get(i);if(!n)return t;let s=0;if(n.duration>3e4&&n.interactions>20&&(s-=.15),n.duration>6e4&&n.interactions>50&&(s-=.25),n.challenges>0){let a=n.successes/n.challenges;a>.8?s-=.1:a<.3&&(s+=.2);}let r=n.interactions/(n.duration/1e3);return (r<.1||r>50)&&(s+=.15),Math.max(0,Math.min(1,t+s))}calculateMultiModalScore(i){let e=this.getWeightsForMode(),t=0;return t+=(i.behavioral||0)*e.behavioral,t+=(i.fingerprint||0)*e.fingerprint,t+=(i.environmental||0)*e.environmental,t+=(i.sessionAnomaly||0)*e.sessionAnomaly,t+=(i.textAnalysis||0)*e.textAnalysis,t+=(i.networkAnalysis||0)*e.networkAnalysis,Math.max(0,Math.min(1,t))}getWeightsForMode(){switch(this.mode){case "lite":return {behavioral:.8,fingerprint:.2,environmental:0,sessionAnomaly:0,textAnalysis:0,networkAnalysis:0};case "strict":return {behavioral:.35,fingerprint:.25,environmental:.25,sessionAnomaly:.15,textAnalysis:0,networkAnalysis:0};case "adaptive":return {behavioral:.3,fingerprint:.2,environmental:.2,sessionAnomaly:.15,textAnalysis:.1,networkAnalysis:.05};case "enterprise":return {behavioral:.25,fingerprint:.2,environmental:.2,sessionAnomaly:.15,textAnalysis:.1,networkAnalysis:.1};default:return {behavioral:.5,fingerprint:.5,environmental:0,sessionAnomaly:0,textAnalysis:0,networkAnalysis:0}}}shouldReduceChallenges(i){let e=this.sessionHistory.get(i);return e?e.duration>45e3&&e.interactions>30||e.challenges>2&&e.successes/e.challenges>.9:false}getRecommendedAction(i,e){let t=this.sessionHistory.get(e);return this.mode==="lite"?i<.5?"accept":i<.7?"challenge":"block":this.mode==="strict"?i<.3?"accept":i<.5?"challenge":"block":this.mode==="adaptive"||this.mode==="enterprise"?t&&t.duration>6e4&&t.interactions>50?i<.5?"accept":i<.7?"challenge":"block":this.mode==="enterprise"?i<.25?"accept":i<.45?"challenge":"block":i<.35?"accept":i<.6?"challenge":"block":i<.4?"accept":i<.6?"challenge":"block"}cleanupOldSessions(i=36e5){let e=Date.now();for(let[t,n]of this.sessionHistory)e-n.lastSeen>i&&this.sessionHistory.delete(t);}};var b=class{constructor(i){this.isInitialized=false;this.isActive=false;this.startTime=0;this.name=i;}start(){if(!this.isInitialized)throw new Error(`Module ${this.name} not initialized`);if(this.isActive){o.warn(`Module ${this.name} already started`);return}this.startTime=Date.now(),this.isActive=true,this.onStart(),o.debug(`Module ${this.name} started`);}stop(){this.isActive&&(this.isActive=false,this.onStop(),o.debug(`Module ${this.name} stopped`));}reset(){o.debug(`Resetting module ${this.name}`),this.isActive=false,this.startTime=0,this.onReset();}onStart(){}onStop(){}onReset(){}getElapsedTime(){return this.isActive?Date.now()-this.startTime:0}isReady(){return this.isInitialized}isRunning(){return this.isActive}};var P=class extends b{constructor(){super("behavioral");this.mouseEvents=[];this.keyboardEvents=[];this.scrollEvents=[];this.focusEvents=[];this.blurEvents=[];this.pasteDetected=false;this.eventListeners=new Map;}async init(){if(o.debug("Initializing BehavioralModule"),typeof window>"u")throw new Error("BehavioralModule requires browser environment");this.isInitialized=true,o.debug("BehavioralModule initialized");}onStart(){o.debug("Starting behavioral tracking"),this.setupMouseTracking(),this.setupKeyboardTracking(),this.setupScrollTracking(),this.setupFocusTracking(),o.debug("Behavioral tracking active");}onStop(){o.debug("Stopping behavioral tracking"),this.removeEventListeners(),o.debug("Behavioral tracking stopped");}setupMouseTracking(){if(typeof window>"u")return;let e=G(r=>{this.mouseEvents.push({x:r.clientX,y:r.clientY,timestamp:Date.now()}),this.mouseEvents.length>100&&this.mouseEvents.shift();},50),t=r=>{o.debug("Click detected",{x:r.clientX,y:r.clientY});},n=e,s=t;window.addEventListener("mousemove",n),window.addEventListener("click",s),this.eventListeners.set("mousemove",n),this.eventListeners.set("click",s);}setupKeyboardTracking(){let e=r=>{this.keyboardEvents.push({key:r.key,timestamp:Date.now()}),this.keyboardEvents.length>50&&this.keyboardEvents.shift();},t=()=>{this.pasteDetected=true,o.debug("Paste event detected");},n=e,s=t;window.addEventListener("keydown",n),window.addEventListener("paste",s),this.eventListeners.set("keydown",n),this.eventListeners.set("paste",s);}setupScrollTracking(){let t=G(()=>{this.scrollEvents.push({x:window.scrollX,y:window.scrollY,timestamp:Date.now()}),this.scrollEvents.length>50&&this.scrollEvents.shift();},100);window.addEventListener("scroll",t),this.eventListeners.set("scroll",t);}setupFocusTracking(){let e=()=>{this.focusEvents.push(Date.now());},t=()=>{this.blurEvents.push(Date.now());},n=e,s=t;window.addEventListener("focus",n),window.addEventListener("blur",s),this.eventListeners.set("focus",n),this.eventListeners.set("blur",s);}removeEventListeners(){for(let[e,t]of this.eventListeners)window.removeEventListener(e,t);this.eventListeners.clear();}async analyze(){o.debug("Analyzing behavioral data");let e=0,t=0,n=this.analyzeMouseBehavior();n>=0&&(e+=n,t++);let s=this.analyzeKeyboardBehavior();s>=0&&(e+=s,t++);let r=this.analyzeScrollBehavior();r>=0&&(e+=r,t++);let a=this.analyzeFocusPatterns();a>=0&&(e+=a,t++);let l=t>0?e/t:0;return o.debug(`Behavioral analysis complete: ${l.toFixed(3)}`),l}analyzeMouseBehavior(){let e=this.mouseEvents;if(e.length<w.MIN_MOUSE_EVENTS)return o.debug("Insufficient mouse events for analysis"),-1;let t=0,n=e.map(h=>h.x),s=e.map(h=>h.y),r=y(n),a=y(s);r+a<w.MIN_MOUSE_VARIANCE&&(t+=.3,o.debug("Low mouse variance detected (bot-like)"));let c=[];for(let h=1;h<e.length;h++){let g=e[h-1],d=e[h],m=d.timestamp-g.timestamp;if(m>0){let v=U(g.x,g.y,d.x,d.y,m);c.push(v);}}if(c.length>0){let h=M(c);C(c)<.1&&(t+=.2,o.debug("Constant velocity detected (bot-like)")),h>w.MAX_MOUSE_VELOCITY&&(t+=.3,o.debug("Inhuman mouse velocity detected"));}return this.calculateStraightLineRatio()>.8&&(t+=.2,o.debug("Excessive straight line movements (bot-like)")),Math.min(t,1)}calculateStraightLineRatio(){let e=this.mouseEvents;if(e.length<3)return 0;let t=0,n=e.length-2;for(let s=1;s<e.length-1;s++){let r=e[s-1],a=e[s],l=e[s+1],c=Math.atan2(a.y-r.y,a.x-r.x),p=Math.atan2(l.y-a.y,l.x-a.x);Math.abs(c-p)<.1&&t++;}return t/n}analyzeKeyboardBehavior(){let e=this.keyboardEvents;if(e.length<w.MIN_KEYBOARD_EVENTS)return o.debug("Insufficient keyboard events for analysis"),-1;let t=0,n=[];for(let l=1;l<e.length;l++){let c=e[l].timestamp-e[l-1].timestamp;n.push(c);}let s=M(n),r=y(n);return Math.sqrt(r)<w.KEY_TIMING_VARIANCE_THRESHOLD&&(t+=.4,o.debug("Consistent keyboard timing detected (bot-like)")),s<w.MIN_KEY_TIMING&&(t+=.3,o.debug("Inhuman typing speed detected")),this.pasteDetected&&(t+=.3,o.debug("Paste event detected")),Math.min(t,1)}analyzeScrollBehavior(){let e=this.scrollEvents;if(e.length<w.MIN_SCROLL_EVENTS)return o.debug("Insufficient scroll events for analysis"),-1;let t=0,n=[];for(let s=1;s<e.length;s++){let r=e[s-1],a=e[s],l=a.timestamp-r.timestamp;if(l>0){let p=Math.abs(a.y-r.y)/l;n.push(p);}}n.length>0&&C(n)<.05&&(t+=.3,o.debug("Consistent scroll speed detected (bot-like)"));for(let s=1;s<e.length;s++){let r=e[s-1],a=e[s],l=a.timestamp-r.timestamp,c=Math.abs(a.y-r.y);if(l<10&&c>500){t+=.2,o.debug("Programmatic scroll detected");break}}return Math.min(t,1)}analyzeFocusPatterns(){let e=this.focusEvents.length,t=this.blurEvents.length;if(e===0&&t===0)return -1;let n=0,s=e+t,r=this.getElapsedTime();return r>0&&s/r*1e3>2&&(n+=.3,o.debug("Excessive focus/blur switching detected")),Math.min(n,1)}async getDetails(){let e=this.mouseEvents.length>0?y(this.mouseEvents.map(s=>s.x))+y(this.mouseEvents.map(s=>s.y)):0,t=[];for(let s=1;s<this.mouseEvents.length;s++){let r=this.mouseEvents[s-1],a=this.mouseEvents[s],l=a.timestamp-r.timestamp;l>0&&t.push(U(r.x,r.y,a.x,a.y,l));}let n=[];for(let s=1;s<this.keyboardEvents.length;s++)n.push(this.keyboardEvents[s].timestamp-this.keyboardEvents[s-1].timestamp);return {mouseEvents:{count:this.mouseEvents.length,variance:e,velocity:t,humanLike:e>=w.MIN_MOUSE_VARIANCE},keyboardEvents:{count:this.keyboardEvents.length,interKeyTiming:n,pasteDetected:this.pasteDetected,humanLike:n.length>0&&C(n)>=w.KEY_TIMING_VARIANCE_THRESHOLD},scrollEvents:{count:this.scrollEvents.length,pattern:this.scrollEvents.map(s=>s.y),naturalScroll:this.scrollEvents.length>=w.MIN_SCROLL_EVENTS},focusEvents:{count:this.focusEvents.length,blur:this.blurEvents.length,pattern:"normal"},score:await this.analyze()}}onReset(){this.mouseEvents=[],this.keyboardEvents=[],this.scrollEvents=[],this.focusEvents=[],this.blurEvents=[],this.pasteDetected=false;}};var N=class extends b{constructor(){super("fingerprint");this.fingerprintData={};this.suspicionFlags=[];}async init(){if(o.debug("Initializing FingerprintModule"),typeof window>"u")throw new Error("FingerprintModule requires browser environment");this.isInitialized=true,o.debug("FingerprintModule initialized");}onStart(){o.debug("Starting fingerprint collection"),this.collectFingerprints();}async collectFingerprints(){o.groupStart("Collecting fingerprints");try{await Promise.all([this.collectCanvasFingerprint(),this.collectWebGLFingerprint(),this.collectNavigatorInfo(),this.collectScreenInfo(),this.collectHardwareInfo(),this.detectHeadless()]),o.debug("Fingerprint collection complete");}catch(e){o.error("Error collecting fingerprints",e);}finally{o.groupEnd();}}async collectCanvasFingerprint(){try{let e=document.createElement("canvas");e.width=200,e.height=50;let t=e.getContext("2d");if(!t){this.suspicionFlags.push(E.CANVAS_BLOCKED);return}t.textBaseline="top",t.font='14px "Arial"',t.textBaseline="alphabetic",t.fillStyle="#f60",t.fillRect(125,1,62,20),t.fillStyle="#069",t.fillText("Vision",2,15),t.fillStyle="rgba(102, 204, 0, 0.7)",t.fillText("Vision",4,17);let n=e.toDataURL(),s=await V(n),r=this.checkCanvasNoise(t,e);this.fingerprintData.canvas={hash:s,consistent:r},r||(this.suspicionFlags.push(E.CANVAS_NOISE_MISSING),o.debug("Canvas noise missing (possible headless browser)")),o.debug("Canvas fingerprint collected",{hash:s.substring(0,16)});}catch(e){o.error("Failed to collect canvas fingerprint",e),this.suspicionFlags.push(E.CANVAS_BLOCKED);}}checkCanvasNoise(e,t){try{let s=e.getImageData(0,0,t.width,t.height).data,r=new Set;for(let a=0;a<s.length;a+=4){let l=`${s[a]},${s[a+1]},${s[a+2]}`;r.add(l);}return r.size>10}catch{return false}}async collectWebGLFingerprint(){if(!this.fingerprintData.webgl)try{let e=document.createElement("canvas");e.width=1,e.height=1;let t=e.getContext("webgl",{failIfMajorPerformanceCaveat:!0,powerPreference:"low-power"})||e.getContext("experimental-webgl");if(!t||!(t instanceof WebGLRenderingContext)){o.warn("WebGL not available");return}let n=t.getExtension("WEBGL_debug_renderer_info"),s="Unknown",r="Unknown";n?(s=t.getParameter(n.UNMASKED_VENDOR_WEBGL)||"Unknown",r=t.getParameter(n.UNMASKED_RENDERER_WEBGL)||"Unknown"):(s=t.getParameter(t.VENDOR)||"Unknown",r=t.getParameter(t.RENDERER)||"Unknown");let a=`${s}|${r}|${t.getParameter(t.VERSION)}`,l=await V(a);this.fingerprintData.webgl={vendor:s,renderer:r,hash:l},s.includes("Google")&&r.includes("SwiftShader")&&(this.suspicionFlags.push(E.WEBGL_INCONSISTENT),o.debug("SwiftShader detected (possible headless)"));let c=t.getExtension("WEBGL_lose_context");c&&c.loseContext(),e.width=0,e.height=0,o.debug("WebGL fingerprint collected",{vendor:s,renderer:r});}catch(e){o.error("Failed to collect WebGL fingerprint",e);}}async collectNavigatorInfo(){let e=window.navigator;this.fingerprintData.navigator={userAgent:e.userAgent,platform:e.platform,languages:[...e.languages||[]],plugins:e.plugins.length,mimeTypes:e.mimeTypes.length,webdriver:e.webdriver||false},e.webdriver&&(this.suspicionFlags.push(E.WEBDRIVER_PRESENT),o.debug("navigator.webdriver is true (automation detected)")),e.plugins.length===0&&e.mimeTypes.length===0&&(this.suspicionFlags.push(E.PLUGINS_EMPTY),o.debug("No plugins detected (possible headless)")),e.languages.length===0&&this.suspicionFlags.push(E.LANGUAGES_INCONSISTENT),o.debug("Navigator info collected",{platform:e.platform,languages:e.languages,webdriver:e.webdriver});}async collectScreenInfo(){this.fingerprintData.screen={width:window.screen.width,height:window.screen.height,colorDepth:window.screen.colorDepth,pixelRatio:window.devicePixelRatio},window.screen.colorDepth<24&&o.debug("Low color depth detected"),o.debug("Screen info collected",this.fingerprintData.screen);}async collectHardwareInfo(){let e=window.navigator;this.fingerprintData.hardware={deviceMemory:e.deviceMemory,hardwareConcurrency:e.hardwareConcurrency||0,maxTouchPoints:e.maxTouchPoints||0},o.debug("Hardware info collected",this.fingerprintData.hardware);}async detectHeadless(){let e=[];this.detectChromeHeadless()&&e.push(E.CHROME_HEADLESS),this.detectPhantomJS()&&e.push(E.PHANTOM_JS),this.detectSelenium()&&e.push(E.SELENIUM),this.detectAutomationFrameworks()&&e.push("automation_framework_detected");let t=e.length>0;this.fingerprintData.headlessDetection={isHeadless:t,indicators:e},t?(this.suspicionFlags.push(...e),o.warn("Headless browser detected",{indicators:e})):o.debug("No headless indicators found");}detectChromeHeadless(){let e=window;return !!(e.chrome&&!e.chrome.runtime||navigator.userAgent.includes("HeadlessChrome")||navigator.userAgent.includes("Chrome")&&!e.chrome)}detectPhantomJS(){let e=window;return !!(e.callPhantom||e._phantom||e.phantom)}detectSelenium(){let e=document,t=window;return !!(t.document.__selenium_unwrapped||t.document.__webdriver_evaluate||t.document.__driver_evaluate||e.$cdc_asdjflasutopfhvcZLmcfl_||e.$chrome_asyncScriptInfo||t.navigator.webdriver)}detectAutomationFrameworks(){let e=window;return !!(e.__nightmare||e._Selenium_IDE_Recorder||e.__webdriver_script_fn||e.domAutomation||e.domAutomationController)}async analyze(){o.debug("Analyzing fingerprint data");let e=0;return e+=this.suspicionFlags.length*.15,this.fingerprintData.headlessDetection?.isHeadless&&(e+=.5),this.fingerprintData.navigator?.webdriver&&(e+=.4),this.fingerprintData.navigator?.plugins===0&&this.fingerprintData.navigator?.mimeTypes===0&&(e+=.2),this.fingerprintData.canvas?.consistent||(e+=.15),e=Math.min(e,1),o.debug(`Fingerprint analysis complete: ${e.toFixed(3)}`),o.debug(`Suspicion flags: ${this.suspicionFlags.length}`,this.suspicionFlags),e}async getDetails(){let e=await this.analyze();return {canvas:this.fingerprintData.canvas||{hash:"unknown",consistent:false},webgl:this.fingerprintData.webgl||{vendor:"unknown",renderer:"unknown",hash:"unknown"},navigator:this.fingerprintData.navigator||{userAgent:navigator.userAgent,platform:navigator.platform,languages:[],plugins:0,mimeTypes:0,webdriver:false},screen:this.fingerprintData.screen||{width:0,height:0,colorDepth:0,pixelRatio:1},hardware:this.fingerprintData.hardware||{hardwareConcurrency:0,maxTouchPoints:0},headlessDetection:this.fingerprintData.headlessDetection||{isHeadless:false,indicators:[]},score:e}}onReset(){this.fingerprintData={},this.suspicionFlags=[];}};var z=class extends b{constructor(){super("network");this.timingData=[];this.connectionInfo={};this.suspicionFlags=[];}async init(){if(o.debug("Initializing NetworkModule"),typeof window>"u")throw new Error("NetworkModule requires browser environment");this.isInitialized=true,o.debug("NetworkModule initialized");}onStart(){o.debug("Starting network analysis"),this.collectNetworkInfo(),this.analyzeConnectionTiming();}collectNetworkInfo(){try{let e=navigator,t=e.connection||e.mozConnection||e.webkitConnection;t?(this.connectionInfo={type:t.type||"unknown",effectiveType:t.effectiveType||"unknown",downlink:t.downlink,rtt:t.rtt,saveData:t.saveData},o.debug("Connection info collected",this.connectionInfo),t.downlink&&t.downlink>T.SUSPICIOUS_DOWNLINK&&(this.suspicionFlags.push("high_bandwidth_datacenter"),o.debug("Suspiciously high bandwidth detected")),t.rtt&&t.rtt>T.SUSPICIOUS_RTT&&(this.suspicionFlags.push("high_rtt"),o.debug("High RTT detected (possible proxy/VPN)"))):o.debug("Network Information API not available");}catch(e){o.error("Failed to collect network info",e);}}analyzeConnectionTiming(){try{if(window.performance&&window.performance.timing){let e=window.performance.timing,t=e.domainLookupEnd-e.domainLookupStart,n=e.connectEnd-e.connectStart,s=e.responseStart-e.requestStart,r=e.responseEnd-e.responseStart;this.timingData=[t,n,s,r],o.debug("Timing data collected",{dns:t,tcp:n,request:s,response:r}),t===0&&n===0&&this.suspicionFlags.push("cached_or_local_connection");let a=M(this.timingData.filter(c=>c>0));y(this.timingData.filter(c=>c>0))>T.MAX_REQUEST_JITTER&&(this.suspicionFlags.push("high_timing_jitter"),o.debug("High timing jitter detected"));}if(window.performance&&window.performance.getEntriesByType){let e=window.performance.getEntriesByType("resource");this.analyzeResourceTiming(e);}}catch(e){o.error("Failed to analyze connection timing",e);}}analyzeResourceTiming(e){if(e.length===0)return;let t=e.map(n=>n.duration).filter(n=>n>0);if(t.length>0){let n=M(t),s=y(t);o.debug("Resource timing analyzed",{count:e.length,avgDuration:n.toFixed(2),variance:s.toFixed(2)}),s<10&&t.length>5&&this.suspicionFlags.push("consistent_resource_timing");}}detectProxy(){return false}detectTor(){let e=navigator.userAgent;return e.includes("Firefox")&&e.includes("Windows"),Intl.DateTimeFormat().resolvedOptions().timeZone==="UTC"&&this.suspicionFlags.push("utc_timezone"),false}async analyze(){o.debug("Analyzing network data");let e=0;return e+=this.suspicionFlags.length*.15,this.connectionInfo.rtt&&this.connectionInfo.rtt>T.SUSPICIOUS_RTT&&(e+=.2),this.connectionInfo.downlink&&this.connectionInfo.downlink>T.SUSPICIOUS_DOWNLINK&&(e+=.15),this.timingData.length>0&&y(this.timingData.filter(s=>s>0))>T.MAX_REQUEST_JITTER&&(e+=.1),e=Math.min(e,1),o.debug(`Network analysis complete: ${e.toFixed(3)}`),e}async getDetails(){let e=await this.analyze(),t=this.timingData.length>0?M(this.timingData.filter(s=>s>0)):0,n=this.timingData.length>0?y(this.timingData.filter(s=>s>0)):0;return {timing:{latency:t,jitter:n,pattern:this.timingData.length>0?"analyzed":"unknown"},connection:{type:this.connectionInfo.type||"unknown",effectiveType:this.connectionInfo.effectiveType||"unknown",downlink:this.connectionInfo.downlink,rtt:this.connectionInfo.rtt},proxy:{detected:this.detectProxy(),indicators:this.suspicionFlags.filter(s=>s.includes("proxy")||s.includes("vpn")||s.includes("datacenter"))},tor:{detected:this.detectTor()},score:e}}onReset(){this.timingData=[],this.connectionInfo={},this.suspicionFlags=[];}};var F=class extends b{constructor(){super("textAnalysis");this.textContent="";this.nlpAnalysis=null;this.aiDetectionResult=null;this.compromiseNlp=null;}async init(){o.debug("Initializing TextAnalysisModule");try{let e=await import('compromise');this.compromiseNlp=e.default,o.debug("NLP library loaded");}catch(e){o.warn("Failed to load NLP library (compromise). Text analysis will use fallback.",e);}this.isInitialized=true,o.debug("TextAnalysisModule initialized");}setText(e){this.textContent=e,o.debug(`Text set for analysis: ${e.length} characters`);}onStart(){o.debug("Starting text analysis"),this.textContent||o.warn("No text content set for analysis");}analyzeWithNLP(){if(!this.compromiseNlp||!this.textContent)return o.debug("Using fallback text analysis (compromise not available)"),this.analyzeFallback();o.debug("Performing NLP analysis");let e=this.compromiseNlp(this.textContent),t=e.terms().out("array"),n=new Set(t),s=t.length>0?n.size/t.length:0,a=(this.textContent.match(/[.,!?;:]/g)||[]).length/this.textContent.length,l=t.reduce((m,v)=>m+v.length,0),c=t.length>0?l/t.length:0,p=e.sentences().out("array"),h=p.length>0?t.length/p.length:0,g=H(h,5,30),d={lexicalRichness:s,punctuationRate:a,averageWordLength:c,sentenceComplexity:g,wordCount:t.length,sentenceCount:p.length};return o.debug("NLP analysis complete",d),d}analyzeFallback(){if(!this.textContent)return null;o.debug("Performing fallback text analysis");let e=this.textContent.split(/\s+/).filter(g=>g.length>0),t=this.textContent.split(/[.!?]+/).filter(g=>g.trim().length>0),n=new Set(e.map(g=>g.toLowerCase())),s=e.length>0?n.size/e.length:0,a=(this.textContent.match(/[.,!?;:]/g)||[]).length/this.textContent.length,l=e.reduce((g,d)=>g+d.length,0),c=e.length>0?l/e.length:0,p=t.length>0?e.length/t.length:0,h=H(p,5,30);return {lexicalRichness:s,punctuationRate:a,averageWordLength:c,sentenceComplexity:h,wordCount:e.length,sentenceCount:t.length}}async detectAIContent(){if(!this.textContent||this.textContent.length<x.MIN_TEXT_LENGTH)return o.debug("Text too short for AI detection"),{isAiGenerated:false,confidence:0,perplexity:0};o.debug("Analyzing for AI-generated content");let e=0,t=[];if(this.nlpAnalysis){let{lexicalRichness:c,punctuationRate:p,averageWordLength:h}=this.nlpAnalysis;c>.35&&c<.65&&(e+=.2,t.push("consistent_lexical_richness")),p>x.MIN_PUNCTUATION_RATE&&p<x.MAX_PUNCTUATION_RATE&&(e+=.15,t.push("optimal_punctuation")),h>4.5&&h<6.5&&(e+=.15,t.push("consistent_word_length"));}let n=[/\b(furthermore|moreover|additionally|consequently|therefore|thus|hence)\b/gi,/\b(it is important to note that|it should be noted that|as previously mentioned)\b/gi,/\b(in conclusion|to summarize|in summary)\b/gi,/\b(delve into|dive into|explore|comprehensive|multifaceted|nuanced)\b/gi],s=0;for(let c of n)c.test(this.textContent)&&s++;s>=3&&(e+=.3,t.push("ai_typical_phrases"),o.debug("AI-typical phrases detected"));let r=this.textContent.split(/[.!?]+/).filter(c=>c.trim());if(r.length>=3){let c=r.map(h=>h.trim().split(/\s+/).length),p=c.reduce((h,g)=>h+g,0)/c.length;p>12&&p<25&&c.reduce((g,d)=>g+Math.pow(d-p,2),0)/c.length<40&&(e+=.2,t.push("consistent_sentence_length"));}let a=this.calculateSimplePerplexity();a<x.AI_PERPLEXITY_THRESHOLD&&(e+=.25,t.push("low_perplexity")),e=Math.min(e,1);let l=e>=x.AI_CONFIDENCE_THRESHOLD;return o.debug("AI detection complete",{isAiGenerated:l,confidence:e,indicators:t.length}),{isAiGenerated:l,confidence:e,perplexity:a,indicators:t}}calculateSimplePerplexity(){if(!this.compromiseNlp||!this.textContent)return 100;let t=this.compromiseNlp(this.textContent).terms().out("array");if(t.length<10)return 100;let n=new Map,s=0;for(let l=0;l<t.length-1;l++){let c=`${t[l].toLowerCase()} ${t[l+1].toLowerCase()}`;n.set(c,(n.get(c)||0)+1),s++;}let r=0;for(let l of n.values()){let c=l/s;r-=c*Math.log2(c);}let a=Math.pow(2,r);return o.debug(`Calculated perplexity: ${a.toFixed(2)}`),a}analyzeStylometry(){if(!this.textContent||!this.compromiseNlp)return {features:{},similarity:0};let e=this.compromiseNlp(this.textContent),t={pronounRatio:this.calculateFeatureRatio(e.pronouns()),verbRatio:this.calculateFeatureRatio(e.verbs()),adjectiveRatio:this.calculateFeatureRatio(e.adjectives()),adverbRatio:this.calculateFeatureRatio(e.adverbs()),avgSentenceLength:this.nlpAnalysis?.sentenceComplexity||0,avgWordLength:this.nlpAnalysis?.averageWordLength||0,lexicalDensity:this.nlpAnalysis?.lexicalRichness||0,punctuationDensity:this.nlpAnalysis?.punctuationRate||0};return o.debug("Stylometry features extracted",t),{features:t,similarity:0}}calculateFeatureRatio(e){if(!this.compromiseNlp||!this.textContent)return 0;let n=this.compromiseNlp(this.textContent).terms().out("array").length,s=e.out("array").length;return n>0?s/n:0}async analyze(){if(!this.textContent||this.textContent.length<x.MIN_TEXT_LENGTH)return o.debug("Text too short for analysis"),0;o.debug("Analyzing text content"),this.nlpAnalysis=this.analyzeWithNLP(),this.aiDetectionResult=await this.detectAIContent();let e=this.analyzeStylometry(),t=0;return this.aiDetectionResult.isAiGenerated&&(t=this.aiDetectionResult.confidence),e.similarity>.7&&(t=Math.max(t,.8)),o.debug(`Text analysis complete: ${t.toFixed(3)}`),t}async getDetails(){!this.nlpAnalysis&&this.textContent&&await this.analyze();let e=this.analyzeStylometry();return {text:this.textContent,nlp:{lexicalRichness:this.nlpAnalysis?.lexicalRichness||0,punctuationRate:this.nlpAnalysis?.punctuationRate||0,averageWordLength:this.nlpAnalysis?.averageWordLength||0,sentenceComplexity:this.nlpAnalysis?.sentenceComplexity||0},aiDetection:{perplexity:this.aiDetectionResult?.perplexity||0,transformerScore:0,embeddingDistance:0,isAiGenerated:this.aiDetectionResult?.isAiGenerated||false,confidence:this.aiDetectionResult?.confidence||0},stylometry:{features:e.features,similarity:e.similarity},score:await this.analyze()}}onReset(){this.textContent="",this.nlpAnalysis=null,this.aiDetectionResult=null;}getText(){return this.textContent}};var B=class extends b{constructor(){super("entropy");this.mousePoints=[];this.keyEvents=[];this.clickEvents=[];this.scrollDeltas=[];this.handleMouseMove=e=>{this.mousePoints.length>200&&this.mousePoints.shift(),this.mousePoints.push({x:e.clientX,y:e.clientY,t:Date.now()});};this.handleKeyDown=e=>{this.keyEvents.length>50&&this.keyEvents.shift(),this.keyEvents.push({key:e.key,t:Date.now()});};this.handleClick=e=>{let t=e.target;if(!t)return;let n=t.getBoundingClientRect(),s=this.mousePoints[this.mousePoints.length-1],r=s?Date.now()-s.t:0;this.clickEvents.length>20&&this.clickEvents.shift(),this.clickEvents.push({x:e.clientX,y:e.clientY,t:Date.now(),targetRect:n,reactionTime:r});};this.handleWheel=e=>{this.scrollDeltas.length>30&&this.scrollDeltas.shift(),this.scrollDeltas.push(e.deltaY);};}async init(){await this.onInit(),this.isInitialized=true;}async onInit(){o.debug("Initializing Entropy Detection"),this.setupListeners();}onStart(){o.debug("Entropy detection started");}onStop(){this.cleanup();}setupListeners(){typeof document>"u"||(document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("keydown",this.handleKeyDown),document.addEventListener("click",this.handleClick),document.addEventListener("wheel",this.handleWheel));}cleanup(){typeof document>"u"||(document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("click",this.handleClick),document.removeEventListener("wheel",this.handleWheel));}async analyze(){let e=0,t={mouse:.3,keyboard:.2,click:.35,scroll:.15};return this.mousePoints.length>=20&&(e+=this.analyzeMouseEntropy()*t.mouse),this.keyEvents.length>=5&&(e+=this.analyzeKeyboardEntropy()*t.keyboard),this.clickEvents.length>=3&&(e+=this.analyzeClickPrecision()*t.click),this.scrollDeltas.length>=5&&(e+=this.analyzeScrollEntropy()*t.scroll),e}analyzeMouseEntropy(){if(this.mousePoints.length<10)return 0;let e=0;for(let d=2;d<this.mousePoints.length;d++){let m=Math.atan2(this.mousePoints[d-1].y-this.mousePoints[d-2].y,this.mousePoints[d-1].x-this.mousePoints[d-2].x),v=Math.atan2(this.mousePoints[d].y-this.mousePoints[d-1].y,this.mousePoints[d].x-this.mousePoints[d-1].x),f=Math.abs(v-m);f>.35&&e++;}let n=[];for(let d=1;d<this.mousePoints.length;d++){let m=this.mousePoints[d].x-this.mousePoints[d-1].x,v=this.mousePoints[d].y-this.mousePoints[d-1].y,f=this.mousePoints[d].t-this.mousePoints[d-1].t;f>0&&n.push(Math.sqrt(m*m+v*v)/f);}let s=n.reduce((d,m)=>d+m,0)/n.length,r=n.reduce((d,m)=>d+Math.pow(m-s,2),0)/n.length,a=Math.sqrt(r)/s,l=0;for(let d=1;d<this.mousePoints.length;d++){let m=this.mousePoints[d].t-this.mousePoints[d-1].t;m>100&&m<500&&l++;}let c=Math.min(e/8,1),p=Math.min(a*2,1),h=Math.min(l/5,1),g=(c+p+h)/3;return g<.3?.8:g<.5?.4:.1}analyzeKeyboardEntropy(){if(this.keyEvents.length<5)return 0;let e=[];for(let r=1;r<this.keyEvents.length;r++)e.push(this.keyEvents[r].t-this.keyEvents[r-1].t);let t=e.reduce((r,a)=>r+a,0)/e.length,n=e.reduce((r,a)=>r+Math.pow(a-t,2),0)/e.length,s=Math.sqrt(n)/t;return s<.15?.9:s<.25?.6:s>.6?.05:.3}analyzeClickPrecision(){if(this.clickEvents.length===0)return 0;let e=0,t=0,n=0;for(let c of this.clickEvents){let p=c.targetRect.left+c.targetRect.width/2,h=c.targetRect.top+c.targetRect.height/2,g=c.x-p,d=c.y-h,v=Math.sqrt(g*g+d*d)/(c.targetRect.width/2);e+=v,v<.12&&t++,c.reactionTime<150&&c.reactionTime>0&&n++;}let s=e/this.clickEvents.length,r=t/this.clickEvents.length,a=n/this.clickEvents.length,l=0;return s<.18&&(l+=.5),r>.4&&(l+=.3),a>.3&&(l+=.2),Math.min(l,1)}analyzeScrollEntropy(){if(this.scrollDeltas.length<5)return 0;let e=this.scrollDeltas.map(r=>Math.abs(r)),t=e.reduce((r,a)=>r+a,0)/e.length,n=e.reduce((r,a)=>r+Math.pow(a-t,2),0)/e.length,s=Math.sqrt(n)/t;return s<.2?.7:s<.4?.3:.1}async getDetails(){return {mousePoints:this.mousePoints.length,keyEvents:this.keyEvents.length,clickEvents:this.clickEvents.length,scrollDeltas:this.scrollDeltas.length}}};var q=class extends b{constructor(){super("temporal-correlation");this.requestTimings=[];this.interactionTimestamps=[];this.loadTimings=[];}async init(){await this.onInit(),this.isInitialized=true;}async onInit(){o.debug("Initializing Temporal Correlation Analysis"),this.startTracking();}onStart(){o.debug("Temporal correlation tracking started");}onStop(){this.requestTimings=[],this.interactionTimestamps=[];}startTracking(){if(typeof window>"u")return;let e=window.fetch;if(window.fetch=async(...t)=>{let n=performance.now(),s=await e(...t),r=performance.now()-n;return this.requestTimings.push({timestamp:Date.now(),duration:r,type:"fetch"}),this.requestTimings.length>50&&this.requestTimings.shift(),s},["click","keydown","scroll"].forEach(t=>{document.addEventListener(t,()=>{this.interactionTimestamps.push(Date.now()),this.interactionTimestamps.length>100&&this.interactionTimestamps.shift();});}),performance.timing){let t=performance.timing.loadEventEnd-performance.timing.navigationStart;t>0&&this.loadTimings.push(t);}}async analyze(){let e=0;return this.requestTimings.length>=5&&(e+=this.analyzeRequestPeriodicity()*.4),this.interactionTimestamps.length>=10&&(e+=this.analyzeInteractionRhythm()*.3),this.requestTimings.length>=3&&this.interactionTimestamps.length>=5&&(e+=this.analyzeLoadTimeCorrelation()*.3),e}analyzeRequestPeriodicity(){if(this.requestTimings.length<5)return 0;let e=[];for(let h=1;h<this.requestTimings.length;h++)e.push(this.requestTimings[h].timestamp-this.requestTimings[h-1].timestamp);let t=e.reduce((h,g)=>h+g,0)/e.length,n=e.reduce((h,g)=>h+Math.pow(g-t,2),0)/e.length,s=Math.sqrt(n)/t,r=0;s<.1?r+=.8:s<.2?r+=.5:s<.3&&(r+=.2);let a=this.requestTimings.map(h=>h.duration),l=a.reduce((h,g)=>h+g,0)/a.length,c=a.reduce((h,g)=>h+Math.pow(g-l,2),0)/a.length;return Math.sqrt(c)/l<.15&&(r+=.2),Math.min(r,1)}analyzeInteractionRhythm(){if(this.interactionTimestamps.length<10)return 0;let e=[];for(let l=1;l<this.interactionTimestamps.length;l++)e.push(this.interactionTimestamps[l]-this.interactionTimestamps[l-1]);let t=e.reduce((l,c)=>l+c,0)/e.length,n=e.reduce((l,c)=>l+Math.pow(c-t,2),0)/e.length,s=Math.sqrt(n)/t,r=0;return s<.15?r=.9:s<.25?r=.6:s<.4?r=.3:r=.05,this.detectSequencePatterns(e)>.7&&(r=Math.max(r,.8)),r}detectSequencePatterns(e){if(e.length<10)return 0;let t=0,n=3;for(let s=0;s<e.length-n*2;s++){let r=e.slice(s,s+n),a=e.slice(s+n,s+n*2),l=0;for(let c=0;c<n;c++)Math.abs(r[c]-a[c])<50&&l++;l===n&&t++;}return Math.min(t/5,1)}analyzeLoadTimeCorrelation(){if(this.requestTimings.length===0||this.interactionTimestamps.length===0)return 0;let e=0;for(let n of this.requestTimings)this.interactionTimestamps.filter(r=>Math.abs(r-n.timestamp)<200).length===0&&e++;let t=e/this.requestTimings.length;return t>.7?.8:t>.5?.5:.2}async getDetails(){return {requestCount:this.requestTimings.length,interactionCount:this.interactionTimestamps.length,avgRequestInterval:this.requestTimings.length>1?(this.requestTimings[this.requestTimings.length-1].timestamp-this.requestTimings[0].timestamp)/this.requestTimings.length:0}}};var $=class extends b{constructor(){super("perplexity");this.textSamples=[];}async init(){await this.onInit(),this.isInitialized=true;}async onInit(){o.debug("Initializing Perplexity Analysis");}onStart(){o.debug("Perplexity analysis started");}onStop(){this.textSamples=[];}addTextSample(e){e&&e.length>10&&(this.textSamples.push(e),this.textSamples.length>20&&this.textSamples.shift());}async analyze(){if(this.textSamples.length===0)return 0;let e=this.textSamples[this.textSamples.length-1],t=this.calculatePerplexity(e),n=this.calculateBurstiness(e),s=this.analyzeSyntacticBalance(e),r=this.detectRepetitivePatterns(e);return t*.35+n*.3+s*.2+r*.15}calculatePerplexity(e){let t=e.toLowerCase().split(/\s+/).filter(f=>f.length>0);if(t.length<5)return 0;let n=new Map,s=new Map;for(let f=0;f<t.length-1;f++){let k=`${t[f]} ${t[f+1]}`;n.set(k,(n.get(k)||0)+1),s.set(t[f],(s.get(t[f])||0)+1);}let r=n.size,a=t.length-1,l=r/a,c=s.size,p=t.length,h=c/p,g=t.reduce((f,k)=>f+k.length,0)/t.length,d=t.reduce((f,k)=>f+Math.pow(k.length-g,2),0)/t.length,m=Math.sqrt(d),v=0;return l<.7&&(v+=.3),h<.5&&(v+=.3),m<2&&(v+=.2),(g<4||g>7)&&(v+=.2),Math.min(v,1)}calculateBurstiness(e){let t=e.split(/[.!?]+/).filter(c=>c.trim().length>0);if(t.length<3)return 0;let n=t.map(c=>c.trim().split(/\s+/).length),s=n.reduce((c,p)=>c+p,0)/n.length,r=n.reduce((c,p)=>c+Math.pow(p-s,2),0)/n.length,a=Math.sqrt(r)/s,l=0;return a<.3?l=.8:a<.5?l=.5:a>1?l=.3:l=.1,l}analyzeSyntacticBalance(e){let t=["the","a","an","and","or","but","in","on","at","to","for","of","with"],n=e.toLowerCase().split(/\s+/);if(n.length<10)return 0;let r=n.filter(d=>t.includes(d)).length/n.length,l=(e.match(/[,;:]/g)||[]).length/n.length,p=e.split(/\s+/).filter(d=>/^[A-Z]/.test(d)).length/n.length,h=0;(r<.15||r>.4)&&(h+=.3),l<.02&&(h+=.3),(p>.3||p<.05)&&(h+=.2);let g=n.length/(e.split(/[.!?]+/).length||1);return (g<8||g>25)&&(h+=.2),Math.min(h,1)}detectRepetitivePatterns(e){let t=e.toLowerCase().split(/\s+/);if(t.length<10)return 0;let n=3,s=new Map;for(let l=0;l<=t.length-n;l++){let c=t.slice(l,l+n).join(" ");s.set(c,(s.get(c)||0)+1);}let r=0;for(let l of s.values())l>1&&(r+=l-1);let a=r/(t.length-n+1);return a>.15?.8:a>.08?.5:a>.04?.2:0}async getDetails(){return {samplesCount:this.textSamples.length,totalCharacters:this.textSamples.reduce((e,t)=>e+t.length,0)}}};var D=class{constructor(i){this.modules=new Map;this.isInitialized=false;this.isRunning=false;o.info("Initializing Vision Core",{mode:i.mode}),this.securityMode=i.securityMode||"adaptive",this.progressiveScorer=new W(this.securityMode),this.sessionId=Q(),this.config={elementId:i.elementId||"vision",mode:i.mode,onResult:i.onResult||(()=>{}),thresholds:{...X,...i.thresholds},modules:{...Y,...i.modules},apiEndpoint:i.apiEndpoint||"",debug:i.debug||false,challenges:{...j,...i.challenges}},o.setDebug(this.config.debug),this.sessionManager=new L(this.sessionId),this.scoringEngine=new _(this.config.thresholds),o.info("VisionCore initialized",{sessionId:this.sessionId});}async init(){if(this.isInitialized){o.warn("Vision already initialized");return}o.groupStart("Initializing Vision");let i=performance.now();try{await this.sessionManager.init(),await this.initializeModules(),await this.scoringEngine.init(),this.isInitialized=!0;let e=performance.now()-i;o.performance("Vision initialization",e),o.info("Vision initialized successfully");}catch(e){throw o.error("Failed to initialize Vision",e),e}finally{o.groupEnd();}}async initializeModules(){o.info("Initializing detection modules");let i=this.config.modules,e=[];if(i.behavioral){o.debug("Initializing Behavioral module");let r=new P;e.push(r.init().then(()=>{this.modules.set("behavioral",r),o.debug("Behavioral module initialized");}));}if(i.fingerprint){o.debug("Initializing Fingerprint module");let r=new N;e.push(r.init().then(()=>{this.modules.set("fingerprint",r),o.debug("Fingerprint module initialized");}));}if(i.textAnalysis){o.debug("Initializing Text Analysis module");let r=new F;e.push(r.init().then(()=>{this.modules.set("textAnalysis",r),o.debug("Text Analysis module initialized");}));}if(i.network){o.debug("Initializing Network module");let r=new z;e.push(r.init().then(()=>{this.modules.set("network",r),o.debug("Network module initialized");}));}o.debug("Initializing Entropy module");let t=new B;e.push(t.init().then(()=>{this.modules.set("entropy",t),o.debug("Entropy module initialized");})),o.debug("Initializing Temporal Correlation module");let n=new q;e.push(n.init().then(()=>{this.modules.set("temporal",n),o.debug("Temporal Correlation module initialized");})),o.debug("Initializing Perplexity module");let s=new $;e.push(s.init().then(()=>{this.modules.set("perplexity",s),o.debug("Perplexity module initialized");})),await Promise.all(e),o.info(`Initialized ${this.modules.size} modules`);}async start(){if(!this.isInitialized)throw new Error("Vision not initialized. Call init() first.");if(this.isRunning){o.warn("Vision already running");return}o.info("Starting Vision detection");for(let[i,e]of this.modules)try{e.start(),o.debug(`Started module: ${i}`);}catch(t){o.error(`Failed to start module: ${i}`,t);}this.isRunning=true,o.info("Vision detection started");}stop(){if(this.isRunning){o.info("Stopping Vision detection");for(let[i,e]of this.modules)try{e.stop(),o.debug(`Stopped module: ${i}`);}catch(t){o.error(`Failed to stop module: ${i}`,t);}this.isRunning=false,o.info("Vision detection stopped");}}async analyze(){if(!this.isRunning)throw new Error("Vision not running. Call start() first.");o.info("Starting analysis",{sessionId:this.sessionId,mode:this.securityMode});let e=performance.now();try{let t=await this.collectModuleScores(),n=this.scoringEngine.calculateCombinedScore(t),s=this.scoringEngine.calculateConfidence(t),r=this.determineAction(n,s),a=this.determineRiskLevel(n),l=this.config.debug?{...await this.collectDetailedInfo(),confidence:s}:{confidence:s},c={score:n,action:r,riskLevel:a,signals:t,details:l,sessionId:this.sessionId,timestamp:Date.now()};if(o.info("Analysis complete",{score:c.score,action:c.action,riskLevel:c.riskLevel,confidence:s}),this.sessionManager.updateResult(c),this.config.onResult)try{this.config.onResult(c);}catch(h){o.error("Error in onResult callback",h);}let p=performance.now()-e;return o.performance("Signal analysis",p),c}catch(t){throw o.error("Analysis failed",t),t}finally{o.groupEnd();}}async collectModuleScores(){let i={behavioral:0,fingerprint:0,textAnalysis:0,network:0,combined:0},e=[];for(let[t,n]of this.modules)e.push(n.analyze().then(s=>{t==="behavioral"?i.behavioral=s:t==="fingerprint"?i.fingerprint=s:t==="textAnalysis"?i.textAnalysis=s:t==="network"&&(i.network=s),o.debug(`Module score: ${t} = ${s.toFixed(3)}`);}));return await Promise.all(e),i}determineAction(i,e){let{accept:t,block:n}=this.config.thresholds,{acceptMargin:s,blockMargin:r,confThreshold:a}=this.getDecisionTuning();return i<t+s&&e>=a?"accept":i>=n-r&&e>=a?"block":i<t?"accept":i>=n?"block":"challenge"}getDecisionTuning(){switch(this.securityMode){case "lite":return {acceptMargin:.1,blockMargin:.04,confThreshold:.55};case "strict":return {acceptMargin:.02,blockMargin:.015,confThreshold:.75};case "enterprise":return {acceptMargin:.04,blockMargin:.03,confThreshold:.7};case "adaptive":default:return {acceptMargin:.06,blockMargin:.03,confThreshold:.65}}}determineRiskLevel(i){return i<.3?"low":i<.6?"medium":i<.85?"high":"critical"}async collectDetailedInfo(){let i={flags:[],confidence:0};for(let[e,t]of this.modules)try{let n=await t.getDetails();i[e]=n,n.flags&&i.flags.push(...n.flags);}catch(n){o.warn(`Failed to get details from module $