@botsigged/sdk 1.0.7 → 1.0.9

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/botsigged.js CHANGED
@@ -1,46 +1,7 @@
1
- (()=>{var{defineProperty:h,getOwnPropertyNames:VA,getOwnPropertyDescriptor:DA}=Object,HA=Object.prototype.hasOwnProperty;var BA=new WeakMap,$A=(A)=>{var B=BA.get(A),Q;if(B)return B;if(B=h({},"__esModule",{value:!0}),A&&typeof A==="object"||typeof A==="function")VA(A).map((E)=>!HA.call(B,E)&&h(B,E,{get:()=>A[E],enumerable:!(Q=DA(A,E))||Q.enumerable}));return BA.set(A,B),B};var v=(A,B)=>{for(var Q in B)h(A,Q,{get:B[Q],enumerable:!0,configurable:!0,set:(E)=>B[Q]=()=>E})};var g=(A,B)=>()=>(A&&(B=A(A=0)),B);var CA="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";function NA(A){let B=atob(A),Q=new Uint8Array(B.length);for(let E=0;E<B.length;E++)Q[E]=B.charCodeAt(E);return Q}async function c(){if(j)return j;return j=(async()=>{try{let A=NA(CA),B=await WebAssembly.compile(A);return l=(await WebAssembly.instantiate(B,{env:{abort:(E,I,C,Y)=>{}}})).exports,LA(l)}catch(A){throw j=null,A}})(),j}function a(){return l!==null}function LA(A){function B(I){let C=A.__new(I.length,1);return new Uint8Array(A.memory.buffer,C,I.length).set(I),C}function Q(I){let C=new Uint16Array(I.length);for(let Z=0;Z<I.length;Z++)C[Z]=I.charCodeAt(Z);let Y=A.__new(C.length*2,2);return new Uint16Array(A.memory.buffer,Y,C.length).set(C),Y}function E(I,C=1024){let Y=new Uint8Array(A.memory.buffer),G=Y.length;if(I<0||I>=G)return"";let Z=I,W=Math.min(I+C,G);while(Z<W&&Y[Z]!==0)Z++;let X=Y.slice(I,Z);return new TextDecoder().decode(X)}return{xxHash32(I,C=0){let Y=B(I);try{return A.xxHash32(Y,C)}finally{A.__unpin(Y)}},hashString(I,C=0){let Y=Q(I);try{return A.hashString(Y,C)}finally{A.__unpin(Y)}},hashStringToHex(I,C=0){let Y=Q(I);try{let G=A.hashStringToHex(Y,C);return E(G)}finally{A.__unpin(Y)}},verifyHash(I,C,Y=0){let G=B(I);try{return A.verifyHash(G,C,Y)}finally{A.__unpin(G)}},verifyStringHash(I,C,Y=0){let G=Q(I);try{return A.verifyStringHash(G,C,Y)}finally{A.__unpin(G)}}}}function P(){let A=new TextEncoder;function B(E,I=0){let X=(N,H)=>(N<<H|N>>>32-H)>>>0,L=(N,H)=>(N[H]|N[H+1]<<8|N[H+2]<<16|N[H+3]<<24)>>>0,D=E.length,z,q=0;if(D>=16){let N=D-16,H=I+2654435761+2246822519>>>0,T=I+2246822519>>>0,S=I>>>0,x=I-2654435761>>>0;while(q<=N)H=Math.imul(X(H+Math.imul(L(E,q),2246822519)>>>0,13),2654435761)>>>0,q+=4,T=Math.imul(X(T+Math.imul(L(E,q),2246822519)>>>0,13),2654435761)>>>0,q+=4,S=Math.imul(X(S+Math.imul(L(E,q),2246822519)>>>0,13),2654435761)>>>0,q+=4,x=Math.imul(X(x+Math.imul(L(E,q),2246822519)>>>0,13),2654435761)>>>0,q+=4;z=X(H,1)+X(T,7)+X(S,12)+X(x,18)>>>0}else z=I+374761393>>>0;z=z+D>>>0;while(q<=D-4)z=Math.imul(X(z+Math.imul(L(E,q),3266489917)>>>0,17),668265263)>>>0,q+=4;while(q<D)z=Math.imul(X(z+Math.imul(E[q],374761393)>>>0,11),2654435761)>>>0,q++;return z^=z>>>15,z=Math.imul(z,2246822519)>>>0,z^=z>>>13,z=Math.imul(z,3266489917)>>>0,z^=z>>>16,z>>>0}function Q(E){return(E>>>0).toString(16).padStart(8,"0")}return{xxHash32:B,hashString(E,I=0){return B(A.encode(E),I)},hashStringToHex(E,I=0){return Q(B(A.encode(E),I))},verifyHash(E,I,C=0){return B(E,C)===I},verifyStringHash(E,I,C=0){return B(A.encode(E),C)===I}}}var l=null,j=null;var YA=()=>{};var JA={};v(JA,{verifySignature:()=>FA,verify:()=>OA,loadHashModule:()=>c,isUsingWasm:()=>wA,isHashModuleLoaded:()=>a,initHashModule:()=>kA,hashToHex:()=>i,hash:()=>UA,getHash:()=>U,createSignature:()=>GA,createFallbackHashModule:()=>P});async function kA(A={}){let{preferWasm:B=!0,onWasmLoaded:Q,onFallback:E}=A;if($)return $;if(M)return M;return M=(async()=>{if(B)try{return $=await c(),y=!0,Q?.(),$}catch(I){let C=I instanceof Error?I.message:"Unknown error";E?.(C)}else E?.("WASM disabled by configuration");return $=P(),y=!1,$})(),M}function U(){if($)return $;return $=P(),y=!1,$}function wA(){return y&&a()}function UA(A,B=0){let Q=U();if(typeof A==="string")return Q.hashString(A,B);return Q.xxHash32(A,B)}function i(A,B=0){let Q=U();if(typeof A==="string")return Q.hashStringToHex(A,B);return Q.xxHash32(A,B).toString(16).padStart(8,"0")}function OA(A,B,Q=0){let E=U(),I=typeof B==="string"?parseInt(B,16):B;if(typeof A==="string")return E.verifyStringHash(A,I,Q);return E.verifyHash(A,I,Q)}function GA(A,B){let Q=U(),E=Q.hashString(B,0);return Q.hashString(A,E).toString(16).padStart(8,"0")}function FA(A,B,Q){return GA(A,Q)===B}var $=null,M=null,y=!0;var b=g(()=>{YA()});class AA{overlay=null;messageEl=null;progressEl=null;config;constructor(A){this.config=A}show(){if(!this.config.enabled||this.overlay)return;this.overlay=document.createElement("div"),this.overlay.id="botsigged-challenge-overlay",this.overlay.style.cssText=`
2
- position: fixed;
3
- top: 0;
4
- left: 0;
5
- width: 100%;
6
- height: 100%;
7
- background: ${this.config.backgroundColor};
8
- display: flex;
9
- flex-direction: column;
10
- align-items: center;
11
- justify-content: center;
12
- z-index: ${this.config.zIndex};
13
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
14
- `;let A=document.createElement("div");A.style.cssText=`
15
- width: 48px;
16
- height: 48px;
17
- border: 4px solid ${this.config.textColor}33;
18
- border-top-color: ${this.config.spinnerColor};
19
- border-radius: 50%;
20
- animation: botsigged-spin 1s linear infinite;
21
- margin-bottom: 20px;
22
- `,this.messageEl=document.createElement("span"),this.messageEl.textContent=this.config.message,this.messageEl.style.cssText=`
23
- color: ${this.config.textColor};
24
- font-size: 18px;
25
- font-weight: 500;
26
- margin-bottom: 12px;
27
- `;let B=document.createElement("div");B.style.cssText=`
28
- width: 200px;
29
- height: 4px;
30
- background: ${this.config.textColor}33;
31
- border-radius: 2px;
32
- overflow: hidden;
33
- `,this.progressEl=document.createElement("div"),this.progressEl.style.cssText=`
34
- width: 0%;
35
- height: 100%;
36
- background: ${this.config.spinnerColor};
37
- border-radius: 2px;
38
- transition: width 0.1s ease-out;
39
- `,B.appendChild(this.progressEl);let Q=document.createElement("style");Q.textContent=`
40
- @keyframes botsigged-spin {
41
- to { transform: rotate(360deg); }
42
- }
43
- `,document.head.appendChild(Q),this.overlay.appendChild(A),this.overlay.appendChild(this.messageEl),this.overlay.appendChild(B),document.body.appendChild(this.overlay)}setProgress(A){if(this.progressEl){let B=Math.min(100,Math.max(0,A*100));this.progressEl.style.width=`${B}%`}}showSuccess(){if(this.messageEl)this.messageEl.textContent=this.config.successMessage;if(this.progressEl)this.progressEl.style.width="100%"}hide(){if(this.overlay)this.overlay.remove(),this.overlay=null,this.messageEl=null,this.progressEl=null}isVisible(){return this.overlay!==null}}var WA={};v(WA,{ChallengeManager:()=>KA});function _A(){let A=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(A);else for(let B=0;B<16;B++)A[B]=Math.floor(Math.random()*256);return A}function PA(A){if(A===0)return 32;let B=0;if((A&4294901760)===0)B+=16,A<<=16;if((A&4278190080)===0)B+=8,A<<=8;if((A&4026531840)===0)B+=4,A<<=4;if((A&3221225472)===0)B+=2,A<<=2;if((A&2147483648)===0)B+=1;return B}function MA(A,B,Q,E){let I=U(),C=new Uint8Array(A.length+4);C.set(A);let Y=E,G=0;while(G<Q){C[A.length]=Y&255,C[A.length+1]=Y>>>8&255,C[A.length+2]=Y>>>16&255,C[A.length+3]=Y>>>24&255;let Z=I.xxHash32(C,0);if(G++,PA(Z)>=B)return{nonce:Y,found:!0,iterations:G};Y=Y+1>>>0}return{nonce:Y,found:!1,iterations:G}}class KA{config;overlay;solving=!1;solved=!1;pendingForms=new Map;formHandler=null;formObserver=null;resubmitting=!1;debug;constructor(A,B=!1){this.config=A,this.debug=B,this.overlay=new AA(A.ui)}getDifficultyForLevel(A){let B=this.config.difficulty;switch(A){case"critical":return B.critical;case"high":return B.high;case"medium":return B.medium;default:return 0}}shouldChallenge(A){if(!this.config.enabled||this.solved)return!1;let B=["low","medium","high","critical"],Q=B.indexOf(A),E=B.indexOf(this.config.minLevel);return Q>=E}blockFormsUntilSolved(A){if(this.formHandler)return;this.formHandler=(B)=>{if(this.solved||this.resubmitting)return;B.preventDefault(),B.stopPropagation();let Q=B.target;if(!this.pendingForms.has(Q))this.pendingForms.set(Q,B);if(!this.solving)this.startChallenge(A)},document.querySelectorAll("form").forEach((B)=>{B.addEventListener("submit",this.formHandler,!0)}),this.formObserver=new MutationObserver((B)=>{B.forEach((Q)=>{Q.addedNodes.forEach((E)=>{if(E instanceof HTMLFormElement&&this.formHandler)E.addEventListener("submit",this.formHandler,!0);if(E instanceof HTMLElement&&this.formHandler)E.querySelectorAll("form").forEach((I)=>{I.addEventListener("submit",this.formHandler,!0)})})})}),this.formObserver.observe(document.body,{childList:!0,subtree:!0}),this.log("Forms blocked, challenge required")}async startChallenge(A){if(this.solving||this.solved)return;this.solving=!0;let B=this.getDifficultyForLevel(A),Q=_A(),E=performance.now();this.log(`Starting challenge: difficulty=${B}, level=${A}`),this.config.onChallengeStart?.(A,B),this.overlay.show();let I=1<<B,C=0,Y=0,G;do{await new Promise((L)=>setTimeout(L,0)),G=MA(Q,B,this.config.chunkSize,C),Y+=G.iterations,C=G.nonce+1;let X=Math.min(1,Y/I);this.overlay.setProgress(X),this.config.onChallengeProgress?.(X,Y)}while(!G.found);let Z=performance.now()-E;this.log(`Challenge solved: nonce=${G.nonce}, iterations=${Y}, time=${Z.toFixed(0)}ms`),this.overlay.showSuccess(),await new Promise((X)=>setTimeout(X,500)),this.overlay.hide(),this.solved=!0,this.solving=!1;let W={solveTimeMs:Z,iterations:Y,difficulty:B,level:A,nonce:G.nonce};this.config.onChallengeComplete?.(W),this.unblockForms()}unblockForms(){if(this.formObserver)this.formObserver.disconnect(),this.formObserver=null;if(this.formHandler)document.querySelectorAll("form").forEach((A)=>{A.removeEventListener("submit",this.formHandler,!0)}),this.formHandler=null;this.log("Forms unblocked"),this.resubmitting=!0,this.pendingForms.forEach((A,B)=>{if(this.log("Resubmitting pending form"),B.requestSubmit)B.requestSubmit();else B.submit()}),this.pendingForms.clear(),this.resubmitting=!1}isSolving(){return this.solving}isSolved(){return this.solved}reset(){if(this.formObserver)this.formObserver.disconnect(),this.formObserver=null;if(this.formHandler)document.querySelectorAll("form").forEach((A)=>{A.removeEventListener("submit",this.formHandler,!0)}),this.formHandler=null;this.solved=!1,this.solving=!1,this.resubmitting=!1,this.pendingForms.clear()}log(...A){if(this.debug);}}var qA=g(()=>{b()});var yA={};v(yA,{BotSigged:()=>K});function QA(A){return typeof A==="object"&&A!==null&&"code"in A&&A.code==="LIMIT_EXCEEDED"}var R={endpoint:"wss://botsigged.com/sdk/websocket",debug:!1,sendInterval:2000,maxBufferSize:1000,mouseSampleRate:0.5,autoStart:!0,actionThreshold:70,action:"none",minAlertLevel:"high",botScoreThresholds:{medium:40,high:70,critical:90},hashVerification:{enabled:!1,preferWasm:!0},challenge:{enabled:!1,minLevel:"high",chunkSize:1e4,difficulty:{medium:12,high:16,critical:20},ui:{enabled:!0,message:"Verifying you're human...",successMessage:"Verified!",backgroundColor:"rgba(0, 0, 0, 0.7)",textColor:"#ffffff",spinnerColor:"#3b82f6",zIndex:999999}},formProtection:{mode:"auto",minTimeBeforeSubmit:500,maxHoldTime:3000,showLoadingUI:!0,loadingMessage:"Please wait..."},fallbackMode:"degraded"},EA={action:"none",form_protection_mode:"none"};function IA(A){let B=A.action??R.action,Q=B==="challenge"||A.challenge?.enabled;return{apiKey:A.apiKey,accountId:A.accountId,endpoint:A.endpoint??R.endpoint,debug:A.debug??R.debug,sendInterval:A.sendInterval??R.sendInterval,maxBufferSize:A.maxBufferSize??R.maxBufferSize,mouseSampleRate:A.mouseSampleRate??R.mouseSampleRate,autoStart:A.autoStart??R.autoStart,actionThreshold:A.actionThreshold??R.actionThreshold,action:B,minAlertLevel:A.minAlertLevel??R.minAlertLevel,botScoreThresholds:{...R.botScoreThresholds,...A.botScoreThresholds},hashVerification:{...R.hashVerification,...A.hashVerification},challenge:{enabled:Q,minLevel:A.challenge?.minLevel??R.challenge.minLevel,chunkSize:A.challenge?.chunkSize??R.challenge.chunkSize,difficulty:{...R.challenge.difficulty,...A.challenge?.difficulty},ui:{...R.challenge.ui,...A.challenge?.ui},onChallengeStart:A.challenge?.onChallengeStart,onChallengeComplete:A.challenge?.onChallengeComplete,onChallengeProgress:A.challenge?.onChallengeProgress},formProtection:{mode:A.formProtection?.mode??R.formProtection.mode,minTimeBeforeSubmit:A.formProtection?.minTimeBeforeSubmit??R.formProtection.minTimeBeforeSubmit,maxHoldTime:A.formProtection?.maxHoldTime??R.formProtection.maxHoldTime,showLoadingUI:A.formProtection?.showLoadingUI??R.formProtection.showLoadingUI,loadingMessage:A.formProtection?.loadingMessage??R.formProtection.loadingMessage,onHold:A.formProtection?.onHold,onRelease:A.formProtection?.onRelease,onBlock:A.formProtection?.onBlock},fallbackMode:A.fallbackMode??R.fallbackMode,cookie:A.cookie,headers:A.headers,formInject:A.formInject,onScoreUpdate:A.onScoreUpdate,onConnectionChange:A.onConnectionChange,onError:A.onError,onUsageLimitExceeded:A.onUsageLimitExceeded,onHighBotScore:A.onHighBotScore,onServerConfig:A.onServerConfig,onServerAction:A.onServerAction}}class u{events=[];startTime=0;sampleRate;maxBufferSize;isListening=!1;boundHandleMouseMove;boundHandleMouseDown;boundHandleMouseUp;boundHandleClick;constructor(A={}){this.sampleRate=A.sampleRate??0.5,this.maxBufferSize=A.maxBufferSize??500,this.boundHandleMouseMove=this.handleMouseMove.bind(this),this.boundHandleMouseDown=this.handleMouseDown.bind(this),this.boundHandleMouseUp=this.handleMouseUp.bind(this),this.boundHandleClick=this.handleClick.bind(this)}start(){if(this.isListening)return;this.startTime=Date.now(),document.addEventListener("mousemove",this.boundHandleMouseMove,{passive:!0}),document.addEventListener("mousedown",this.boundHandleMouseDown,{passive:!0}),document.addEventListener("mouseup",this.boundHandleMouseUp,{passive:!0}),document.addEventListener("click",this.boundHandleClick,{passive:!0}),this.isListening=!0}stop(){if(!this.isListening)return;document.removeEventListener("mousemove",this.boundHandleMouseMove),document.removeEventListener("mousedown",this.boundHandleMouseDown),document.removeEventListener("mouseup",this.boundHandleMouseUp),document.removeEventListener("click",this.boundHandleClick),this.isListening=!1}addEvent(A){if(this.events.push(A),this.events.length>this.maxBufferSize)this.events.shift()}handleMouseMove(A){if(Math.random()>this.sampleRate)return;this.addEvent({type:"move",x:A.clientX,y:A.clientY,t:Date.now()})}handleMouseDown(A){this.addEvent({type:"down",x:A.clientX,y:A.clientY,t:Date.now(),button:A.button})}handleMouseUp(A){this.addEvent({type:"up",x:A.clientX,y:A.clientY,t:Date.now(),button:A.button})}handleClick(A){let B=A.target,Q,E;if(B&&B.getBoundingClientRect){let I=B.getBoundingClientRect();Q={top:I.top,left:I.left,width:I.width,height:I.height},E=B.tagName?.toLowerCase()}this.addEvent({type:"click",x:A.clientX,y:A.clientY,t:Date.now(),button:A.button,targetRect:Q,targetTag:E})}getSignal(){return{events:[...this.events],start_time:this.startTime}}flush(){this.events=[]}getBufferSize(){return this.events.length}reset(){this.events=[],this.startTime=Date.now()}}class p{events=[];startTime=0;maxBufferSize;isListening=!1;boundHandleScroll;constructor(A={}){this.maxBufferSize=A.maxBufferSize??200,this.boundHandleScroll=this.handleScroll.bind(this)}start(){if(this.isListening)return;this.startTime=Date.now(),window.addEventListener("scroll",this.boundHandleScroll,{passive:!0}),this.isListening=!0}stop(){if(!this.isListening)return;window.removeEventListener("scroll",this.boundHandleScroll),this.isListening=!1}handleScroll(){if(this.events.push({y:window.scrollY,t:Date.now()}),this.events.length>this.maxBufferSize)this.events.shift()}getSignal(){return{events:[...this.events],start_time:this.startTime}}flush(){this.events=[]}getBufferSize(){return this.events.length}reset(){this.events=[],this.startTime=Date.now()}}class k{static instance=null;timings={signalRoundtrips:[]};pendingSignals=new Map;constructor(){this.timings.scriptStart=performance.now()}static getInstance(){if(!k.instance)k.instance=new k;return k.instance}static reset(){k.instance=null}markScriptStart(){this.timings.scriptStart=performance.now()}markConstructorStart(){this.timings.constructorStart=performance.now()}markConstructorEnd(){this.timings.constructorEnd=performance.now()}markStartCalled(){this.timings.startCalled=performance.now()}markSdkReady(){this.timings.sdkReady=performance.now()}markFingerprintStart(){this.timings.fingerprintStart=performance.now()}markFingerprintEnd(){this.timings.fingerprintEnd=performance.now()}markWsConnectStart(){this.timings.wsConnectStart=performance.now()}markWsConnectEnd(){this.timings.wsConnectEnd=performance.now()}markChannelJoinStart(){this.timings.channelJoinStart=performance.now()}markChannelJoinEnd(){this.timings.channelJoinEnd=performance.now()}markInitialScoreReceived(){this.timings.initialScoreReceived=performance.now()}markFormCollectorStart(){this.timings.formCollectorStart=performance.now()}markFormCollectorReady(){this.timings.formCollectorReady=performance.now()}markFirstFormInteraction(){if(!this.timings.firstFormInteraction){if(this.timings.firstFormInteraction=performance.now(),this.timings.sdkReady)this.timings.timeToFirstInteraction=this.timings.firstFormInteraction-this.timings.sdkReady}}markFirstSubmitAttempt(A){if(!this.timings.firstSubmitAttempt)this.timings.firstSubmitAttempt=performance.now(),this.timings.hadScoreBeforeSubmit=A}markSignalSent(A){this.pendingSignals.set(A,performance.now())}markSignalResponseReceived(A){let B=this.pendingSignals.get(A);if(B!==void 0){let Q=performance.now(),E={sentAt:B,receivedAt:Q,roundtripMs:Q-B,seq:A};this.timings.signalRoundtrips?.push(E),this.pendingSignals.delete(A)}}getTimings(){return{...this.timings}}getSummary(){let A=this.timings,B=A.signalRoundtrips||[],Q=0,E=1/0,I=0;if(B.length>0)Q=B.reduce((D,z)=>D+z.roundtripMs,0)/B.length,E=Math.min(...B.map((D)=>D.roundtripMs)),I=Math.max(...B.map((D)=>D.roundtripMs));let C=(A.sdkReady??0)-(A.scriptStart??0),Y=(A.fingerprintEnd??0)-(A.fingerprintStart??0),G=(A.wsConnectEnd??0)-(A.wsConnectStart??0),Z=(A.channelJoinEnd??0)-(A.channelJoinStart??0),W=(A.initialScoreReceived??0)-(A.startCalled??0),X=(A.initialScoreReceived??0)-(A.scriptStart??0);return{totalStartupMs:Math.round(C),fingerprintMs:Math.round(Y),wsConnectionMs:Math.round(G),channelJoinMs:Math.round(Z),timeToFirstScoreMs:Math.round(W),avgSignalRoundtripMs:Math.round(Q),minSignalRoundtripMs:E===1/0?0:Math.round(E),maxSignalRoundtripMs:Math.round(I),vulnerabilityWindowMs:Math.round(X),protectedBeforeSubmit:A.hadScoreBeforeSubmit??!1}}logSummary(){let A=this.getSummary(),B=this.timings;if(B.firstFormInteraction);if(B.firstSubmitAttempt);if(A.vulnerabilityWindowMs>0);}getReport(){return{timings:this.timings,summary:this.getSummary(),userAgent:navigator.userAgent,timestamp:Date.now()}}}var J=k.getInstance();function O(){return k.getInstance()}var _="__bs_ghost_value";class m{keyEvents=[];focusEvents=[];pasteEvents=[];inputEvents=[];submitCount=0;startTime=0;maxKeyEvents;maxFocusEvents;maxInputEvents;isListening=!1;valueSetterHooked=!1;onSubmit;originalInputDescriptor;originalTextareaDescriptor;lastKeyWasTab=!1;currentField=null;emailDomains=new Set;boundHandleFocusIn;boundHandleFocusOut;boundHandleKeyDown;boundHandleKeyUp;boundHandlePaste;boundHandleSubmit;boundHandleClick;boundHandleInput;boundHandleGhostValue;constructor(A={}){this.maxKeyEvents=A.maxKeyEvents??500,this.maxFocusEvents=A.maxFocusEvents??100,this.maxInputEvents=A.maxInputEvents??200,this.onSubmit=A.onSubmit,this.boundHandleFocusIn=this.handleFocusIn.bind(this),this.boundHandleFocusOut=this.handleFocusOut.bind(this),this.boundHandleKeyDown=this.handleKeyDown.bind(this),this.boundHandleKeyUp=this.handleKeyUp.bind(this),this.boundHandlePaste=this.handlePaste.bind(this),this.boundHandleSubmit=this.handleSubmit.bind(this),this.boundHandleClick=this.handleClick.bind(this),this.boundHandleInput=this.handleInput.bind(this),this.boundHandleGhostValue=this.handleGhostValue.bind(this)}start(){if(this.isListening)return;this.startTime=Date.now(),document.addEventListener("focusin",this.boundHandleFocusIn,{passive:!0,capture:!0}),document.addEventListener("focusout",this.boundHandleFocusOut,{passive:!0,capture:!0}),document.addEventListener("keydown",this.boundHandleKeyDown,{passive:!0}),document.addEventListener("keyup",this.boundHandleKeyUp,{passive:!0}),document.addEventListener("paste",this.boundHandlePaste,{passive:!0}),document.addEventListener("submit",this.boundHandleSubmit,{passive:!0}),document.addEventListener("click",this.boundHandleClick,{passive:!0}),document.addEventListener("input",this.boundHandleInput,{passive:!0}),document.addEventListener(_,this.boundHandleGhostValue,{passive:!0}),this.hookValueSetters(),this.isListening=!0}stop(){if(!this.isListening)return;document.removeEventListener("focusin",this.boundHandleFocusIn,{capture:!0}),document.removeEventListener("focusout",this.boundHandleFocusOut,{capture:!0}),document.removeEventListener("keydown",this.boundHandleKeyDown),document.removeEventListener("keyup",this.boundHandleKeyUp),document.removeEventListener("paste",this.boundHandlePaste),document.removeEventListener("submit",this.boundHandleSubmit),document.removeEventListener("click",this.boundHandleClick),document.removeEventListener("input",this.boundHandleInput),document.removeEventListener(_,this.boundHandleGhostValue),this.unhookValueSetters(),this.isListening=!1}isFormInput(A){if(!A||!(A instanceof HTMLElement))return!1;let B=A.tagName.toLowerCase();if(B==="textarea"||B==="select")return!0;if(B==="input"){let Q=A.type.toLowerCase();return!["submit","button","reset","hidden","image"].includes(Q)}return!1}isEmailField(A){let B=A.type?.toLowerCase()||"",Q=(A.name||"").toLowerCase(),E=(A.id||"").toLowerCase();return B==="email"||Q.includes("email")||Q.includes("e-mail")||E.includes("email")||E.includes("e-mail")}extractEmailDomain(A){if(!A||typeof A!=="string")return null;let B=A.trim();if(!B)return null;let Q=B.match(/@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})$/);return Q?Q[1].toLowerCase():null}getFieldId(A){return A.id||A.getAttribute("name")||`field-${A.tagName.toLowerCase()}`}handleFocusIn(A){if(!this.isFormInput(A.target))return;O().markFirstFormInteraction();let B=this.getFieldId(A.target),Q="direct";if(this.lastKeyWasTab)Q="tab";if(this.focusEvents.push({type:"focus",field:B,t:Date.now(),method:Q}),this.focusEvents.length>this.maxFocusEvents)this.focusEvents.shift();this.currentField=B,this.lastKeyWasTab=!1}handleFocusOut(A){if(!this.isFormInput(A.target))return;let B=A.target,Q=this.getFieldId(B);if(this.focusEvents.push({type:"blur",field:Q,t:Date.now()}),this.focusEvents.length>this.maxFocusEvents)this.focusEvents.shift();if(B instanceof HTMLInputElement&&this.isEmailField(B)){let E=this.extractEmailDomain(B.value);if(E)this.emailDomains.add(E)}this.currentField=null}handleClick(A){if(!this.isFormInput(A.target))return;let B=this.focusEvents[this.focusEvents.length-1];if(B&&B.type==="focus"&&Date.now()-B.t<50)B.method="click"}handleKeyDown(A){if(A.key==="Tab"){this.lastKeyWasTab=!0;return}if(!this.isFormInput(A.target))return;let B="key";if(A.key==="Backspace")B="backspace";else if(A.key==="Delete")B="delete";else if(A.key==="Enter")B="enter";else if(A.key==="Tab")B="tab";else if(A.key.length===1)B="char";else if(A.key.startsWith("Arrow"))B="arrow";if(this.keyEvents.push({type:"down",code:B,t:Date.now(),field:this.currentField||void 0}),this.keyEvents.length>this.maxKeyEvents)this.keyEvents.shift()}handleKeyUp(A){if(!this.isFormInput(A.target))return;let B="key";if(A.key==="Backspace")B="backspace";else if(A.key==="Delete")B="delete";else if(A.key.length===1)B="char";if(this.keyEvents.push({type:"up",code:B,t:Date.now(),field:this.currentField||void 0}),this.keyEvents.length>this.maxKeyEvents)this.keyEvents.shift()}handleInput(A){if(!this.isFormInput(A.target))return;let B=A.target,E=A.inputType||"unknown",I=B.value?.length??0;if(this.inputEvents.push({field:this.getFieldId(B),t:Date.now(),inputType:E,valueLength:I}),this.inputEvents.length>this.maxInputEvents)this.inputEvents.shift()}handlePaste(A){if(!this.isFormInput(A.target))return;let B=A.clipboardData?.getData("text")||"";this.pasteEvents.push({field:this.getFieldId(A.target),t:Date.now(),length:B.length})}handleSubmit(A){this.submitCount++;let B=A.target;if(B&&B.elements)for(let Q=0;Q<B.elements.length;Q++){let E=B.elements[Q];if(E instanceof HTMLInputElement&&this.isEmailField(E)){let I=this.extractEmailDomain(E.value);if(I)this.emailDomains.add(I)}}this.onSubmit?.()}getSignal(){return{keys:[...this.keyEvents],focus:[...this.focusEvents],pastes:[...this.pasteEvents],inputs:[...this.inputEvents],submits:this.submitCount,start_time:this.startTime,email_domains:this.emailDomains.size>0?Array.from(this.emailDomains):void 0}}flush(){this.keyEvents=[],this.focusEvents=[],this.pasteEvents=[],this.inputEvents=[]}getBufferSize(){return this.keyEvents.length+this.focusEvents.length+this.pasteEvents.length+this.inputEvents.length}reset(){this.keyEvents=[],this.focusEvents=[],this.pasteEvents=[],this.inputEvents=[],this.submitCount=0,this.startTime=Date.now(),this.lastKeyWasTab=!1,this.currentField=null,this.emailDomains.clear()}hookValueSetters(){if(this.valueSetterHooked)return;if(this.originalInputDescriptor=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"value"),this.originalInputDescriptor){let A=this.originalInputDescriptor.set,B=this.originalInputDescriptor.get;Object.defineProperty(HTMLInputElement.prototype,"value",{configurable:!0,enumerable:!0,get(){return B?.call(this)},set(Q){let E=B?.call(this)??"";A?.call(this,Q);let I=Q??"";if(I!==E)this.dispatchEvent(new CustomEvent(_,{bubbles:!0,detail:{valueLength:I.length,wasEmpty:E.length===0}}))}})}if(this.originalTextareaDescriptor=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value"),this.originalTextareaDescriptor){let A=this.originalTextareaDescriptor.set,B=this.originalTextareaDescriptor.get;Object.defineProperty(HTMLTextAreaElement.prototype,"value",{configurable:!0,enumerable:!0,get(){return B?.call(this)},set(Q){let E=B?.call(this)??"";A?.call(this,Q);let I=Q??"";if(I!==E)this.dispatchEvent(new CustomEvent(_,{bubbles:!0,detail:{valueLength:I.length,wasEmpty:E.length===0}}))}})}this.valueSetterHooked=!0}unhookValueSetters(){if(!this.valueSetterHooked)return;if(this.originalInputDescriptor)Object.defineProperty(HTMLInputElement.prototype,"value",this.originalInputDescriptor);if(this.originalTextareaDescriptor)Object.defineProperty(HTMLTextAreaElement.prototype,"value",this.originalTextareaDescriptor);this.valueSetterHooked=!1}handleGhostValue(A){let B=A.target;if(!this.isFormInput(B))return;let E=A.detail?.valueLength??0;if(this.inputEvents.push({field:this.getFieldId(B),t:Date.now(),inputType:"programmatic",valueLength:E}),this.inputEvents.length>this.maxInputEvents)this.inputEvents.shift()}}class d{cachedSignal=null;collect(){if(this.cachedSignal)return this.cachedSignal;let A=navigator,B=window;return this.cachedSignal={user_agent:navigator.userAgent,platform:navigator.platform,language:navigator.language,languages:[...navigator.languages||[]],hardware_concurrency:navigator.hardwareConcurrency??null,device_memory:A.deviceMemory??null,max_touch_points:navigator.maxTouchPoints??0,screen_width:screen.width,screen_height:screen.height,screen_avail_width:screen.availWidth,screen_avail_height:screen.availHeight,color_depth:screen.colorDepth,pixel_ratio:window.devicePixelRatio??1,...this.getWebGLInfo(),plugins_count:navigator.plugins?.length??0,mime_types_count:navigator.mimeTypes?.length??0,timezone:this.getTimezone(),timezone_offset:new Date().getTimezoneOffset(),has_webdriver:A.webdriver===!0,has_chrome_runtime:!!B.chrome?.runtime,has_chrome_app:!!B.chrome?.app,has_notification_api:"Notification"in window,has_permissions_api:"permissions"in navigator,outer_dimensions:{width:window.outerWidth,height:window.outerHeight},inner_dimensions:{width:window.innerWidth,height:window.innerHeight},notification_permission:this.getNotificationPermission()},this.cachedSignal}getWebGLInfo(){try{let A=document.createElement("canvas"),B=A.getContext("webgl")||A.getContext("experimental-webgl");if(!B||!(B instanceof WebGLRenderingContext))return{webgl_vendor:null,webgl_renderer:null};let Q=B.getExtension("WEBGL_debug_renderer_info");if(!Q)return{webgl_vendor:null,webgl_renderer:null};return{webgl_vendor:B.getParameter(Q.UNMASKED_VENDOR_WEBGL),webgl_renderer:B.getParameter(Q.UNMASKED_RENDERER_WEBGL)}}catch{return{webgl_vendor:null,webgl_renderer:null}}}getTimezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return null}}getNotificationPermission(){if("Notification"in window)return Notification.permission;return null}getSignal(){return this.collect()}reset(){this.cachedSignal=null}}b();class s{cachedFingerprint=null;async generate(){if(this.cachedFingerprint)return this.cachedFingerprint;let[A,B,Q,E,I]=await Promise.all([this.getCanvasHash(),this.getWebGLData(),this.getAudioHash(),this.getFontData(),this.getScreenHash()]),C={hash:"",canvas_hash:A,webgl_hash:B.hash,audio_hash:Q,font_hash:E.hash,screen_hash:I,webgl_vendor:B.vendor,webgl_renderer:B.renderer,timezone:this.getTimezone(),language:this.getLanguage(),platform:this.getPlatform(),font_count:E.count};return C.hash=await this.generateMainHash(C),this.cachedFingerprint=C,C}getFingerprint(){return this.cachedFingerprint}reset(){this.cachedFingerprint=null}async getCanvasHash(){try{let A=document.createElement("canvas");A.width=200,A.height=50;let B=A.getContext("2d");if(!B)return null;B.textBaseline="top",B.font="14px 'Arial'",B.fillStyle="#f60",B.fillRect(125,1,62,20),B.fillStyle="#069",B.fillText("BotSigged,\uD83C\uDFA8",2,15),B.fillStyle="rgba(102, 204, 0, 0.7)",B.fillText("BotSigged,\uD83C\uDFA8",4,17);let Q=A.toDataURL();return this.hashString(Q)}catch{return null}}async getWebGLData(){try{let A=document.createElement("canvas"),B=A.getContext("webgl")||A.getContext("experimental-webgl");if(!B||!(B instanceof WebGLRenderingContext))return{hash:null,vendor:null,renderer:null};let Q=[],E=[B.ALIASED_LINE_WIDTH_RANGE,B.ALIASED_POINT_SIZE_RANGE,B.ALPHA_BITS,B.BLUE_BITS,B.DEPTH_BITS,B.GREEN_BITS,B.MAX_COMBINED_TEXTURE_IMAGE_UNITS,B.MAX_CUBE_MAP_TEXTURE_SIZE,B.MAX_FRAGMENT_UNIFORM_VECTORS,B.MAX_RENDERBUFFER_SIZE,B.MAX_TEXTURE_IMAGE_UNITS,B.MAX_TEXTURE_SIZE,B.MAX_VARYING_VECTORS,B.MAX_VERTEX_ATTRIBS,B.MAX_VERTEX_TEXTURE_IMAGE_UNITS,B.MAX_VERTEX_UNIFORM_VECTORS,B.MAX_VIEWPORT_DIMS,B.RED_BITS,B.RENDERER,B.SHADING_LANGUAGE_VERSION,B.STENCIL_BITS,B.VENDOR,B.VERSION];for(let W of E)try{let X=B.getParameter(W);Q.push(String(X))}catch{Q.push("")}let I=B.getSupportedExtensions();if(I)Q.push(I.sort().join(","));let C=null,Y=null,G=B.getExtension("WEBGL_debug_renderer_info");if(G)C=B.getParameter(G.UNMASKED_VENDOR_WEBGL),Y=B.getParameter(G.UNMASKED_RENDERER_WEBGL);return{hash:this.hashString(Q.join("|")),vendor:C,renderer:Y}}catch{return{hash:null,vendor:null,renderer:null}}}async getAudioHash(){try{let A=window.OfflineAudioContext||window.webkitOfflineAudioContext;if(!A)return null;let B=new A(1,4500,44100),Q=B.createOscillator(),E=B.createDynamicsCompressor();Q.type="triangle",Q.frequency.setValueAtTime(1e4,B.currentTime),E.threshold.setValueAtTime(-50,B.currentTime),E.knee.setValueAtTime(40,B.currentTime),E.ratio.setValueAtTime(12,B.currentTime),E.attack.setValueAtTime(0,B.currentTime),E.release.setValueAtTime(0.25,B.currentTime),Q.connect(E),E.connect(B.destination),Q.start(0);let C=(await B.startRendering()).getChannelData(0),Y=[];for(let G=0;G<C.length;G+=100)Y.push(C[G]);return this.hashString(Y.join(","))}catch{return null}}async getFontData(){let A=["Arial","Arial Black","Arial Narrow","Calibri","Cambria","Cambria Math","Comic Sans MS","Consolas","Courier","Courier New","Georgia","Helvetica","Impact","Lucida Console","Lucida Sans Unicode","Microsoft Sans Serif","MS Gothic","MS PGothic","MS Sans Serif","MS Serif","Palatino Linotype","Segoe Print","Segoe Script","Segoe UI","Symbol","Tahoma","Times","Times New Roman","Trebuchet MS","Verdana","Wingdings"],B=["monospace","sans-serif","serif"],Q="mmmmmmmmmmlli",E="72px",I=document.createElement("span");I.style.position="absolute",I.style.left="-9999px",I.style.fontSize="72px",I.style.lineHeight="normal",I.innerHTML="mmmmmmmmmmlli",document.body.appendChild(I);let C={};for(let Z of B)I.style.fontFamily=Z,C[Z]=I.offsetWidth;let Y=[];for(let Z of A){let W=!1;for(let X of B)if(I.style.fontFamily=`'${Z}', ${X}`,I.offsetWidth!==C[X]){W=!0;break}if(W)Y.push(Z)}return document.body.removeChild(I),{hash:this.hashString(Y.join(",")),count:Y.length}}async getScreenHash(){let A=[String(screen.width),String(screen.height),String(screen.availWidth),String(screen.availHeight),String(screen.colorDepth),String(screen.pixelDepth),String(window.devicePixelRatio||1)];return this.hashString(A.join("|"))}getTimezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return null}}getLanguage(){return navigator.language||null}getPlatform(){return navigator.platform||null}generateMainHash(A){let B=[A.canvas_hash||"",A.webgl_hash||"",A.audio_hash||"",A.font_hash||"",A.screen_hash||"",A.timezone||"",A.language||"",A.platform||""];return this.hashString(B.join("|"))}hashString(A){return i(A)}}class n{ws=null;endpoint;apiKey;heartbeatInterval;reconnectAttempts;reconnectDelay;debug;state="disconnected";channelState="closed";refCounter=0;joinRef=null;heartbeatTimer=null;reconnectTimer=null;reconnectCount=0;pendingReplies=new Map;onConnectionChange;onError;channelCallbacks={};topic=null;constructor(A){this.endpoint=A.endpoint,this.apiKey=A.apiKey,this.heartbeatInterval=A.heartbeatInterval??30000,this.reconnectAttempts=A.reconnectAttempts??10,this.reconnectDelay=A.reconnectDelay??((B)=>Math.min(1000*Math.pow(2,B),30000)),this.debug=A.debug??!1,this.onConnectionChange=A.onConnectionChange,this.onError=A.onError}connect(){return new Promise((A,B)=>{if(this.ws&&this.state==="connected"){A();return}this.setState("connecting");let Q=this.buildUrl();this.log("Connecting to",Q);try{this.ws=new WebSocket(Q),this.ws.onopen=()=>{this.log("WebSocket connected"),this.setState("connected"),this.reconnectCount=0,this.startHeartbeat(),A()},this.ws.onclose=(E)=>{this.log("WebSocket closed",E.code,E.reason),this.handleClose()},this.ws.onerror=(E)=>{this.log("WebSocket error",E);let I=Error("WebSocket connection error");this.handleError(I),B(I)},this.ws.onmessage=(E)=>{this.handleMessage(E.data)}}catch(E){let I=E instanceof Error?E:Error(String(E));this.handleError(I),B(I)}})}disconnect(){if(this.stopHeartbeat(),this.stopReconnect(),this.ws)this.ws.close(1000,"Client disconnect"),this.ws=null;this.setState("disconnected"),this.setChannelState("closed")}joinChannel(A,B,Q,E,I={},C){return this.channelCallbacks=I,this.topic=`detection:${A}`,new Promise((Y,G)=>{if(this.state!=="connected"){G(Error("WebSocket not connected"));return}this.setChannelState("joining"),this.joinRef=this.makeRef();let Z={session_id:A,api_key:this.apiKey,fingerprint:B,session:Q,browser:E};if(C)Z.account_id=C;this.push("phx_join",Z,this.joinRef).then((W)=>{this.log("Channel joined",W),this.setChannelState("joined"),this.channelCallbacks.onJoin?.(),Y(W)}).catch((W)=>{this.log("Channel join failed",W),this.setChannelState("error"),this.channelCallbacks.onError?.(W),G(W)})})}leaveChannel(){return new Promise((A,B)=>{if(this.channelState!=="joined"){A();return}this.setChannelState("leaving"),this.push("phx_leave",{}).then(()=>{this.log("Channel left"),this.setChannelState("closed"),this.joinRef=null,this.topic=null,this.channelCallbacks.onLeave?.(),A()}).catch((Q)=>{this.setChannelState("error"),B(Q)})})}sendSignal(A){if(this.channelState!=="joined")return Promise.reject(Error("Channel not joined"));return this.push("signal",A)}sendFormStatus(A){if(this.channelState!=="joined")return Promise.reject(Error("Channel not joined"));return this.push("form_status",{status:A})}sendEvent(A,B){if(this.channelState!=="joined")return Promise.reject(Error("Channel not joined"));return this.push(A,B)}getState(){return this.state}getChannelState(){return this.channelState}isReady(){return this.state==="connected"&&this.channelState==="joined"}buildUrl(){let A=new URL(this.endpoint);return A.searchParams.set("vsn","2.0.0"),A.searchParams.set("api_key",this.apiKey),A.toString()}makeRef(){return this.refCounter++,String(this.refCounter)}push(A,B,Q){return new Promise((E,I)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){I(Error("WebSocket not open"));return}if(!this.topic){I(Error("Channel topic not set"));return}let C=Q??this.makeRef(),Y=[this.joinRef,C,this.topic,A,B],G=setTimeout(()=>{this.pendingReplies.delete(C),I(Error(`Timeout waiting for reply to ${A}`))},1e4);this.pendingReplies.set(C,{resolve:E,reject:I,timeout:G}),this.log("Sending",A,B),this.ws.send(JSON.stringify(Y))})}handleMessage(A){try{let[B,Q,E,I,C]=JSON.parse(A);if(this.log("Received",I,C),I==="phx_reply"&&Q){let Y=this.pendingReplies.get(Q);if(Y){clearTimeout(Y.timeout),this.pendingReplies.delete(Q);let G=C;if(G.status==="ok")Y.resolve(G.response??{});else if(G.response&&typeof G.response==="object"&&"code"in G.response)Y.reject(G.response);else{let Z=this.buildErrorMessage(G.status,G.response);Y.reject(Error(Z))}}return}if(I==="phx_error"){let Y=Error("Channel error");this.setChannelState("error"),this.channelCallbacks.onError?.(Y);return}if(I==="phx_close"){this.setChannelState("closed"),this.channelCallbacks.onLeave?.();return}if(I==="score_update"){this.channelCallbacks.onScoreUpdate?.(C);return}if(I==="action"){this.channelCallbacks.onAction?.(C);return}this.channelCallbacks.onMessage?.(I,C)}catch(B){this.log("Error parsing message",B)}}handleClose(){this.stopHeartbeat(),this.setState("disconnected"),this.setChannelState("closed");for(let[A,B]of this.pendingReplies)clearTimeout(B.timeout),B.reject(Error("Connection closed"));this.pendingReplies.clear(),this.scheduleReconnect()}handleError(A){this.setState("error"),this.onError?.(A)}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){let A=[null,this.makeRef(),"phoenix","heartbeat",{}];if(this.ws.send(JSON.stringify(A)),this.channelState==="joined")this.push("heartbeat",{}).then((B)=>{if(B.bot_score!==void 0)this.channelCallbacks.onScoreUpdate?.({bot_score:B.bot_score,classification:B.classification,triggered_rules:[],event_count:0})}).catch(()=>{})}},this.heartbeatInterval)}stopHeartbeat(){if(this.heartbeatTimer)clearInterval(this.heartbeatTimer),this.heartbeatTimer=null}scheduleReconnect(){if(this.reconnectCount>=this.reconnectAttempts){this.log("Max reconnect attempts reached");return}let A=this.reconnectDelay(this.reconnectCount);this.reconnectCount++,this.log(`Scheduling reconnect attempt ${this.reconnectCount} in ${A}ms`),this.reconnectTimer=setTimeout(()=>{this.connect().catch((B)=>{this.log("Reconnect failed",B)})},A)}stopReconnect(){if(this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;this.reconnectCount=0}setState(A){if(this.state!==A)this.state=A,this.onConnectionChange?.(A)}setChannelState(A){this.channelState=A}buildErrorMessage(A,B){if(B){if(typeof B.reason==="string")return`Channel error: ${B.reason}`;if(Object.keys(B).length>0)return`Channel error (${A??"error"}): ${JSON.stringify(B)}`}return A??"Unknown error"}log(...A){if(this.debug);}}class t{config;isReady=!1;hasScore=!1;hasFormScore=!1;currentScore=null;pendingSubmissions=[];pendingRequests=[];protectedForms=new Set;releasingForms=new Set;loadingOverlay=null;formObserver=null;startTime;originalFetch=null;originalXHROpen=null;originalXHRSend=null;constructor(A={}){if(this.startTime=performance.now(),this.config={mode:A.mode??"none",minTimeBeforeSubmit:A.minTimeBeforeSubmit??500,maxHoldTime:A.maxHoldTime??5000,showLoadingUI:A.showLoadingUI??!0,loadingMessage:A.loadingMessage??"Please wait...",onHold:A.onHold,onRelease:A.onRelease,onBlock:A.onBlock,flushAndWaitForScore:A.flushAndWaitForScore},this.config.mode!=="none")this.setup()}setup(){if(this.config.mode==="auto")this.interceptFetch(),this.interceptXHR();let A=()=>{document.querySelectorAll("form").forEach((B)=>{this.protectForm(B)}),this.formObserver=new MutationObserver((B)=>{B.forEach((Q)=>{Q.addedNodes.forEach((E)=>{if(E instanceof HTMLFormElement)this.protectForm(E);if(E instanceof HTMLElement)E.querySelectorAll("form").forEach((I)=>{this.protectForm(I)})})})}),this.formObserver.observe(document.body,{childList:!0,subtree:!0})};if(document.body)A();else document.addEventListener("DOMContentLoaded",A,{once:!0})}isFormLikeRequest(A,B){if((B?.method?.toUpperCase()||"GET")!=="POST")return!1;try{if((typeof A==="string"?new URL(A,window.location.origin):A instanceof URL?A:new URL(A.url)).origin!==window.location.origin)return!1}catch{return!1}let E=B?.headers instanceof Headers?B.headers.get("content-type"):typeof B?.headers==="object"&&B.headers!==null?B.headers["content-type"]||B.headers["Content-Type"]:null;if(E){let I=E.toLowerCase();if(I.includes("application/x-www-form-urlencoded")||I.includes("multipart/form-data")||I.includes("application/json"))return!0;return!1}if(B?.body)return!0;return!1}interceptFetch(){this.originalFetch=window.fetch.bind(window);let A=this;window.fetch=async function(B,Q){if(!A.isFormLikeRequest(B,Q))return A.originalFetch(B,Q);if(A.hasScore)return A.originalFetch(B,Q);return new Promise((E,I)=>{let C={resolve:E,reject:I,execute:()=>A.originalFetch(B,Q),timestamp:performance.now()};if(A.pendingRequests.push(C),A.config.showLoadingUI&&A.pendingRequests.length===1)A.showLoading(document.createElement("form"));if(setTimeout(()=>{if(A.pendingRequests.includes(C))A.releaseRequest(C)},A.config.maxHoldTime),A.hasScore)A.releaseRequest(C)})}}interceptXHR(){this.originalXHROpen=XMLHttpRequest.prototype.open,this.originalXHRSend=XMLHttpRequest.prototype.send;let A=this;XMLHttpRequest.prototype.open=function(B,Q,E=!0,I,C){let Y=this;return Y._bsMethod=B.toUpperCase(),Y._bsUrl=Q.toString(),A.originalXHROpen.call(this,B,Q,E,I,C)},XMLHttpRequest.prototype.send=function(B){let Q=this,E=Q._bsMethod||"GET",I=Q._bsUrl||"";if(E!=="POST")return A.originalXHRSend.call(this,B);try{if(new URL(I,window.location.origin).origin!==window.location.origin)return A.originalXHRSend.call(this,B)}catch{return A.originalXHRSend.call(this,B)}if(A.hasScore)return A.originalXHRSend.call(this,B);let C=performance.now(),Y=()=>{if(A.hasScore){if(A.config.showLoadingUI)A.hideLoading();A.originalXHRSend.call(Q,B)}else if(performance.now()-C>=A.config.maxHoldTime){if(A.config.showLoadingUI)A.hideLoading();A.originalXHRSend.call(Q,B)}else setTimeout(Y,50)};if(A.config.showLoadingUI)A.showLoading(document.createElement("form"));Y()}}releaseRequest(A){let B=this.pendingRequests.indexOf(A);if(B===-1)return;if(this.pendingRequests.splice(B,1),this.pendingRequests.length===0&&this.config.showLoadingUI)this.hideLoading();A.execute().then(A.resolve).catch(A.reject)}protectForm(A){if(this.protectedForms.has(A))return;this.protectedForms.add(A),A.addEventListener("submit",(B)=>this.handleSubmit(B,A),{capture:!0})}handleSubmit(A,B){if(this.releasingForms.has(B)){this.releasingForms.delete(B);return}let E=performance.now()-this.startTime;switch(O().markFirstSubmitAttempt(this.hasScore),this.config.mode){case"holdUntilReady":if(!this.hasScore)A.preventDefault(),A.stopPropagation(),this.holdSubmission(B,A);break;case"holdUntilFormScored":A.preventDefault(),A.stopPropagation(),this.holdAndScoreSubmission(B,A);break;case"blockInstant":if(E<this.config.minTimeBeforeSubmit)A.preventDefault(),A.stopPropagation(),this.config.onBlock?.(B,"instant_submission");break;case"challengeFirst":if(!this.hasScore)A.preventDefault(),A.stopPropagation(),this.holdSubmission(B,A);break;case"none":default:break}}holdSubmission(A,B){if(this.config.onHold?.(A),this.config.showLoadingUI)this.showLoading(A);let Q={form:A,event:B,timestamp:performance.now(),resolver:()=>{},rejecter:()=>{}},E=new Promise((I,C)=>{Q.resolver=I,Q.rejecter=C});if(this.pendingSubmissions.push(Q),setTimeout(()=>{if(this.pendingSubmissions.includes(Q))this.releaseSubmission(Q,!1)},this.config.maxHoldTime),this.hasScore)this.releaseSubmission(Q,!1);E.catch(()=>{})}async holdAndScoreSubmission(A,B){if(this.config.onHold?.(A),this.config.showLoadingUI)this.showLoading(A);let Q=performance.now();try{if(!this.config.flushAndWaitForScore){this.submitForm(A);return}let E=this.config.flushAndWaitForScore(),I=new Promise((G)=>{setTimeout(()=>G(null),this.config.maxHoldTime)}),C=await Promise.race([E,I]),Y=performance.now()-Q;if(C===null);else this.currentScore=C,this.hasFormScore=!0;if(this.config.showLoadingUI)this.hideLoading();this.config.onRelease?.(A,!1),this.submitForm(A)}catch(E){if(this.config.showLoadingUI)this.hideLoading();this.config.onRelease?.(A,!1),this.submitForm(A)}}submitForm(A){if(this.releasingForms.add(A),A.requestSubmit)A.requestSubmit();else A.submit()}releaseSubmission(A,B){let Q=this.pendingSubmissions.indexOf(A);if(Q===-1)return;if(this.pendingSubmissions.splice(Q,1),this.config.showLoadingUI)this.hideLoading();if(this.config.onRelease?.(A.form,B),!B)if(A.resolver(),A.form.requestSubmit)A.form.requestSubmit();else A.form.submit();else A.rejecter("blocked")}showLoading(A){if(this.loadingOverlay)return;this.loadingOverlay=document.createElement("div"),this.loadingOverlay.innerHTML=`
1
+ (()=>{var{defineProperty:h,getOwnPropertyNames:DA,getOwnPropertyDescriptor:HA}=Object,$A=Object.prototype.hasOwnProperty;var BA=new WeakMap,VA=(A)=>{var B=BA.get(A),Q;if(B)return B;if(B=h({},"__esModule",{value:!0}),A&&typeof A==="object"||typeof A==="function")DA(A).map((E)=>!$A.call(B,E)&&h(B,E,{get:()=>A[E],enumerable:!(Q=HA(A,E))||Q.enumerable}));return BA.set(A,B),B};var v=(A,B)=>{for(var Q in B)h(A,Q,{get:B[Q],enumerable:!0,configurable:!0,set:(E)=>B[Q]=()=>E})};var g=(A,B)=>()=>(A&&(B=A(A=0)),B);var CA="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";function LA(A){let B=atob(A),Q=new Uint8Array(B.length);for(let E=0;E<B.length;E++)Q[E]=B.charCodeAt(E);return Q}async function c(){if(j)return j;return j=(async()=>{try{let A=LA(CA),B=await WebAssembly.compile(A);return l=(await WebAssembly.instantiate(B,{env:{abort:(E,I,C,Y)=>{console.error(`WASM abort at ${C}:${Y}`)}}})).exports,NA(l)}catch(A){throw j=null,A}})(),j}function a(){return l!==null}function NA(A){function B(I){let C=A.__new(I.length,1);return new Uint8Array(A.memory.buffer,C,I.length).set(I),C}function Q(I){let C=new Uint16Array(I.length);for(let Z=0;Z<I.length;Z++)C[Z]=I.charCodeAt(Z);let Y=A.__new(C.length*2,2);return new Uint16Array(A.memory.buffer,Y,C.length).set(C),Y}function E(I,C=1024){let Y=new Uint8Array(A.memory.buffer),G=Y.length;if(I<0||I>=G)return"";let Z=I,W=Math.min(I+C,G);while(Z<W&&Y[Z]!==0)Z++;let X=Y.slice(I,Z);return new TextDecoder().decode(X)}return{xxHash32(I,C=0){let Y=B(I);try{return A.xxHash32(Y,C)}finally{A.__unpin(Y)}},hashString(I,C=0){let Y=Q(I);try{return A.hashString(Y,C)}finally{A.__unpin(Y)}},hashStringToHex(I,C=0){let Y=Q(I);try{let G=A.hashStringToHex(Y,C);return E(G)}finally{A.__unpin(Y)}},verifyHash(I,C,Y=0){let G=B(I);try{return A.verifyHash(G,C,Y)}finally{A.__unpin(G)}},verifyStringHash(I,C,Y=0){let G=Q(I);try{return A.verifyStringHash(G,C,Y)}finally{A.__unpin(G)}}}}function P(){let A=new TextEncoder;function B(E,I=0){let X=(L,$)=>(L<<$|L>>>32-$)>>>0,N=(L,$)=>(L[$]|L[$+1]<<8|L[$+2]<<16|L[$+3]<<24)>>>0,H=E.length,z,q=0;if(H>=16){let L=H-16,$=I+2654435761+2246822519>>>0,T=I+2246822519>>>0,S=I>>>0,x=I-2654435761>>>0;while(q<=L)$=Math.imul(X($+Math.imul(N(E,q),2246822519)>>>0,13),2654435761)>>>0,q+=4,T=Math.imul(X(T+Math.imul(N(E,q),2246822519)>>>0,13),2654435761)>>>0,q+=4,S=Math.imul(X(S+Math.imul(N(E,q),2246822519)>>>0,13),2654435761)>>>0,q+=4,x=Math.imul(X(x+Math.imul(N(E,q),2246822519)>>>0,13),2654435761)>>>0,q+=4;z=X($,1)+X(T,7)+X(S,12)+X(x,18)>>>0}else z=I+374761393>>>0;z=z+H>>>0;while(q<=H-4)z=Math.imul(X(z+Math.imul(N(E,q),3266489917)>>>0,17),668265263)>>>0,q+=4;while(q<H)z=Math.imul(X(z+Math.imul(E[q],374761393)>>>0,11),2654435761)>>>0,q++;return z^=z>>>15,z=Math.imul(z,2246822519)>>>0,z^=z>>>13,z=Math.imul(z,3266489917)>>>0,z^=z>>>16,z>>>0}function Q(E){return(E>>>0).toString(16).padStart(8,"0")}return{xxHash32:B,hashString(E,I=0){return B(A.encode(E),I)},hashStringToHex(E,I=0){return Q(B(A.encode(E),I))},verifyHash(E,I,C=0){return B(E,C)===I},verifyStringHash(E,I,C=0){return B(A.encode(E),C)===I}}}var l=null,j=null;var YA=()=>{};var JA={};v(JA,{verifySignature:()=>FA,verify:()=>OA,loadHashModule:()=>c,isUsingWasm:()=>wA,isHashModuleLoaded:()=>a,initHashModule:()=>kA,hashToHex:()=>i,hash:()=>UA,getHash:()=>U,createSignature:()=>GA,createFallbackHashModule:()=>P});async function kA(A={}){let{preferWasm:B=!0,onWasmLoaded:Q,onFallback:E}=A;if(V)return V;if(M)return M;return M=(async()=>{if(B)try{return V=await c(),y=!0,Q?.(),V}catch(I){let C=I instanceof Error?I.message:"Unknown error";E?.(C)}else E?.("WASM disabled by configuration");return V=P(),y=!1,V})(),M}function U(){if(V)return V;return V=P(),y=!1,V}function wA(){return y&&a()}function UA(A,B=0){let Q=U();if(typeof A==="string")return Q.hashString(A,B);return Q.xxHash32(A,B)}function i(A,B=0){let Q=U();if(typeof A==="string")return Q.hashStringToHex(A,B);return Q.xxHash32(A,B).toString(16).padStart(8,"0")}function OA(A,B,Q=0){let E=U(),I=typeof B==="string"?parseInt(B,16):B;if(typeof A==="string")return E.verifyStringHash(A,I,Q);return E.verifyHash(A,I,Q)}function GA(A,B){let Q=U(),E=Q.hashString(B,0);return Q.hashString(A,E).toString(16).padStart(8,"0")}function FA(A,B,Q){return GA(A,Q)===B}var V=null,M=null,y=!0;var b=g(()=>{YA()});class AA{overlay=null;messageEl=null;progressEl=null;config;constructor(A){this.config=A}show(){return}setProgress(A){if(this.progressEl){let B=Math.min(100,Math.max(0,A*100));this.progressEl.style.width=`${B}%`}}showSuccess(){if(this.messageEl)this.messageEl.textContent=this.config.successMessage;if(this.progressEl)this.progressEl.style.width="100%"}hide(){if(this.overlay)this.overlay.remove(),this.overlay=null,this.messageEl=null,this.progressEl=null}isVisible(){return this.overlay!==null}}var WA={};v(WA,{ChallengeManager:()=>KA});function _A(){let A=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(A);else for(let B=0;B<16;B++)A[B]=Math.floor(Math.random()*256);return A}function PA(A){if(A===0)return 32;let B=0;if((A&4294901760)===0)B+=16,A<<=16;if((A&4278190080)===0)B+=8,A<<=8;if((A&4026531840)===0)B+=4,A<<=4;if((A&3221225472)===0)B+=2,A<<=2;if((A&2147483648)===0)B+=1;return B}function MA(A,B,Q,E){let I=U(),C=new Uint8Array(A.length+4);C.set(A);let Y=E,G=0;while(G<Q){C[A.length]=Y&255,C[A.length+1]=Y>>>8&255,C[A.length+2]=Y>>>16&255,C[A.length+3]=Y>>>24&255;let Z=I.xxHash32(C,0);if(G++,PA(Z)>=B)return{nonce:Y,found:!0,iterations:G};Y=Y+1>>>0}return{nonce:Y,found:!1,iterations:G}}class KA{config;overlay;solving=!1;solved=!1;pendingForms=new Map;formHandler=null;formObserver=null;resubmitting=!1;debug;constructor(A,B=!1){this.config=A,this.debug=B,this.overlay=new AA(A.ui)}getDifficultyForLevel(A){let B=this.config.difficulty;switch(A){case"critical":return B.critical;case"high":return B.high;case"medium":return B.medium;default:return 0}}shouldChallenge(A){if(!this.config.enabled||this.solved)return!1;let B=["low","medium","high","critical"],Q=B.indexOf(A),E=B.indexOf(this.config.minLevel);return Q>=E}blockFormsUntilSolved(A){if(this.formHandler)return;this.formHandler=(B)=>{if(this.solved||this.resubmitting)return;B.preventDefault(),B.stopPropagation();let Q=B.target;if(!this.pendingForms.has(Q))this.pendingForms.set(Q,B);if(!this.solving)this.startChallenge(A)},document.querySelectorAll("form").forEach((B)=>{B.addEventListener("submit",this.formHandler,!0)}),this.formObserver=new MutationObserver((B)=>{B.forEach((Q)=>{Q.addedNodes.forEach((E)=>{if(E instanceof HTMLFormElement&&this.formHandler)E.addEventListener("submit",this.formHandler,!0);if(E instanceof HTMLElement&&this.formHandler)E.querySelectorAll("form").forEach((I)=>{I.addEventListener("submit",this.formHandler,!0)})})})}),this.formObserver.observe(document.body,{childList:!0,subtree:!0}),this.log("Forms blocked, challenge required")}async startChallenge(A){if(this.solving||this.solved)return;this.solving=!0;let B=this.getDifficultyForLevel(A),Q=_A(),E=performance.now();this.log(`Starting challenge: difficulty=${B}, level=${A}`),this.config.onChallengeStart?.(A,B),this.overlay.show();let I=1<<B,C=0,Y=0,G;do{await new Promise((N)=>setTimeout(N,0)),G=MA(Q,B,this.config.chunkSize,C),Y+=G.iterations,C=G.nonce+1;let X=Math.min(1,Y/I);this.overlay.setProgress(X),this.config.onChallengeProgress?.(X,Y)}while(!G.found);let Z=performance.now()-E;this.log(`Challenge solved: nonce=${G.nonce}, iterations=${Y}, time=${Z.toFixed(0)}ms`),this.overlay.showSuccess(),await new Promise((X)=>setTimeout(X,500)),this.overlay.hide(),this.solved=!0,this.solving=!1;let W={solveTimeMs:Z,iterations:Y,difficulty:B,level:A,nonce:G.nonce};this.config.onChallengeComplete?.(W),this.unblockForms()}unblockForms(){if(this.formObserver)this.formObserver.disconnect(),this.formObserver=null;if(this.formHandler)document.querySelectorAll("form").forEach((A)=>{A.removeEventListener("submit",this.formHandler,!0)}),this.formHandler=null;this.log("Forms unblocked"),this.resubmitting=!0,this.pendingForms.forEach((A,B)=>{if(this.log("Resubmitting pending form"),B.requestSubmit)B.requestSubmit();else B.submit()}),this.pendingForms.clear(),this.resubmitting=!1}isSolving(){return this.solving}isSolved(){return this.solved}reset(){if(this.formObserver)this.formObserver.disconnect(),this.formObserver=null;if(this.formHandler)document.querySelectorAll("form").forEach((A)=>{A.removeEventListener("submit",this.formHandler,!0)}),this.formHandler=null;this.solved=!1,this.solving=!1,this.resubmitting=!1,this.pendingForms.clear()}log(...A){if(this.debug)console.log("[BotSigged:Challenge]",...A)}}var qA=g(()=>{b()});var yA={};v(yA,{BotSigged:()=>K});function QA(A){return typeof A==="object"&&A!==null&&"code"in A&&A.code==="LIMIT_EXCEEDED"}var R={endpoint:"wss://botsigged.com/sdk/websocket",debug:!1,sendInterval:2000,maxBufferSize:1000,mouseSampleRate:0.5,autoStart:!0,actionThreshold:70,action:"none",minAlertLevel:"high",botScoreThresholds:{medium:40,high:70,critical:90},hashVerification:{enabled:!1,preferWasm:!0},challenge:{enabled:!1,minLevel:"high",chunkSize:1e4,difficulty:{medium:12,high:16,critical:20},ui:{enabled:!0,message:"Verifying you're human...",successMessage:"Verified!",backgroundColor:"rgba(0, 0, 0, 0.7)",textColor:"#ffffff",spinnerColor:"#3b82f6",zIndex:999999}},formProtection:{mode:"auto",minTimeBeforeSubmit:500,maxHoldTime:3000,showLoadingUI:!0,loadingMessage:"Please wait..."},fallbackMode:"degraded"},EA={action:"none",form_protection_mode:"none"};function IA(A){let B=A.action??R.action,Q=B==="challenge"||A.challenge?.enabled;return{apiKey:A.apiKey,accountId:A.accountId,endpoint:A.endpoint??R.endpoint,debug:A.debug??R.debug,sendInterval:A.sendInterval??R.sendInterval,maxBufferSize:A.maxBufferSize??R.maxBufferSize,mouseSampleRate:A.mouseSampleRate??R.mouseSampleRate,autoStart:A.autoStart??R.autoStart,actionThreshold:A.actionThreshold??R.actionThreshold,action:B,minAlertLevel:A.minAlertLevel??R.minAlertLevel,botScoreThresholds:{...R.botScoreThresholds,...A.botScoreThresholds},hashVerification:{...R.hashVerification,...A.hashVerification},challenge:{enabled:Q,minLevel:A.challenge?.minLevel??R.challenge.minLevel,chunkSize:A.challenge?.chunkSize??R.challenge.chunkSize,difficulty:{...R.challenge.difficulty,...A.challenge?.difficulty},ui:{...R.challenge.ui,...A.challenge?.ui},onChallengeStart:A.challenge?.onChallengeStart,onChallengeComplete:A.challenge?.onChallengeComplete,onChallengeProgress:A.challenge?.onChallengeProgress},formProtection:{mode:A.formProtection?.mode??R.formProtection.mode,minTimeBeforeSubmit:A.formProtection?.minTimeBeforeSubmit??R.formProtection.minTimeBeforeSubmit,maxHoldTime:A.formProtection?.maxHoldTime??R.formProtection.maxHoldTime,showLoadingUI:A.formProtection?.showLoadingUI??R.formProtection.showLoadingUI,loadingMessage:A.formProtection?.loadingMessage??R.formProtection.loadingMessage,onHold:A.formProtection?.onHold,onRelease:A.formProtection?.onRelease,onBlock:A.formProtection?.onBlock},fallbackMode:A.fallbackMode??R.fallbackMode,cookie:A.cookie,headers:A.headers,formInject:A.formInject,onScoreUpdate:A.onScoreUpdate,onConnectionChange:A.onConnectionChange,onError:A.onError,onUsageLimitExceeded:A.onUsageLimitExceeded,onHighBotScore:A.onHighBotScore,onServerConfig:A.onServerConfig,onServerAction:A.onServerAction}}class u{events=[];startTime=0;sampleRate;maxBufferSize;isListening=!1;boundHandleMouseMove;boundHandleMouseDown;boundHandleMouseUp;boundHandleClick;constructor(A={}){this.sampleRate=A.sampleRate??0.5,this.maxBufferSize=A.maxBufferSize??500,this.boundHandleMouseMove=this.handleMouseMove.bind(this),this.boundHandleMouseDown=this.handleMouseDown.bind(this),this.boundHandleMouseUp=this.handleMouseUp.bind(this),this.boundHandleClick=this.handleClick.bind(this)}start(){if(this.isListening)return;this.startTime=Date.now(),document.addEventListener("mousemove",this.boundHandleMouseMove,{passive:!0}),document.addEventListener("mousedown",this.boundHandleMouseDown,{passive:!0}),document.addEventListener("mouseup",this.boundHandleMouseUp,{passive:!0}),document.addEventListener("click",this.boundHandleClick,{passive:!0}),this.isListening=!0}stop(){if(!this.isListening)return;document.removeEventListener("mousemove",this.boundHandleMouseMove),document.removeEventListener("mousedown",this.boundHandleMouseDown),document.removeEventListener("mouseup",this.boundHandleMouseUp),document.removeEventListener("click",this.boundHandleClick),this.isListening=!1}addEvent(A){if(this.events.push(A),this.events.length>this.maxBufferSize)this.events.shift()}handleMouseMove(A){if(Math.random()>this.sampleRate)return;this.addEvent({type:"move",x:A.clientX,y:A.clientY,t:Date.now()})}handleMouseDown(A){this.addEvent({type:"down",x:A.clientX,y:A.clientY,t:Date.now(),button:A.button})}handleMouseUp(A){this.addEvent({type:"up",x:A.clientX,y:A.clientY,t:Date.now(),button:A.button})}handleClick(A){let B=A.target,Q,E;if(B&&B.getBoundingClientRect){let I=B.getBoundingClientRect();Q={top:I.top,left:I.left,width:I.width,height:I.height},E=B.tagName?.toLowerCase()}this.addEvent({type:"click",x:A.clientX,y:A.clientY,t:Date.now(),button:A.button,targetRect:Q,targetTag:E})}getSignal(){return{events:[...this.events],start_time:this.startTime}}flush(){this.events=[]}getBufferSize(){return this.events.length}reset(){this.events=[],this.startTime=Date.now()}}class p{events=[];startTime=0;maxBufferSize;isListening=!1;boundHandleScroll;constructor(A={}){this.maxBufferSize=A.maxBufferSize??200,this.boundHandleScroll=this.handleScroll.bind(this)}start(){if(this.isListening)return;this.startTime=Date.now(),window.addEventListener("scroll",this.boundHandleScroll,{passive:!0}),this.isListening=!0}stop(){if(!this.isListening)return;window.removeEventListener("scroll",this.boundHandleScroll),this.isListening=!1}handleScroll(){if(this.events.push({y:window.scrollY,t:Date.now()}),this.events.length>this.maxBufferSize)this.events.shift()}getSignal(){return{events:[...this.events],start_time:this.startTime}}flush(){this.events=[]}getBufferSize(){return this.events.length}reset(){this.events=[],this.startTime=Date.now()}}class k{static instance=null;timings={signalRoundtrips:[]};pendingSignals=new Map;constructor(){this.timings.scriptStart=performance.now()}static getInstance(){if(!k.instance)k.instance=new k;return k.instance}static reset(){k.instance=null}markScriptStart(){this.timings.scriptStart=performance.now()}markConstructorStart(){this.timings.constructorStart=performance.now()}markConstructorEnd(){this.timings.constructorEnd=performance.now()}markStartCalled(){this.timings.startCalled=performance.now()}markSdkReady(){this.timings.sdkReady=performance.now()}markFingerprintStart(){this.timings.fingerprintStart=performance.now()}markFingerprintEnd(){this.timings.fingerprintEnd=performance.now()}markWsConnectStart(){this.timings.wsConnectStart=performance.now()}markWsConnectEnd(){this.timings.wsConnectEnd=performance.now()}markChannelJoinStart(){this.timings.channelJoinStart=performance.now()}markChannelJoinEnd(){this.timings.channelJoinEnd=performance.now()}markInitialScoreReceived(){this.timings.initialScoreReceived=performance.now()}markFormCollectorStart(){this.timings.formCollectorStart=performance.now()}markFormCollectorReady(){this.timings.formCollectorReady=performance.now()}markFirstFormInteraction(){if(!this.timings.firstFormInteraction){if(this.timings.firstFormInteraction=performance.now(),this.timings.sdkReady)this.timings.timeToFirstInteraction=this.timings.firstFormInteraction-this.timings.sdkReady}}markFirstSubmitAttempt(A){if(!this.timings.firstSubmitAttempt)this.timings.firstSubmitAttempt=performance.now(),this.timings.hadScoreBeforeSubmit=A}markSignalSent(A){this.pendingSignals.set(A,performance.now())}markSignalResponseReceived(A){let B=this.pendingSignals.get(A);if(B!==void 0){let Q=performance.now(),E={sentAt:B,receivedAt:Q,roundtripMs:Q-B,seq:A};this.timings.signalRoundtrips?.push(E),this.pendingSignals.delete(A)}}getTimings(){return{...this.timings}}getSummary(){let A=this.timings,B=A.signalRoundtrips||[],Q=0,E=1/0,I=0;if(B.length>0)Q=B.reduce((H,z)=>H+z.roundtripMs,0)/B.length,E=Math.min(...B.map((H)=>H.roundtripMs)),I=Math.max(...B.map((H)=>H.roundtripMs));let C=(A.sdkReady??0)-(A.scriptStart??0),Y=(A.fingerprintEnd??0)-(A.fingerprintStart??0),G=(A.wsConnectEnd??0)-(A.wsConnectStart??0),Z=(A.channelJoinEnd??0)-(A.channelJoinStart??0),W=(A.initialScoreReceived??0)-(A.startCalled??0),X=(A.initialScoreReceived??0)-(A.scriptStart??0);return{totalStartupMs:Math.round(C),fingerprintMs:Math.round(Y),wsConnectionMs:Math.round(G),channelJoinMs:Math.round(Z),timeToFirstScoreMs:Math.round(W),avgSignalRoundtripMs:Math.round(Q),minSignalRoundtripMs:E===1/0?0:Math.round(E),maxSignalRoundtripMs:Math.round(I),vulnerabilityWindowMs:Math.round(X),protectedBeforeSubmit:A.hadScoreBeforeSubmit??!1}}logSummary(){let A=this.getSummary(),B=this.timings;if(console.group("[BotSigged Performance]"),console.log("=== Startup Timeline ==="),console.log(`Script started at: ${B.scriptStart?.toFixed(2)}ms`),console.log(`Constructor: ${((B.constructorEnd??0)-(B.constructorStart??0)).toFixed(2)}ms`),console.log(`Fingerprint generation: ${A.fingerprintMs}ms`),console.log(`WebSocket connection: ${A.wsConnectionMs}ms`),console.log(`Channel join: ${A.channelJoinMs}ms`),console.log(`Total startup (script → SDK ready): ${A.totalStartupMs}ms`),console.log(`Time to first score: ${A.timeToFirstScoreMs}ms`),console.log(`
2
+ === Signal Roundtrips ===`),console.log(`Average: ${A.avgSignalRoundtripMs}ms`),console.log(`Min: ${A.minSignalRoundtripMs}ms`),console.log(`Max: ${A.maxSignalRoundtripMs}ms`),console.log(`Samples: ${B.signalRoundtrips?.length??0}`),console.log(`
3
+ === Form Interaction ===`),B.firstFormInteraction)console.log(`First interaction at: ${B.firstFormInteraction.toFixed(2)}ms`),console.log(`Time to first interaction: ${B.timeToFirstInteraction?.toFixed(2)}ms`);if(B.firstSubmitAttempt)console.log(`First submit attempt at: ${B.firstSubmitAttempt.toFixed(2)}ms`),console.log(`Had score before submit: ${B.hadScoreBeforeSubmit}`);if(console.log(`
4
+ === Vulnerability Analysis ===`),console.log(`Vulnerability window: ${A.vulnerabilityWindowMs}ms`),console.log(`Protected before submit: ${A.protectedBeforeSubmit}`),A.vulnerabilityWindowMs>0)console.warn(`⚠️ A bot could submit a form within ${A.vulnerabilityWindowMs}ms before the SDK has a detection score.`);console.groupEnd()}getReport(){return{timings:this.timings,summary:this.getSummary(),userAgent:navigator.userAgent,timestamp:Date.now()}}}var J=k.getInstance();function O(){return k.getInstance()}var _="__bs_ghost_value";class m{keyEvents=[];focusEvents=[];pasteEvents=[];inputEvents=[];submitCount=0;startTime=0;maxKeyEvents;maxFocusEvents;maxInputEvents;isListening=!1;valueSetterHooked=!1;onSubmit;originalInputDescriptor;originalTextareaDescriptor;lastKeyWasTab=!1;currentField=null;emailDomains=new Set;boundHandleFocusIn;boundHandleFocusOut;boundHandleKeyDown;boundHandleKeyUp;boundHandlePaste;boundHandleSubmit;boundHandleClick;boundHandleInput;boundHandleGhostValue;constructor(A={}){this.maxKeyEvents=A.maxKeyEvents??500,this.maxFocusEvents=A.maxFocusEvents??100,this.maxInputEvents=A.maxInputEvents??200,this.onSubmit=A.onSubmit,this.boundHandleFocusIn=this.handleFocusIn.bind(this),this.boundHandleFocusOut=this.handleFocusOut.bind(this),this.boundHandleKeyDown=this.handleKeyDown.bind(this),this.boundHandleKeyUp=this.handleKeyUp.bind(this),this.boundHandlePaste=this.handlePaste.bind(this),this.boundHandleSubmit=this.handleSubmit.bind(this),this.boundHandleClick=this.handleClick.bind(this),this.boundHandleInput=this.handleInput.bind(this),this.boundHandleGhostValue=this.handleGhostValue.bind(this)}start(){if(this.isListening)return;this.startTime=Date.now(),document.addEventListener("focusin",this.boundHandleFocusIn,{passive:!0,capture:!0}),document.addEventListener("focusout",this.boundHandleFocusOut,{passive:!0,capture:!0}),document.addEventListener("keydown",this.boundHandleKeyDown,{passive:!0}),document.addEventListener("keyup",this.boundHandleKeyUp,{passive:!0}),document.addEventListener("paste",this.boundHandlePaste,{passive:!0}),document.addEventListener("submit",this.boundHandleSubmit,{passive:!0}),document.addEventListener("click",this.boundHandleClick,{passive:!0}),document.addEventListener("input",this.boundHandleInput,{passive:!0}),document.addEventListener(_,this.boundHandleGhostValue,{passive:!0}),this.hookValueSetters(),this.isListening=!0}stop(){if(!this.isListening)return;document.removeEventListener("focusin",this.boundHandleFocusIn,{capture:!0}),document.removeEventListener("focusout",this.boundHandleFocusOut,{capture:!0}),document.removeEventListener("keydown",this.boundHandleKeyDown),document.removeEventListener("keyup",this.boundHandleKeyUp),document.removeEventListener("paste",this.boundHandlePaste),document.removeEventListener("submit",this.boundHandleSubmit),document.removeEventListener("click",this.boundHandleClick),document.removeEventListener("input",this.boundHandleInput),document.removeEventListener(_,this.boundHandleGhostValue),this.unhookValueSetters(),this.isListening=!1}isFormInput(A){if(!A||!(A instanceof HTMLElement))return!1;let B=A.tagName.toLowerCase();if(B==="textarea"||B==="select")return!0;if(B==="input"){let Q=A.type.toLowerCase();return!["submit","button","reset","hidden","image"].includes(Q)}return!1}isEmailField(A){let B=A.type?.toLowerCase()||"",Q=(A.name||"").toLowerCase(),E=(A.id||"").toLowerCase();return B==="email"||Q.includes("email")||Q.includes("e-mail")||E.includes("email")||E.includes("e-mail")}extractEmailDomain(A){if(!A||typeof A!=="string")return null;let B=A.trim();if(!B)return null;let Q=B.match(/@([a-zA-Z0-9.-]+\.[a-zA-Z]{2,})$/);return Q?Q[1].toLowerCase():null}getFieldId(A){return A.id||A.getAttribute("name")||`field-${A.tagName.toLowerCase()}`}handleFocusIn(A){if(!this.isFormInput(A.target))return;O().markFirstFormInteraction();let B=this.getFieldId(A.target),Q="direct";if(this.lastKeyWasTab)Q="tab";if(this.focusEvents.push({type:"focus",field:B,t:Date.now(),method:Q}),this.focusEvents.length>this.maxFocusEvents)this.focusEvents.shift();this.currentField=B,this.lastKeyWasTab=!1}handleFocusOut(A){if(!this.isFormInput(A.target))return;let B=A.target,Q=this.getFieldId(B);if(this.focusEvents.push({type:"blur",field:Q,t:Date.now()}),this.focusEvents.length>this.maxFocusEvents)this.focusEvents.shift();if(B instanceof HTMLInputElement&&this.isEmailField(B)){let E=this.extractEmailDomain(B.value);if(E)this.emailDomains.add(E)}this.currentField=null}handleClick(A){if(!this.isFormInput(A.target))return;let B=this.focusEvents[this.focusEvents.length-1];if(B&&B.type==="focus"&&Date.now()-B.t<50)B.method="click"}handleKeyDown(A){if(A.key==="Tab"){this.lastKeyWasTab=!0;return}if(!this.isFormInput(A.target))return;let B="key";if(A.key==="Backspace")B="backspace";else if(A.key==="Delete")B="delete";else if(A.key==="Enter")B="enter";else if(A.key==="Tab")B="tab";else if(A.key.length===1)B="char";else if(A.key.startsWith("Arrow"))B="arrow";if(this.keyEvents.push({type:"down",code:B,t:Date.now(),field:this.currentField||void 0}),this.keyEvents.length>this.maxKeyEvents)this.keyEvents.shift()}handleKeyUp(A){if(!this.isFormInput(A.target))return;let B="key";if(A.key==="Backspace")B="backspace";else if(A.key==="Delete")B="delete";else if(A.key.length===1)B="char";if(this.keyEvents.push({type:"up",code:B,t:Date.now(),field:this.currentField||void 0}),this.keyEvents.length>this.maxKeyEvents)this.keyEvents.shift()}getFieldType(A){let B=A.tagName.toLowerCase();if(B==="textarea")return"textarea";if(B==="select")return"select";if(B==="input")return A.type?.toLowerCase()||"text";return"unknown"}handleInput(A){if(!this.isFormInput(A.target))return;let B=A.target,E=A.inputType||"unknown",I=B.value?.length??0,C=this.getFieldType(B);if(this.inputEvents.push({field:this.getFieldId(B),t:Date.now(),inputType:E,valueLength:I,fieldType:C}),this.inputEvents.length>this.maxInputEvents)this.inputEvents.shift()}handlePaste(A){if(!this.isFormInput(A.target))return;let B=A.clipboardData?.getData("text")||"";this.pasteEvents.push({field:this.getFieldId(A.target),t:Date.now(),length:B.length})}handleSubmit(A){this.submitCount++;let B=A.target;if(B&&B.elements)for(let Q=0;Q<B.elements.length;Q++){let E=B.elements[Q];if(E instanceof HTMLInputElement&&this.isEmailField(E)){let I=this.extractEmailDomain(E.value);if(I)this.emailDomains.add(I)}}this.onSubmit?.()}getSignal(){return{keys:[...this.keyEvents],focus:[...this.focusEvents],pastes:[...this.pasteEvents],inputs:[...this.inputEvents],submits:this.submitCount,start_time:this.startTime,email_domains:this.emailDomains.size>0?Array.from(this.emailDomains):void 0}}flush(){this.keyEvents=[],this.focusEvents=[],this.pasteEvents=[],this.inputEvents=[]}getBufferSize(){return this.keyEvents.length+this.focusEvents.length+this.pasteEvents.length+this.inputEvents.length}reset(){this.keyEvents=[],this.focusEvents=[],this.pasteEvents=[],this.inputEvents=[],this.submitCount=0,this.startTime=Date.now(),this.lastKeyWasTab=!1,this.currentField=null,this.emailDomains.clear()}hookValueSetters(){if(this.valueSetterHooked)return;if(console.log("[BotSigged] Hooking value setters for ghost fill detection"),this.originalInputDescriptor=Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,"value"),console.log("[BotSigged] Input descriptor:",!!this.originalInputDescriptor),this.originalInputDescriptor){let A=this.originalInputDescriptor.set,B=this.originalInputDescriptor.get;Object.defineProperty(HTMLInputElement.prototype,"value",{configurable:!0,enumerable:!0,get(){return B?.call(this)},set(Q){let E=B?.call(this)??"";A?.call(this,Q);let I=Q??"";if(console.log("[BotSigged] Input.value set:",{oldLen:E.length,newLen:I.length,changed:I!==E}),I!==E)console.log("[BotSigged] Dispatching ghost value event"),this.dispatchEvent(new CustomEvent(_,{bubbles:!0,detail:{valueLength:I.length,wasEmpty:E.length===0}}))}})}if(this.originalTextareaDescriptor=Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,"value"),this.originalTextareaDescriptor){let A=this.originalTextareaDescriptor.set,B=this.originalTextareaDescriptor.get;Object.defineProperty(HTMLTextAreaElement.prototype,"value",{configurable:!0,enumerable:!0,get(){return B?.call(this)},set(Q){let E=B?.call(this)??"";A?.call(this,Q);let I=Q??"";if(I!==E)this.dispatchEvent(new CustomEvent(_,{bubbles:!0,detail:{valueLength:I.length,wasEmpty:E.length===0}}))}})}this.valueSetterHooked=!0}unhookValueSetters(){if(!this.valueSetterHooked)return;if(this.originalInputDescriptor)Object.defineProperty(HTMLInputElement.prototype,"value",this.originalInputDescriptor);if(this.originalTextareaDescriptor)Object.defineProperty(HTMLTextAreaElement.prototype,"value",this.originalTextareaDescriptor);this.valueSetterHooked=!1}handleGhostValue(A){console.log("[BotSigged] handleGhostValue called",A.target);let B=A.target;if(!this.isFormInput(B)){console.log("[BotSigged] handleGhostValue: not a form input");return}let E=A.detail?.valueLength??0,I=this.getFieldType(B);if(console.log("[BotSigged] Recording ghost fill:",{field:this.getFieldId(B),valueLength:E,fieldType:I}),this.inputEvents.push({field:this.getFieldId(B),t:Date.now(),inputType:"programmatic",valueLength:E,fieldType:I}),this.inputEvents.length>this.maxInputEvents)this.inputEvents.shift()}}class d{cachedSignal=null;collect(){if(this.cachedSignal)return this.cachedSignal;let A=navigator,B=window;return this.cachedSignal={user_agent:navigator.userAgent,platform:navigator.platform,language:navigator.language,languages:[...navigator.languages||[]],hardware_concurrency:navigator.hardwareConcurrency??null,device_memory:A.deviceMemory??null,max_touch_points:navigator.maxTouchPoints??0,screen_width:screen.width,screen_height:screen.height,screen_avail_width:screen.availWidth,screen_avail_height:screen.availHeight,color_depth:screen.colorDepth,pixel_ratio:window.devicePixelRatio??1,...this.getWebGLInfo(),plugins_count:navigator.plugins?.length??0,mime_types_count:navigator.mimeTypes?.length??0,timezone:this.getTimezone(),timezone_offset:new Date().getTimezoneOffset(),has_webdriver:A.webdriver===!0,has_chrome_runtime:!!B.chrome?.runtime,has_chrome_app:!!B.chrome?.app,has_notification_api:"Notification"in window,has_permissions_api:"permissions"in navigator,outer_dimensions:{width:window.outerWidth,height:window.outerHeight},inner_dimensions:{width:window.innerWidth,height:window.innerHeight},notification_permission:this.getNotificationPermission()},this.cachedSignal}getWebGLInfo(){try{let A=document.createElement("canvas"),B=A.getContext("webgl")||A.getContext("experimental-webgl");if(!B||!(B instanceof WebGLRenderingContext))return{webgl_vendor:null,webgl_renderer:null};let Q=B.getExtension("WEBGL_debug_renderer_info");if(!Q)return{webgl_vendor:null,webgl_renderer:null};return{webgl_vendor:B.getParameter(Q.UNMASKED_VENDOR_WEBGL),webgl_renderer:B.getParameter(Q.UNMASKED_RENDERER_WEBGL)}}catch{return{webgl_vendor:null,webgl_renderer:null}}}getTimezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return null}}getNotificationPermission(){if("Notification"in window)return Notification.permission;return null}getSignal(){return this.collect()}reset(){this.cachedSignal=null}}b();class s{cachedFingerprint=null;async generate(){if(this.cachedFingerprint)return this.cachedFingerprint;let[A,B,Q,E,I]=await Promise.all([this.getCanvasHash(),this.getWebGLData(),this.getAudioHash(),this.getFontData(),this.getScreenHash()]),C={hash:"",canvas_hash:A,webgl_hash:B.hash,audio_hash:Q,font_hash:E.hash,screen_hash:I,webgl_vendor:B.vendor,webgl_renderer:B.renderer,timezone:this.getTimezone(),language:this.getLanguage(),platform:this.getPlatform(),font_count:E.count};return C.hash=await this.generateMainHash(C),this.cachedFingerprint=C,C}getFingerprint(){return this.cachedFingerprint}reset(){this.cachedFingerprint=null}async getCanvasHash(){try{let A=document.createElement("canvas");A.width=200,A.height=50;let B=A.getContext("2d");if(!B)return null;B.textBaseline="top",B.font="14px 'Arial'",B.fillStyle="#f60",B.fillRect(125,1,62,20),B.fillStyle="#069",B.fillText("BotSigged,\uD83C\uDFA8",2,15),B.fillStyle="rgba(102, 204, 0, 0.7)",B.fillText("BotSigged,\uD83C\uDFA8",4,17);let Q=A.toDataURL();return this.hashString(Q)}catch{return null}}async getWebGLData(){try{let A=document.createElement("canvas"),B=A.getContext("webgl")||A.getContext("experimental-webgl");if(!B||!(B instanceof WebGLRenderingContext))return{hash:null,vendor:null,renderer:null};let Q=[],E=[B.ALIASED_LINE_WIDTH_RANGE,B.ALIASED_POINT_SIZE_RANGE,B.ALPHA_BITS,B.BLUE_BITS,B.DEPTH_BITS,B.GREEN_BITS,B.MAX_COMBINED_TEXTURE_IMAGE_UNITS,B.MAX_CUBE_MAP_TEXTURE_SIZE,B.MAX_FRAGMENT_UNIFORM_VECTORS,B.MAX_RENDERBUFFER_SIZE,B.MAX_TEXTURE_IMAGE_UNITS,B.MAX_TEXTURE_SIZE,B.MAX_VARYING_VECTORS,B.MAX_VERTEX_ATTRIBS,B.MAX_VERTEX_TEXTURE_IMAGE_UNITS,B.MAX_VERTEX_UNIFORM_VECTORS,B.MAX_VIEWPORT_DIMS,B.RED_BITS,B.RENDERER,B.SHADING_LANGUAGE_VERSION,B.STENCIL_BITS,B.VENDOR,B.VERSION];for(let W of E)try{let X=B.getParameter(W);Q.push(String(X))}catch{Q.push("")}let I=B.getSupportedExtensions();if(I)Q.push(I.sort().join(","));let C=null,Y=null,G=B.getExtension("WEBGL_debug_renderer_info");if(G)C=B.getParameter(G.UNMASKED_VENDOR_WEBGL),Y=B.getParameter(G.UNMASKED_RENDERER_WEBGL);return{hash:this.hashString(Q.join("|")),vendor:C,renderer:Y}}catch{return{hash:null,vendor:null,renderer:null}}}async getAudioHash(){try{let A=window.OfflineAudioContext||window.webkitOfflineAudioContext;if(!A)return null;let B=new A(1,4500,44100),Q=B.createOscillator(),E=B.createDynamicsCompressor();Q.type="triangle",Q.frequency.setValueAtTime(1e4,B.currentTime),E.threshold.setValueAtTime(-50,B.currentTime),E.knee.setValueAtTime(40,B.currentTime),E.ratio.setValueAtTime(12,B.currentTime),E.attack.setValueAtTime(0,B.currentTime),E.release.setValueAtTime(0.25,B.currentTime),Q.connect(E),E.connect(B.destination),Q.start(0);let C=(await B.startRendering()).getChannelData(0),Y=[];for(let G=0;G<C.length;G+=100)Y.push(C[G]);return this.hashString(Y.join(","))}catch{return null}}async getFontData(){let A=["Arial","Arial Black","Arial Narrow","Calibri","Cambria","Cambria Math","Comic Sans MS","Consolas","Courier","Courier New","Georgia","Helvetica","Impact","Lucida Console","Lucida Sans Unicode","Microsoft Sans Serif","MS Gothic","MS PGothic","MS Sans Serif","MS Serif","Palatino Linotype","Segoe Print","Segoe Script","Segoe UI","Symbol","Tahoma","Times","Times New Roman","Trebuchet MS","Verdana","Wingdings"],B=["monospace","sans-serif","serif"],Q="mmmmmmmmmmlli",E="72px",I=document.createElement("span");I.style.position="absolute",I.style.left="-9999px",I.style.fontSize="72px",I.style.lineHeight="normal",I.innerHTML="mmmmmmmmmmlli",document.body.appendChild(I);let C={};for(let Z of B)I.style.fontFamily=Z,C[Z]=I.offsetWidth;let Y=[];for(let Z of A){let W=!1;for(let X of B)if(I.style.fontFamily=`'${Z}', ${X}`,I.offsetWidth!==C[X]){W=!0;break}if(W)Y.push(Z)}return document.body.removeChild(I),{hash:this.hashString(Y.join(",")),count:Y.length}}async getScreenHash(){let A=[String(screen.width),String(screen.height),String(screen.availWidth),String(screen.availHeight),String(screen.colorDepth),String(screen.pixelDepth),String(window.devicePixelRatio||1)];return this.hashString(A.join("|"))}getTimezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone}catch{return null}}getLanguage(){return navigator.language||null}getPlatform(){return navigator.platform||null}generateMainHash(A){let B=[A.canvas_hash||"",A.webgl_hash||"",A.audio_hash||"",A.font_hash||"",A.screen_hash||"",A.timezone||"",A.language||"",A.platform||""];return this.hashString(B.join("|"))}hashString(A){return i(A)}}class n{ws=null;endpoint;apiKey;heartbeatInterval;reconnectAttempts;reconnectDelay;debug;state="disconnected";channelState="closed";refCounter=0;joinRef=null;heartbeatTimer=null;reconnectTimer=null;reconnectCount=0;pendingReplies=new Map;onConnectionChange;onError;channelCallbacks={};topic=null;constructor(A){this.endpoint=A.endpoint,this.apiKey=A.apiKey,this.heartbeatInterval=A.heartbeatInterval??30000,this.reconnectAttempts=A.reconnectAttempts??10,this.reconnectDelay=A.reconnectDelay??((B)=>Math.min(1000*Math.pow(2,B),30000)),this.debug=A.debug??!1,this.onConnectionChange=A.onConnectionChange,this.onError=A.onError}connect(){return new Promise((A,B)=>{if(this.ws&&this.state==="connected"){A();return}this.setState("connecting");let Q=this.buildUrl();this.log("Connecting to",Q);try{this.ws=new WebSocket(Q),this.ws.onopen=()=>{this.log("WebSocket connected"),this.setState("connected"),this.reconnectCount=0,this.startHeartbeat(),A()},this.ws.onclose=(E)=>{this.log("WebSocket closed",E.code,E.reason),this.handleClose()},this.ws.onerror=(E)=>{this.log("WebSocket error",E);let I=Error("WebSocket connection error");this.handleError(I),B(I)},this.ws.onmessage=(E)=>{this.handleMessage(E.data)}}catch(E){let I=E instanceof Error?E:Error(String(E));this.handleError(I),B(I)}})}disconnect(){if(this.stopHeartbeat(),this.stopReconnect(),this.ws)this.ws.close(1000,"Client disconnect"),this.ws=null;this.setState("disconnected"),this.setChannelState("closed")}joinChannel(A,B,Q,E,I={},C){return this.channelCallbacks=I,this.topic=`detection:${A}`,new Promise((Y,G)=>{if(this.state!=="connected"){G(Error("WebSocket not connected"));return}this.setChannelState("joining"),this.joinRef=this.makeRef();let Z={session_id:A,api_key:this.apiKey,fingerprint:B,session:Q,browser:E};if(C)Z.account_id=C;this.push("phx_join",Z,this.joinRef).then((W)=>{this.log("Channel joined",W),this.setChannelState("joined"),this.channelCallbacks.onJoin?.(),Y(W)}).catch((W)=>{this.log("Channel join failed",W),this.setChannelState("error"),this.channelCallbacks.onError?.(W),G(W)})})}leaveChannel(){return new Promise((A,B)=>{if(this.channelState!=="joined"){A();return}this.setChannelState("leaving"),this.push("phx_leave",{}).then(()=>{this.log("Channel left"),this.setChannelState("closed"),this.joinRef=null,this.topic=null,this.channelCallbacks.onLeave?.(),A()}).catch((Q)=>{this.setChannelState("error"),B(Q)})})}sendSignal(A){if(this.channelState!=="joined")return Promise.reject(Error("Channel not joined"));return this.push("signal",A)}sendFormStatus(A){if(this.channelState!=="joined")return Promise.reject(Error("Channel not joined"));return this.push("form_status",{status:A})}sendEvent(A,B){if(this.channelState!=="joined")return Promise.reject(Error("Channel not joined"));return this.push(A,B)}getState(){return this.state}getChannelState(){return this.channelState}isReady(){return this.state==="connected"&&this.channelState==="joined"}buildUrl(){let A=new URL(this.endpoint);return A.searchParams.set("vsn","2.0.0"),A.searchParams.set("api_key",this.apiKey),A.toString()}makeRef(){return this.refCounter++,String(this.refCounter)}push(A,B,Q){return new Promise((E,I)=>{if(!this.ws||this.ws.readyState!==WebSocket.OPEN){I(Error("WebSocket not open"));return}if(!this.topic){I(Error("Channel topic not set"));return}let C=Q??this.makeRef(),Y=[this.joinRef,C,this.topic,A,B],G=setTimeout(()=>{this.pendingReplies.delete(C),I(Error(`Timeout waiting for reply to ${A}`))},1e4);this.pendingReplies.set(C,{resolve:E,reject:I,timeout:G}),this.log("Sending",A,B),this.ws.send(JSON.stringify(Y))})}handleMessage(A){try{let[B,Q,E,I,C]=JSON.parse(A);if(this.log("Received",I,C),I==="phx_reply"&&Q){let Y=this.pendingReplies.get(Q);if(Y){clearTimeout(Y.timeout),this.pendingReplies.delete(Q);let G=C;if(G.status==="ok")Y.resolve(G.response??{});else if(G.response&&typeof G.response==="object"&&"code"in G.response)Y.reject(G.response);else{let Z=this.buildErrorMessage(G.status,G.response);Y.reject(Error(Z))}}return}if(I==="phx_error"){let Y=Error("Channel error");this.setChannelState("error"),this.channelCallbacks.onError?.(Y);return}if(I==="phx_close"){this.setChannelState("closed"),this.channelCallbacks.onLeave?.();return}if(I==="score_update"){this.channelCallbacks.onScoreUpdate?.(C);return}if(I==="action"){this.channelCallbacks.onAction?.(C);return}this.channelCallbacks.onMessage?.(I,C)}catch(B){this.log("Error parsing message",B)}}handleClose(){this.stopHeartbeat(),this.setState("disconnected"),this.setChannelState("closed");for(let[A,B]of this.pendingReplies)clearTimeout(B.timeout),B.reject(Error("Connection closed"));this.pendingReplies.clear(),this.scheduleReconnect()}handleError(A){this.setState("error"),this.onError?.(A)}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{if(this.ws&&this.ws.readyState===WebSocket.OPEN){let A=[null,this.makeRef(),"phoenix","heartbeat",{}];if(this.ws.send(JSON.stringify(A)),this.channelState==="joined")this.push("heartbeat",{}).then((B)=>{if(B.bot_score!==void 0)this.channelCallbacks.onScoreUpdate?.({bot_score:B.bot_score,classification:B.classification,triggered_rules:[],event_count:0})}).catch(()=>{})}},this.heartbeatInterval)}stopHeartbeat(){if(this.heartbeatTimer)clearInterval(this.heartbeatTimer),this.heartbeatTimer=null}scheduleReconnect(){if(this.reconnectCount>=this.reconnectAttempts){this.log("Max reconnect attempts reached");return}let A=this.reconnectDelay(this.reconnectCount);this.reconnectCount++,this.log(`Scheduling reconnect attempt ${this.reconnectCount} in ${A}ms`),this.reconnectTimer=setTimeout(()=>{this.connect().catch((B)=>{this.log("Reconnect failed",B)})},A)}stopReconnect(){if(this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;this.reconnectCount=0}setState(A){if(this.state!==A)this.state=A,this.onConnectionChange?.(A)}setChannelState(A){this.channelState=A}buildErrorMessage(A,B){if(B){if(typeof B.reason==="string")return`Channel error: ${B.reason}`;if(Object.keys(B).length>0)return`Channel error (${A??"error"}): ${JSON.stringify(B)}`}return A??"Unknown error"}log(...A){if(this.debug)console.log("[BotSigged]",...A)}}class t{config;isReady=!1;hasScore=!1;hasFormScore=!1;currentScore=null;pendingSubmissions=[];pendingRequests=[];protectedForms=new Set;releasingForms=new Set;loadingOverlay=null;formObserver=null;startTime;originalFetch=null;originalXHROpen=null;originalXHRSend=null;constructor(A={}){if(this.startTime=performance.now(),this.config={mode:A.mode??"none",minTimeBeforeSubmit:A.minTimeBeforeSubmit??500,maxHoldTime:A.maxHoldTime??5000,showLoadingUI:A.showLoadingUI??!0,loadingMessage:A.loadingMessage??"Please wait...",onHold:A.onHold,onRelease:A.onRelease,onBlock:A.onBlock,flushAndWaitForScore:A.flushAndWaitForScore},this.config.mode!=="none")this.setup()}setup(){if(console.log("[BotSigged] Setting up form protection, mode:",this.config.mode),this.config.mode==="auto")this.interceptFetch(),this.interceptXHR();let A=()=>{document.querySelectorAll("form").forEach((B)=>{this.protectForm(B)}),this.formObserver=new MutationObserver((B)=>{B.forEach((Q)=>{Q.addedNodes.forEach((E)=>{if(E instanceof HTMLFormElement)this.protectForm(E);if(E instanceof HTMLElement)E.querySelectorAll("form").forEach((I)=>{this.protectForm(I)})})})}),this.formObserver.observe(document.body,{childList:!0,subtree:!0})};if(document.body)A();else document.addEventListener("DOMContentLoaded",A,{once:!0})}isFormLikeRequest(A,B){if((B?.method?.toUpperCase()||"GET")!=="POST")return!1;try{if((typeof A==="string"?new URL(A,window.location.origin):A instanceof URL?A:new URL(A.url)).origin!==window.location.origin)return!1}catch{return!1}let E=B?.headers instanceof Headers?B.headers.get("content-type"):typeof B?.headers==="object"&&B.headers!==null?B.headers["content-type"]||B.headers["Content-Type"]:null;if(E){let I=E.toLowerCase();if(I.includes("application/x-www-form-urlencoded")||I.includes("multipart/form-data")||I.includes("application/json"))return!0;return!1}if(B?.body)return!0;return!1}interceptFetch(){this.originalFetch=window.fetch.bind(window);let A=this;window.fetch=async function(B,Q){if(!A.isFormLikeRequest(B,Q))return A.originalFetch(B,Q);if(A.hasScore)return A.originalFetch(B,Q);return console.log("[BotSigged] Holding form submission until score ready"),new Promise((E,I)=>{let C={resolve:E,reject:I,execute:()=>A.originalFetch(B,Q),timestamp:performance.now()};if(A.pendingRequests.push(C),A.config.showLoadingUI&&A.pendingRequests.length===1)A.showLoading(document.createElement("form"));if(setTimeout(()=>{if(A.pendingRequests.includes(C))console.warn("[BotSigged] Request hold timeout, releasing"),A.releaseRequest(C)},A.config.maxHoldTime),A.hasScore)A.releaseRequest(C)})},console.log("[BotSigged] fetch() intercepted (same-origin form submissions only)")}interceptXHR(){this.originalXHROpen=XMLHttpRequest.prototype.open,this.originalXHRSend=XMLHttpRequest.prototype.send;let A=this;XMLHttpRequest.prototype.open=function(B,Q,E=!0,I,C){let Y=this;return Y._bsMethod=B.toUpperCase(),Y._bsUrl=Q.toString(),A.originalXHROpen.call(this,B,Q,E,I,C)},XMLHttpRequest.prototype.send=function(B){let Q=this,E=Q._bsMethod||"GET",I=Q._bsUrl||"";if(E!=="POST")return A.originalXHRSend.call(this,B);try{if(new URL(I,window.location.origin).origin!==window.location.origin)return A.originalXHRSend.call(this,B)}catch{return A.originalXHRSend.call(this,B)}if(A.hasScore)return A.originalXHRSend.call(this,B);console.log("[BotSigged] Holding XHR form submission until score ready");let C=performance.now(),Y=()=>{if(A.hasScore){if(A.config.showLoadingUI)A.hideLoading();A.originalXHRSend.call(Q,B)}else if(performance.now()-C>=A.config.maxHoldTime){if(console.warn("[BotSigged] XHR hold timeout, releasing"),A.config.showLoadingUI)A.hideLoading();A.originalXHRSend.call(Q,B)}else setTimeout(Y,50)};if(A.config.showLoadingUI)A.showLoading(document.createElement("form"));Y()},console.log("[BotSigged] XMLHttpRequest intercepted (same-origin POST only)")}releaseRequest(A){let B=this.pendingRequests.indexOf(A);if(B===-1)return;if(this.pendingRequests.splice(B,1),this.pendingRequests.length===0&&this.config.showLoadingUI)this.hideLoading();A.execute().then(A.resolve).catch(A.reject)}protectForm(A){if(this.protectedForms.has(A))return;this.protectedForms.add(A),A.addEventListener("submit",(B)=>this.handleSubmit(B,A),{capture:!0})}handleSubmit(A,B){if(this.releasingForms.has(B)){console.log("[BotSigged FormProtection] Form is being released, allowing through"),this.releasingForms.delete(B);return}let E=performance.now()-this.startTime;switch(console.log("[BotSigged FormProtection] Submit intercepted",{mode:this.config.mode,timeSinceStart:E,isReady:this.isReady,hasScore:this.hasScore}),O().markFirstSubmitAttempt(this.hasScore),this.config.mode){case"holdUntilReady":if(!this.hasScore)A.preventDefault(),A.stopPropagation(),this.holdSubmission(B,A);break;case"holdUntilFormScored":A.preventDefault(),A.stopPropagation(),this.holdAndScoreSubmission(B,A);break;case"blockInstant":if(E<this.config.minTimeBeforeSubmit)A.preventDefault(),A.stopPropagation(),console.warn(`[BotSigged] Blocked instant submission (${E.toFixed(0)}ms < ${this.config.minTimeBeforeSubmit}ms threshold)`),this.config.onBlock?.(B,"instant_submission");break;case"challengeFirst":if(!this.hasScore)A.preventDefault(),A.stopPropagation(),this.holdSubmission(B,A);break;case"none":default:break}}holdSubmission(A,B){if(console.log("[BotSigged FormProtection] Holding submission"),this.config.onHold?.(A),this.config.showLoadingUI)this.showLoading(A);let Q={form:A,event:B,timestamp:performance.now(),resolver:()=>{},rejecter:()=>{}},E=new Promise((I,C)=>{Q.resolver=I,Q.rejecter=C});if(this.pendingSubmissions.push(Q),setTimeout(()=>{if(this.pendingSubmissions.includes(Q))console.warn("[BotSigged] Hold timeout reached, releasing submission"),this.releaseSubmission(Q,!1)},this.config.maxHoldTime),this.hasScore)this.releaseSubmission(Q,!1);E.catch(()=>{})}async holdAndScoreSubmission(A,B){if(console.log("[BotSigged FormProtection] Holding submission for form scoring"),this.config.onHold?.(A),this.config.showLoadingUI)this.showLoading(A);let Q=performance.now();try{if(!this.config.flushAndWaitForScore){console.warn("[BotSigged] holdUntilFormScored mode requires flushAndWaitForScore callback"),this.submitForm(A);return}console.log("[BotSigged FormProtection] Flushing signals and waiting for score...");let E=this.config.flushAndWaitForScore(),I=new Promise((G)=>{setTimeout(()=>G(null),this.config.maxHoldTime)}),C=await Promise.race([E,I]),Y=performance.now()-Q;if(C===null)console.warn(`[BotSigged FormProtection] Timeout waiting for form score after ${Y.toFixed(0)}ms, releasing`);else console.log(`[BotSigged FormProtection] Form scored: ${C} in ${Y.toFixed(0)}ms`),this.currentScore=C,this.hasFormScore=!0;if(this.config.showLoadingUI)this.hideLoading();this.config.onRelease?.(A,!1),this.submitForm(A)}catch(E){if(console.error("[BotSigged FormProtection] Error during form scoring:",E),this.config.showLoadingUI)this.hideLoading();this.config.onRelease?.(A,!1),this.submitForm(A)}}submitForm(A){if(this.releasingForms.add(A),A.requestSubmit)A.requestSubmit();else A.submit()}releaseSubmission(A,B){let Q=this.pendingSubmissions.indexOf(A);if(Q===-1)return;if(this.pendingSubmissions.splice(Q,1),this.config.showLoadingUI)this.hideLoading();if(this.config.onRelease?.(A.form,B),!B)if(console.log("[BotSigged FormProtection] Releasing held submission"),A.resolver(),A.form.requestSubmit)A.form.requestSubmit();else A.form.submit();else A.rejecter("blocked")}showLoading(A){if(this.loadingOverlay)return;this.loadingOverlay=document.createElement("div"),this.loadingOverlay.innerHTML=`
44
5
  <div style="
45
6
  position: fixed;
46
7
  top: 0;
@@ -79,4 +40,4 @@
79
40
  to { transform: rotate(360deg); }
80
41
  }
81
42
  </style>
82
- `,document.body.appendChild(this.loadingOverlay)}hideLoading(){if(this.loadingOverlay)this.loadingOverlay.remove(),this.loadingOverlay=null}notifyReady(A){this.isReady=!0,this.hasScore=!0,this.currentScore=A,[...this.pendingSubmissions].forEach((E)=>{this.releaseSubmission(E,!1)}),[...this.pendingRequests].forEach((E)=>{this.releaseRequest(E)}),this.hideLoading()}blockAllPending(A){[...this.pendingSubmissions].forEach((Q)=>{this.config.onBlock?.(Q.form,A),this.releaseSubmission(Q,!0)})}getStatus(){return{mode:this.config.mode,isReady:this.isReady,hasScore:this.hasScore,pendingCount:this.pendingSubmissions.length,protectedFormCount:this.protectedForms.size}}waitUntilReady(){if(this.hasScore)return Promise.resolve({score:this.currentScore,timedOut:!1});return new Promise((A)=>{let B=performance.now(),Q=()=>{if(this.hasScore){A({score:this.currentScore,timedOut:!1});return}if(performance.now()-B>=this.config.maxHoldTime){A({score:null,timedOut:!0});return}setTimeout(Q,50)};Q()})}withProtection(A){return async(...B)=>{let Q=performance.now()-this.startTime;if(O().markFirstSubmitAttempt(this.hasScore),this.config.mode==="blockInstant"&&Q<this.config.minTimeBeforeSubmit)throw this.config.onBlock?.(document.createElement("form"),"instant_submission"),Error("Submission blocked: too fast");if(this.config.mode==="holdUntilReady"&&!this.hasScore){if(this.config.showLoadingUI)this.showLoading(document.createElement("form"));let{timedOut:E}=await this.waitUntilReady();if(this.config.showLoadingUI)this.hideLoading()}return A(...B)}}protectedFetch(){return this.withProtection(async(A,B)=>{return fetch(A,B)})}setMode(A){if(this.config.mode=A,A==="none")[...this.pendingSubmissions].forEach((Q)=>this.releaseSubmission(Q,!1))}setMaxHoldTime(A){this.config.maxHoldTime=A}canSubmit(){let A=performance.now()-this.startTime;if(this.config.mode==="blockInstant"&&A<this.config.minTimeBeforeSubmit)return{allowed:!1,reason:"too_fast",score:this.currentScore};if(this.config.mode==="holdUntilReady"&&!this.hasScore)return{allowed:!1,reason:"waiting_for_score",score:null};return{allowed:!0,score:this.currentScore}}destroy(){if(this.formObserver)this.formObserver.disconnect(),this.formObserver=null;if(this.originalFetch)window.fetch=this.originalFetch,this.originalFetch=null;if(this.originalXHROpen)XMLHttpRequest.prototype.open=this.originalXHROpen,this.originalXHROpen=null;if(this.originalXHRSend)XMLHttpRequest.prototype.send=this.originalXHRSend,this.originalXHRSend=null;this.hideLoading(),this.pendingSubmissions=[],this.pendingRequests=[],this.protectedForms.clear()}}var ZA={suspicious:40,bot:70},V={name:"_bsid",riskName:"_bsrisk",path:"/",sameSite:"Strict"};function XA(A){if(!A)return null;if(A===!0)return{...V};return{...V,...A}}function jA(A){if(A>=ZA.bot)return"bot";if(A>=ZA.suspicious)return"suspicious";return"human"}class r{config;sessionIdGetter;sessionCookieSet=!1;currentRiskTier=null;constructor(A,B){this.config={...V,...A},this.sessionIdGetter=B}buildCookieString(A,B){let Q=this.config.path||V.path,E=this.config.sameSite||V.sameSite,I=this.config.secure??location.protocol==="https:",C=[`${encodeURIComponent(A)}=${encodeURIComponent(B)}`,`Path=${Q}`,`SameSite=${E}`];if(I||E==="None")C.push("Secure");return C.join("; ")}deleteCookie(A){let B=this.config.path||V.path;document.cookie=`${encodeURIComponent(A)}=; Path=${B}; Max-Age=0`}setSessionCookie(){if(this.sessionCookieSet)return;let A=this.sessionIdGetter();if(!A)return;let B=this.config.name||V.name;document.cookie=this.buildCookieString(B,A),this.sessionCookieSet=!0}updateRiskTier(A){let B=jA(A);if(B===this.currentRiskTier)return!1;let Q=this.config.riskName||V.riskName;document.cookie=this.buildCookieString(Q,B);let E=this.currentRiskTier;return this.currentRiskTier=B,!0}removeCookies(){let A=this.config.name||V.name,B=this.config.riskName||V.riskName;if(this.sessionCookieSet)this.deleteCookie(A),this.sessionCookieSet=!1;if(this.currentRiskTier!==null)this.deleteCookie(B),this.currentRiskTier=null}setCookie(){this.setSessionCookie()}removeCookie(){this.removeCookies()}isSessionCookieSet(){return this.sessionCookieSet}getCurrentRiskTier(){return this.currentRiskTier}getSessionCookieName(){return this.config.name||V.name}getRiskCookieName(){return this.config.riskName||V.riskName}}var F={name:"X-BotSigged-ID"};function RA(A){if(!A)return null;if(A===!0)return{...F};return{...F,...A}}class o{config;sessionIdGetter;started=!1;originalFetch=null;originalXHROpen=null;originalXHRSend=null;originalXHRSetRequestHeader=null;xhrInjectionMap=new WeakMap;constructor(A,B){this.config={...F,...A},this.sessionIdGetter=B}start(){if(this.started)return;this.started=!0,this.patchFetch(),this.patchXHR()}stop(){if(!this.started)return;if(this.originalFetch)window.fetch=this.originalFetch,this.originalFetch=null;if(this.originalXHROpen)XMLHttpRequest.prototype.open=this.originalXHROpen,this.originalXHROpen=null;if(this.originalXHRSend)XMLHttpRequest.prototype.send=this.originalXHRSend,this.originalXHRSend=null;if(this.originalXHRSetRequestHeader)XMLHttpRequest.prototype.setRequestHeader=this.originalXHRSetRequestHeader,this.originalXHRSetRequestHeader=null;this.started=!1}isSameOrigin(A){try{let B;if(A instanceof Request)B=new URL(A.url,window.location.origin);else if(A instanceof URL)B=A;else B=new URL(A,window.location.origin);return B.origin===window.location.origin}catch{return!0}}patchFetch(){this.originalFetch=window.fetch.bind(window);let A=this,B=this.config.name||F.name;window.fetch=function(Q,E){if(!A.isSameOrigin(Q))return A.originalFetch(Q,E);let I=A.sessionIdGetter();if(!I)return A.originalFetch(Q,E);let C=new Headers(E?.headers);if(!C.has(B))C.set(B,I);return A.originalFetch(Q,{...E,headers:C})}}patchXHR(){this.originalXHROpen=XMLHttpRequest.prototype.open,this.originalXHRSend=XMLHttpRequest.prototype.send,this.originalXHRSetRequestHeader=XMLHttpRequest.prototype.setRequestHeader;let A=this,B=this.config.name||F.name;XMLHttpRequest.prototype.open=function(Q,E,I=!0,C,Y){let G=A.isSameOrigin(E);return A.xhrInjectionMap.set(this,G),A.originalXHROpen.call(this,Q,E,I,C,Y)},XMLHttpRequest.prototype.send=function(Q){if(A.xhrInjectionMap.get(this)){let E=A.sessionIdGetter();if(E)try{A.originalXHRSetRequestHeader.call(this,B,E)}catch{}}return A.originalXHRSend.call(this,Q)}}getHeaderName(){return this.config.name||F.name}isStarted(){return this.started}}var w={selector:"form",inputName:"_bsid"};function zA(A){if(!A)return null;if(A===!0)return{...w};return{...w,...A}}class e{config;sessionIdGetter;observer=null;started=!1;constructor(A,B){this.config={...w,...A},this.sessionIdGetter=B}start(){if(this.started)return;this.started=!0;let A=()=>{this.setupExistingForms(),this.setupObserver()};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",A,{once:!0});else A()}stop(){if(!this.started)return;if(this.observer)this.observer.disconnect(),this.observer=null;let A=this.config.selector||w.selector,B=this.config.inputName||w.inputName;document.querySelectorAll(`${A}[data-bs-inject-setup]`).forEach((Q)=>{if(Q instanceof HTMLFormElement)Q.removeEventListener("submit",this.handleSubmit,{capture:!0});Q.removeAttribute("data-bs-inject-setup");let E=Q.querySelector(`input[name="${B}"][data-bs-injected]`);if(E)E.remove()}),this.started=!1}setupExistingForms(){let A=this.config.selector||w.selector;document.querySelectorAll(A).forEach((B)=>{if(B instanceof HTMLFormElement)this.setupForm(B)})}setupObserver(){if(!document.body)return;let A=this.config.selector||w.selector;this.observer=new MutationObserver((B)=>{B.forEach((Q)=>{Q.addedNodes.forEach((E)=>{if(E instanceof HTMLFormElement&&E.matches(A))this.setupForm(E);if(E instanceof HTMLElement)E.querySelectorAll(A).forEach((I)=>{if(I instanceof HTMLFormElement)this.setupForm(I)})})})}),this.observer.observe(document.body,{childList:!0,subtree:!0})}setupForm(A){if(A.hasAttribute("data-bs-inject-setup"))return;A.setAttribute("data-bs-inject-setup","true"),A.addEventListener("submit",this.handleSubmit,{capture:!0})}handleSubmit=(A)=>{let B=A.currentTarget;this.injectInput(B)};injectInput(A){let B=this.config.inputName||w.inputName,Q=A.querySelector(`input[name="${B}"]`);if(Q){if(Q.hasAttribute("data-bs-injected"))Q.value=this.sessionIdGetter();return}let E=document.createElement("input");E.type="hidden",E.name=B,E.value=this.sessionIdGetter(),E.setAttribute("data-bs-injected","true"),A.appendChild(E)}getConfig(){return{...this.config}}isStarted(){return this.started}}class K{static instance=null;static init(A){if(K.instance)return K.instance;return K.instance=new K(A),K.instance}static getInstance(){return K.instance}static async destroy(){if(K.instance)await K.instance.stop(),K.instance=null}config;mouseCollector;scrollCollector;formCollector;browserCollector;fingerprintGenerator;socket=null;sessionId;sequenceNumber=0;isRunning=!1;sendTimer=null;fingerprint=null;browserSignal=null;lastScore=null;hasSentInitial=!1;boundBeforeUnload=null;boundVisibilityChange=null;hashModule=null;formBlocked=!1;formObserver=null;highScoreTriggeredLevels=new Set;challengeManager=null;challengeManagerPromise=null;formProtectionManager=null;formSubmissionStatus="no_submission";cookieManager=null;headerInjector=null;formInjector=null;serverConfig=null;connectionState="disconnected";reconnectTimer=null;readyPromise;readyResolver=null;constructor(A){if(J.markConstructorStart(),!A.apiKey)throw Error("BotSigged: apiKey is required");if(this.config=IA(A),this.sessionId=this.generateSessionId(),this.readyPromise=new Promise((I)=>{this.readyResolver=I}),this.mouseCollector=new u({sampleRate:this.config.mouseSampleRate,maxBufferSize:this.config.maxBufferSize}),this.scrollCollector=new p({maxBufferSize:Math.floor(this.config.maxBufferSize/3)}),this.formCollector=new m({maxKeyEvents:this.config.maxBufferSize,onSubmit:()=>this.handleFormSubmit()}),this.browserCollector=new d,this.fingerprintGenerator=new s,this.config.hashVerification.enabled)this.initializeHashModule();if(this.config.action==="challenge"||this.config.challenge.enabled)this.challengeManagerPromise=this.initializeChallengeManager();if(this.config.formProtection.mode!=="none")this.formProtectionManager=new t({mode:this.config.formProtection.mode,minTimeBeforeSubmit:this.config.formProtection.minTimeBeforeSubmit,maxHoldTime:this.config.formProtection.maxHoldTime,showLoadingUI:this.config.formProtection.showLoadingUI,loadingMessage:this.config.formProtection.loadingMessage,onHold:(I)=>{this.updateFormStatus("challenged"),this.config.formProtection.onHold?.(I)},onRelease:(I,C)=>{if(!C)this.updateFormStatus("completed");this.config.formProtection.onRelease?.(I,C)},onBlock:(I,C)=>{this.updateFormStatus("blocked"),this.config.formProtection.onBlock?.(I,C)},flushAndWaitForScore:()=>this.sendSignalAndGetScore()}),this.log("Form protection enabled:",this.config.formProtection.mode);else this.log("Form protection disabled (mode='none')");let B=XA(this.config.cookie);if(B)this.cookieManager=new r(B,()=>this.sessionId),this.log("Cookie manager enabled:",B.name);let Q=RA(this.config.headers);if(Q)this.headerInjector=new o(Q,()=>this.sessionId),this.headerInjector.start(),this.log("Header injector enabled:",Q.name);let E=zA(this.config.formInject);if(E)this.formInjector=new e(E,()=>this.sessionId),this.formInjector.start(),this.log("Form injector enabled:",E.inputName);if(this.config.autoStart)if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",()=>this.start());else this.start();J.markConstructorEnd(),this.log("Constructor completed in",(J.getTimings().constructorEnd??0)-(J.getTimings().constructorStart??0),"ms")}async initializeHashModule(){try{let{initHashModule:A}=await Promise.resolve().then(() => (b(),JA));this.hashModule=await A({preferWasm:this.config.hashVerification.preferWasm,onWasmLoaded:()=>{this.log("WASM hash module loaded"),this.config.hashVerification.onWasmLoaded?.()},onFallback:(B)=>{this.log("Using JS hash fallback:",B),this.config.hashVerification.onWasmFallback?.(B)}})}catch(A){this.log("Failed to initialize hash module",A)}}async initializeChallengeManager(){try{let{ChallengeManager:A}=await Promise.resolve().then(() => (qA(),WA));this.challengeManager=new A(this.config.challenge,this.config.debug),this.log("Challenge manager loaded")}catch(A){this.log("Failed to initialize challenge manager",A)}}async start(){if(this.isRunning){this.log("Already running");return}J.markStartCalled(),this.log("Starting BotSigged SDK"),this.isRunning=!0,this.connectionState="connecting";try{this.browserSignal=this.browserCollector.collect(),J.markFormCollectorStart(),this.mouseCollector.start(),this.scrollCollector.start(),this.formCollector.start(),J.markFormCollectorReady(),this.log("Collectors started in",(J.getTimings().formCollectorReady??0)-(J.getTimings().formCollectorStart??0),"ms"),J.markFingerprintStart(),J.markWsConnectStart();let[A]=await Promise.all([this.fingerprintGenerator.generate(),this.connectWithRetry()]);this.fingerprint=A,J.markFingerprintEnd(),this.log("Fingerprint generated in",(J.getTimings().fingerprintEnd??0)-(J.getTimings().fingerprintStart??0),"ms"),await this.joinChannel(),this.connectionState="connected",this.readyResolver?.(),J.markSdkReady(),this.startSendInterval(),this.registerBeforeUnload();let B=J.getSummary();if(this.log("SDK started successfully"),this.log("Total startup time:",B.totalStartupMs,"ms"),this.log("Time to first score:",B.timeToFirstScoreMs,"ms"),this.log("Vulnerability window:",B.vulnerabilityWindowMs,"ms"),this.config.debug)J.logSummary()}catch(A){let B=A instanceof Error?A:Error(String(A));this.log("Failed to start",B),this.handleConnectionFailure(B)}}async stop(){if(!this.isRunning)return;if(this.log("Stopping BotSigged SDK"),this.formProtectionManager)this.formProtectionManager.destroy(),this.formProtectionManager=null;if(this.cookieManager)this.cookieManager.removeCookies(),this.cookieManager=null;if(this.headerInjector)this.headerInjector.stop(),this.headerInjector=null;if(this.formInjector)this.formInjector.stop(),this.formInjector=null;if(this.formObserver)this.formObserver.disconnect(),this.formObserver=null;this.unregisterBeforeUnload(),this.mouseCollector.stop(),this.scrollCollector.stop(),this.formCollector.stop(),this.stopSendInterval(),await this.sendSignal(),await this.disconnect(),this.isRunning=!1,this.log("SDK stopped")}async sendSignal(){if(!this.socket?.isReady()){this.log("Cannot send signal: not connected");return}let A=this.buildPayload(),B=A.seq;this.log("Sending signal seq:",B),J.markSignalSent(B);try{let Q=await this.socket.sendSignal(A);J.markSignalResponseReceived(B);let E=J.getTimings().signalRoundtrips||[],I=E[E.length-1];if(I)this.log("Signal roundtrip:",I.roundtripMs,"ms");if(Q.bot_score!==void 0){let C={bot_score:Q.bot_score,classification:Q.classification||"unknown",triggered_rules:Q.triggered_rules||[]};this.lastScore=C,this.config.onScoreUpdate?.(C),this.handleScoreUpdate(C)}this.mouseCollector.flush(),this.scrollCollector.flush(),this.formCollector.flush(),this.hasSentInitial=!0}catch(Q){let E=Q instanceof Error?Q:Error(String(Q));this.log("Failed to send signal",E),this.config.onError?.(E)}}async sendSignalAndGetScore(){if(!this.socket?.isReady())return this.log("Cannot send signal: not connected"),null;let A=this.buildPayload(),B=A.seq;this.log("Sending signal for form scoring, seq:",B);try{let Q=await this.socket.sendSignal(A);if(Q.bot_score!==void 0){let E={bot_score:Q.bot_score,classification:Q.classification||"unknown",triggered_rules:Q.triggered_rules||[]};return this.lastScore=E,this.config.onScoreUpdate?.(E),this.handleScoreUpdate(E),this.mouseCollector.flush(),this.scrollCollector.flush(),this.formCollector.flush(),this.hasSentInitial=!0,E.bot_score}return this.mouseCollector.flush(),this.scrollCollector.flush(),this.formCollector.flush(),this.hasSentInitial=!0,null}catch(Q){let E=Q instanceof Error?Q:Error(String(Q));return this.log("Failed to send signal for form scoring",E),this.config.onError?.(E),null}}getSessionId(){return this.sessionId}getFingerprint(){return this.fingerprint}getFormSubmissionStatus(){return this.formSubmissionStatus}getLastScore(){return this.lastScore}isConnected(){return this.socket?.isReady()??!1}whenReady(){if(this.connectionState==="connected")return Promise.resolve();return this.readyPromise}getConnectionState(){return this.connectionState}getServerConfig(){return this.serverConfig}async identify(A){let{accountId:B}=A;if(!B||typeof B!=="string")throw Error("BotSigged: accountId is required and must be a string");if(B.length>255)throw Error("BotSigged: accountId must be 255 characters or less");this.log("Identifying account:",B),await this.whenReady();try{let Q=await this.socket.sendEvent("identify",{account_id:B,timestamp:Date.now()});if(Q.identified)this.log("Account identified successfully");else throw Error(Q.reason?.toString()||"Failed to identify account")}catch(Q){let E=Q instanceof Error?Q:Error(String(Q));throw this.log("Failed to identify account:",E),this.config.onError?.(E),E}}isDegraded(){return this.connectionState==="degraded"||this.connectionState==="failed"}getCurrentSignals(){return{mouse:this.mouseCollector.getSignal(),scroll:this.scrollCollector.getSignal(),form:this.formCollector.getSignal(),browser:this.browserSignal}}getBufferSizes(){return{mouse:this.mouseCollector.getBufferSize(),scroll:this.scrollCollector.getBufferSize(),form:this.formCollector.getBufferSize()}}resetSignals(){this.mouseCollector.reset(),this.scrollCollector.reset(),this.formCollector.reset(),this.browserCollector.reset(),this.sequenceNumber=0,this.hasSentInitial=!1}async connectSocket(){this.socket=new n({endpoint:this.config.endpoint,apiKey:this.config.apiKey,debug:this.config.debug,onConnectionChange:(A)=>{this.config.onConnectionChange?.(A==="connected")},onError:(A)=>{this.config.onError?.(A)}}),await this.socket.connect(),J.markWsConnectEnd(),this.log("WebSocket connected in",(J.getTimings().wsConnectEnd??0)-(J.getTimings().wsConnectStart??0),"ms")}async connectWithRetry(){let B=[1000,2000,4000];for(let Q=0;Q<3;Q++)try{await this.connectSocket();return}catch(E){if(this.log(`Connection attempt ${Q+1} failed:`,E),Q<2)await this.sleep(B[Q]);else throw E}}sleep(A){return new Promise((B)=>setTimeout(B,A))}handleConnectionFailure(A){this.connectionState="failed";let B=this.config.fallbackMode||"degraded";switch(this.log("Connection failed, applying fallback mode:",B),B){case"open":if(this.connectionState="degraded",this.formProtectionManager)this.formProtectionManager.setMode("none"),this.formProtectionManager.notifyReady(0);break;case"closed":this.blockFormsUntilConnected(),this.scheduleReconnect();break;case"cached":let Q=this.loadCachedConfig();if(Q)this.applyServerConfig(Q),this.connectionState="degraded";else this.applyFallbackConfig();this.scheduleReconnect();break;case"degraded":default:this.applyFallbackConfig(),this.connectionState="degraded",this.scheduleReconnect();break}this.config.onError?.(A),this.config.onConnectionChange?.(!1)}applyFallbackConfig(){if(this.log("Applying fallback config"),this.serverConfig=EA,this.formProtectionManager&&this.serverConfig.form_protection_mode)this.formProtectionManager.setMode(this.serverConfig.form_protection_mode);this.config.onServerConfig?.(this.serverConfig,"fallback")}blockFormsUntilConnected(){if(this.formProtectionManager)this.formProtectionManager.setMode("holdUntilReady"),this.formProtectionManager.setMaxHoldTime(30000)}scheduleReconnect(){if(this.reconnectTimer)clearTimeout(this.reconnectTimer);this.reconnectTimer=setTimeout(()=>{this.attemptReconnect()},5000)}async attemptReconnect(){this.log("Attempting reconnection..."),this.connectionState="connecting";try{if(await this.connectWithRetry(),!this.fingerprint)this.fingerprint=await this.fingerprintGenerator.generate();if(await this.joinChannel(),this.connectionState="connected",this.readyResolver?.(),this.log("Reconnection successful"),!this.sendTimer)this.startSendInterval()}catch(A){this.log("Reconnection failed:",A),this.connectionState="failed"}}cacheServerConfig(A){try{localStorage.setItem(`botsigged_config_${this.config.apiKey}`,JSON.stringify({config:A,timestamp:Date.now()}))}catch{}}loadCachedConfig(){try{let A=localStorage.getItem(`botsigged_config_${this.config.apiKey}`);if(!A)return null;let{config:B,timestamp:Q}=JSON.parse(A);if(Date.now()-Q>86400000)return localStorage.removeItem(`botsigged_config_${this.config.apiKey}`),null;return B}catch{return null}}applyServerConfig(A){if(this.log("Applying server config:",A),this.serverConfig=A,this.formProtectionManager&&A.form_protection_mode)this.formProtectionManager.setMode(A.form_protection_mode);if(A.action&&A.action!=="none")this.applyServerAction(A.action,A.challenge);this.cacheServerConfig(A),this.config.onServerConfig?.(A,"server")}async applyServerAction(A,B){switch(this.log("Applying server action:",A),A){case"block":if(this.updateFormStatus("blocked"),!this.formBlocked)this.blockForms();break;case"challenge":if(this.updateFormStatus("challenged"),!this.challengeManager&&!this.challengeManagerPromise)this.log("Lazily loading challenge manager for server-requested challenge"),this.challengeManagerPromise=this.initializeChallengeManager();if(this.challengeManagerPromise)await this.challengeManagerPromise;if(this.challengeManager){let Q=B?.difficulty?.bot??16,E=Q>=18?"critical":Q>=16?"high":"medium";this.challengeManager.blockFormsUntilSolved(E)}else this.log("Challenge requested but challenge manager failed to load");break;case"flag":this.updateFormStatus("flagged"),this.log("Session flagged by server");break;case"none":default:break}}handleServerAction(A){this.log("Received server action:",A),this.config.onServerAction?.(A);let B=A.challenge?{difficulty:{suspicious:A.challenge.difficulty,bot:A.challenge.difficulty},timeout_ms:A.challenge.timeout_ms}:void 0;this.applyServerAction(A.type,B)}async joinChannel(){if(!this.socket)throw Error("WebSocket not initialized");J.markChannelJoinStart();let A;try{A=await this.socket.joinChannel(this.sessionId,this.fingerprint,this.getSessionData(),this.browserSignal,{onScoreUpdate:(B)=>{this.lastScore=B,this.config.onScoreUpdate?.(B),this.handleScoreUpdate(B)},onError:(B)=>{this.config.onError?.(B)},onAction:(B)=>{this.handleServerAction(B)}},this.config.accountId)}catch(B){if(QA(B)){if(this.log("Usage limit exceeded:",B),this.config.onUsageLimitExceeded)this.config.onUsageLimitExceeded(B);else this.config.onError?.(Error(`Usage limit exceeded: ${B.current_usage}/${B.limit} verifications (${B.plan_name} plan). Please upgrade your plan.`));return}throw B}if(J.markChannelJoinEnd(),this.log("Channel joined in",(J.getTimings().channelJoinEnd??0)-(J.getTimings().channelJoinStart??0),"ms"),A.config){let B=A.config;this.applyServerConfig(B)}if(A.initial_score!==void 0){J.markInitialScoreReceived();let B={bot_score:A.initial_score,classification:A.classification||"unknown",triggered_rules:A.triggered_rules||[]};if(this.lastScore=B,this.config.onScoreUpdate?.(B),this.handleScoreUpdate(B),this.formProtectionManager)this.formProtectionManager.notifyReady(B.bot_score);if(this.cookieManager)this.cookieManager.setCookie();this.log("Initial score received:",B.bot_score,"in",(J.getTimings().initialScoreReceived??0)-(J.getTimings().startCalled??0),"ms from start")}}handleScoreUpdate(A){if(this.cookieManager)this.cookieManager.updateRiskTier(A.bot_score);let B=this.getBotScoreLevel(A.bot_score),Q=A.bot_score>=this.config.actionThreshold;if(this.shouldTriggerAlert(B)){let E={score:A.bot_score,level:B,scoreUpdate:A,sessionId:this.sessionId,fingerprintHash:this.fingerprint?.hash};if(Q&&!this.highScoreTriggeredLevels.has(B))this.executeAction(E);this.config.onHighBotScore?.(E),this.highScoreTriggeredLevels.add(B)}}getBotScoreLevel(A){let B=this.config.botScoreThresholds;if(A>=B.critical)return"critical";if(A>=B.high)return"high";if(A>=B.medium)return"medium";return"low"}shouldTriggerAlert(A){if(this.highScoreTriggeredLevels.has(A))return!1;let B=["low","medium","high","critical"],Q=this.config.minAlertLevel,E=B.indexOf(A),I=B.indexOf(Q);return E>=I}async executeAction(A){let B=this.config.action;switch(this.log(`Executing action '${B}' for score ${A.score}`),B){case"challenge":if(this.challengeManagerPromise)await this.challengeManagerPromise;if(this.challengeManager)this.challengeManager.blockFormsUntilSolved(A.level);break;case"block":if(!this.formBlocked)this.blockForms();break;case"none":default:break}}blockForms(){if(this.formBlocked)return;this.formBlocked=!0,document.querySelectorAll("form").forEach((A)=>{A.addEventListener("submit",this.blockFormSubmit,!0)}),this.formObserver=new MutationObserver((A)=>{A.forEach((B)=>{B.addedNodes.forEach((Q)=>{if(Q instanceof HTMLFormElement)Q.addEventListener("submit",this.blockFormSubmit,!0);if(Q instanceof HTMLElement)Q.querySelectorAll("form").forEach((E)=>{E.addEventListener("submit",this.blockFormSubmit,!0)})})})}),this.formObserver.observe(document.body,{childList:!0,subtree:!0}),this.log("Forms blocked due to high bot score")}blockFormSubmit=(A)=>{A.preventDefault(),A.stopPropagation(),this.log("Form submission blocked due to high bot score");return};isFormsBlocked(){return this.formBlocked}unblockForms(){if(!this.formBlocked)return;if(this.formObserver)this.formObserver.disconnect(),this.formObserver=null;document.querySelectorAll("form").forEach((A)=>{A.removeEventListener("submit",this.blockFormSubmit,!0)}),this.formBlocked=!1,this.log("Forms unblocked")}getHashModule(){return this.hashModule}createSignature(A){let B=this.config.hashVerification.secret;if(!B)return this.log("Cannot create signature: no secret configured"),null;return createSignature(A,B)}verifySignature(A,B){let Q=this.config.hashVerification.secret;if(!Q)return this.log("Cannot verify signature: no secret configured"),!1;return verifySignature(A,B,Q)}isChallengeSolving(){return this.challengeManager?.isSolving()??!1}isChallengeSolved(){return this.challengeManager?.isSolved()??!1}getPerformanceSummary(){return J.getSummary()}logPerformance(){J.logSummary()}getPerformanceReport(){return J.getReport()}async waitUntilReady(){if(this.lastScore)return{score:this.lastScore.bot_score,timedOut:!1};if(this.formProtectionManager)return this.formProtectionManager.waitUntilReady();return new Promise((A)=>{let B=performance.now(),Q=5000,E=()=>{if(this.lastScore){A({score:this.lastScore.bot_score,timedOut:!1});return}if(performance.now()-B>=5000){A({score:null,timedOut:!0});return}setTimeout(E,50)};E()})}withProtection(A,B={}){let Q=B.blockThreshold??this.config.actionThreshold;return async(...E)=>{let{score:I,timedOut:C}=await this.waitUntilReady();if(J.markFirstSubmitAttempt(I!==null),I!==null&&I>=Q)throw this.log(`Blocking submission: score ${I} >= threshold ${Q}`),Error(`Submission blocked: bot score ${I} exceeds threshold`);if(C)this.log("Warning: submitting without detection score (timed out)");return A(...E)}}protectedFetch(A={}){return this.withProtection(async(B,Q)=>{return fetch(B,Q)},A)}canSubmit(){if(!this.lastScore)return{allowed:!1,reason:"waiting_for_score",score:null};if(this.lastScore.bot_score>=this.config.actionThreshold)return{allowed:!1,reason:"high_bot_score",score:this.lastScore.bot_score};return{allowed:!0,score:this.lastScore.bot_score}}async triggerChallenge(A="high"){if(this.challengeManagerPromise)await this.challengeManagerPromise;if(!this.challengeManager){this.log("Challenge not enabled");return}this.challengeManager.blockFormsUntilSolved(A)}async disconnect(){if(this.socket)await this.socket.leaveChannel(),this.socket.disconnect(),this.socket=null}startSendInterval(){this.stopSendInterval(),this.sendTimer=setInterval(()=>{this.sendSignal()},this.config.sendInterval)}stopSendInterval(){if(this.sendTimer)clearInterval(this.sendTimer),this.sendTimer=null}registerBeforeUnload(){this.boundBeforeUnload=()=>{this.handleBeforeUnload()},this.boundVisibilityChange=()=>{if(document.visibilityState==="hidden")this.handleBeforeUnload()},window.addEventListener("beforeunload",this.boundBeforeUnload),document.addEventListener("visibilitychange",this.boundVisibilityChange)}unregisterBeforeUnload(){if(this.boundBeforeUnload)window.removeEventListener("beforeunload",this.boundBeforeUnload),this.boundBeforeUnload=null;if(this.boundVisibilityChange)document.removeEventListener("visibilitychange",this.boundVisibilityChange),this.boundVisibilityChange=null}handleBeforeUnload(){if(!this.isRunning||!this.socket)return;try{let A=this.buildPayload();if(this.socket.isReady())this.socket.sendSignal(A).catch(()=>{})}catch{}}handleFormSubmit(){if(!this.isRunning)return;if(J.markFirstSubmitAttempt(this.lastScore!==null),this.log("Form submitted, flushing signals via beacon"),this.log("Had score before submit:",this.lastScore!==null),this.updateFormStatus("completed"),!this.sessionId){this.log("No session ID yet, cannot send beacon");return}let A=this.buildPayload();if(!this.sendViaBeacon(A))this.sendSignal().catch((Q)=>{this.log("Failed to flush signals on form submit",Q)});else this.mouseCollector.flush(),this.scrollCollector.flush(),this.formCollector.flush()}sendViaBeacon(A){if(!navigator.sendBeacon)return this.log("sendBeacon not available"),!1;try{let B=new URL(this.config.endpoint),Q=`${B.protocol==="wss:"?"https:":"http:"}//${B.host}/api/signal`,E=JSON.stringify({session_id:this.sessionId,api_key:this.config.apiKey,payload:A,form_status:this.formSubmissionStatus}),I=new Blob([E],{type:"application/json"}),C=navigator.sendBeacon(Q,I);return this.log("Beacon sent:",C),C}catch(B){return this.log("Beacon send failed:",B),!1}}buildPayload(){this.sequenceNumber++;let A={session_id:this.sessionId,seq:this.sequenceNumber,mouse:this.mouseCollector.getSignal(),scroll:this.scrollCollector.getSignal(),form:this.formCollector.getSignal(),timestamp:Date.now()};if(!this.hasSentInitial)A.session=this.getSessionData(),A.fingerprint=this.fingerprint,A.browser=this.browserSignal;return A}getSessionData(){let A=new URL(window.location.href),B={};A.searchParams.forEach((E,I)=>{B[I]=E});let Q=null;if(document.referrer)try{Q=new URL(document.referrer).hostname}catch{}return{url_path:A.pathname,url_params:B,referrer_url:document.referrer||null,referrer_domain:Q,user_agent:navigator.userAgent}}generateSessionId(){if(crypto.randomUUID)return crypto.randomUUID();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(A)=>{let B=Math.random()*16|0;return(A==="x"?B:B&3|8).toString(16)})}updateFormStatus(A){if(this.formSubmissionStatus==="challenged"||this.formSubmissionStatus==="flagged"||this.formSubmissionStatus==="blocked"||this.formSubmissionStatus==="completed"){this.log(`Form status already terminal (${this.formSubmissionStatus}), ignoring ${A}`);return}if(this.formSubmissionStatus=A,this.log(`Form status updated to: ${A}`),this.socket?.isReady())this.socket.sendFormStatus(A).catch((B)=>{this.log("Failed to send form status:",B)})}log(...A){if(this.config.debug);}}var DB=K.init.bind(K),HB=K.getInstance.bind(K),$B=K.destroy.bind(K);if(typeof window<"u")window.BotSigged=K;})();
43
+ `,document.body.appendChild(this.loadingOverlay)}hideLoading(){if(this.loadingOverlay)this.loadingOverlay.remove(),this.loadingOverlay=null}notifyReady(A){console.log("[BotSigged] Form protection ready with score:",A),this.isReady=!0,this.hasScore=!0,this.currentScore=A,[...this.pendingSubmissions].forEach((E)=>{this.releaseSubmission(E,!1)}),[...this.pendingRequests].forEach((E)=>{this.releaseRequest(E)}),this.hideLoading()}blockAllPending(A){console.log("[BotSigged FormProtection] Blocking all pending:",A),[...this.pendingSubmissions].forEach((Q)=>{this.config.onBlock?.(Q.form,A),this.releaseSubmission(Q,!0)})}getStatus(){return{mode:this.config.mode,isReady:this.isReady,hasScore:this.hasScore,pendingCount:this.pendingSubmissions.length,protectedFormCount:this.protectedForms.size}}waitUntilReady(){if(this.hasScore)return Promise.resolve({score:this.currentScore,timedOut:!1});return new Promise((A)=>{let B=performance.now(),Q=()=>{if(this.hasScore){A({score:this.currentScore,timedOut:!1});return}if(performance.now()-B>=this.config.maxHoldTime){console.warn("[BotSigged] waitUntilReady timed out after",this.config.maxHoldTime,"ms"),A({score:null,timedOut:!0});return}setTimeout(Q,50)};Q()})}withProtection(A){return async(...B)=>{let Q=performance.now()-this.startTime;if(O().markFirstSubmitAttempt(this.hasScore),this.config.mode==="blockInstant"&&Q<this.config.minTimeBeforeSubmit)throw console.warn(`[BotSigged] Blocked instant submission (${Q.toFixed(0)}ms < ${this.config.minTimeBeforeSubmit}ms threshold)`),this.config.onBlock?.(document.createElement("form"),"instant_submission"),Error("Submission blocked: too fast");if(this.config.mode==="holdUntilReady"&&!this.hasScore){if(console.log("[BotSigged] Waiting for SDK before submission..."),this.config.showLoadingUI)this.showLoading(document.createElement("form"));let{timedOut:E}=await this.waitUntilReady();if(this.config.showLoadingUI)this.hideLoading();if(E)console.warn("[BotSigged] SDK not ready, proceeding anyway")}return A(...B)}}protectedFetch(){return this.withProtection(async(A,B)=>{return fetch(A,B)})}setMode(A){if(console.log("[BotSigged] Form protection mode changed:",this.config.mode,"->",A),this.config.mode=A,A==="none")[...this.pendingSubmissions].forEach((Q)=>this.releaseSubmission(Q,!1))}setMaxHoldTime(A){console.log("[BotSigged] Form protection max hold time changed:",this.config.maxHoldTime,"->",A),this.config.maxHoldTime=A}canSubmit(){let A=performance.now()-this.startTime;if(this.config.mode==="blockInstant"&&A<this.config.minTimeBeforeSubmit)return{allowed:!1,reason:"too_fast",score:this.currentScore};if(this.config.mode==="holdUntilReady"&&!this.hasScore)return{allowed:!1,reason:"waiting_for_score",score:null};return{allowed:!0,score:this.currentScore}}destroy(){if(this.formObserver)this.formObserver.disconnect(),this.formObserver=null;if(this.originalFetch)window.fetch=this.originalFetch,this.originalFetch=null;if(this.originalXHROpen)XMLHttpRequest.prototype.open=this.originalXHROpen,this.originalXHROpen=null;if(this.originalXHRSend)XMLHttpRequest.prototype.send=this.originalXHRSend,this.originalXHRSend=null;this.hideLoading(),this.pendingSubmissions=[],this.pendingRequests=[],this.protectedForms.clear(),console.log("[BotSigged] Form protection destroyed, originals restored")}}var ZA={suspicious:40,bot:70},D={name:"_bsid",riskName:"_bsrisk",path:"/",sameSite:"Strict"};function XA(A){if(!A)return null;if(A===!0)return{...D};return{...D,...A}}function jA(A){if(A>=ZA.bot)return"bot";if(A>=ZA.suspicious)return"suspicious";return"human"}class o{config;sessionIdGetter;sessionCookieSet=!1;currentRiskTier=null;constructor(A,B){this.config={...D,...A},this.sessionIdGetter=B}buildCookieString(A,B){let Q=this.config.path||D.path,E=this.config.sameSite||D.sameSite,I=this.config.secure??location.protocol==="https:",C=[`${encodeURIComponent(A)}=${encodeURIComponent(B)}`,`Path=${Q}`,`SameSite=${E}`];if(I||E==="None")C.push("Secure");return C.join("; ")}deleteCookie(A){let B=this.config.path||D.path;document.cookie=`${encodeURIComponent(A)}=; Path=${B}; Max-Age=0`}setSessionCookie(){if(this.sessionCookieSet)return;let A=this.sessionIdGetter();if(!A){console.warn("[BotSigged] Cannot set cookie: no session ID");return}let B=this.config.name||D.name;document.cookie=this.buildCookieString(B,A),this.sessionCookieSet=!0,console.log(`[BotSigged] Session cookie set: ${B}=${A.substring(0,8)}...`)}updateRiskTier(A){let B=jA(A);if(B===this.currentRiskTier)return!1;let Q=this.config.riskName||D.riskName;document.cookie=this.buildCookieString(Q,B);let E=this.currentRiskTier;return this.currentRiskTier=B,console.log(`[BotSigged] Risk tier ${E?"changed":"set"}: ${E||"none"} -> ${B}`),!0}removeCookies(){let A=this.config.name||D.name,B=this.config.riskName||D.riskName;if(this.sessionCookieSet)this.deleteCookie(A),this.sessionCookieSet=!1,console.log(`[BotSigged] Session cookie removed: ${A}`);if(this.currentRiskTier!==null)this.deleteCookie(B),this.currentRiskTier=null,console.log(`[BotSigged] Risk cookie removed: ${B}`)}setCookie(){this.setSessionCookie()}removeCookie(){this.removeCookies()}isSessionCookieSet(){return this.sessionCookieSet}getCurrentRiskTier(){return this.currentRiskTier}getSessionCookieName(){return this.config.name||D.name}getRiskCookieName(){return this.config.riskName||D.riskName}}var F={name:"X-BotSigged-ID"};function RA(A){if(!A)return null;if(A===!0)return{...F};return{...F,...A}}class r{config;sessionIdGetter;started=!1;originalFetch=null;originalXHROpen=null;originalXHRSend=null;originalXHRSetRequestHeader=null;xhrInjectionMap=new WeakMap;constructor(A,B){this.config={...F,...A},this.sessionIdGetter=B}start(){if(this.started)return;this.started=!0,this.patchFetch(),this.patchXHR(),console.log(`[BotSigged] Header injector started (header: ${this.config.name})`)}stop(){if(!this.started)return;if(this.originalFetch)window.fetch=this.originalFetch,this.originalFetch=null;if(this.originalXHROpen)XMLHttpRequest.prototype.open=this.originalXHROpen,this.originalXHROpen=null;if(this.originalXHRSend)XMLHttpRequest.prototype.send=this.originalXHRSend,this.originalXHRSend=null;if(this.originalXHRSetRequestHeader)XMLHttpRequest.prototype.setRequestHeader=this.originalXHRSetRequestHeader,this.originalXHRSetRequestHeader=null;this.started=!1,console.log("[BotSigged] Header injector stopped")}isSameOrigin(A){try{let B;if(A instanceof Request)B=new URL(A.url,window.location.origin);else if(A instanceof URL)B=A;else B=new URL(A,window.location.origin);return B.origin===window.location.origin}catch{return!0}}patchFetch(){this.originalFetch=window.fetch.bind(window);let A=this,B=this.config.name||F.name;window.fetch=function(Q,E){if(!A.isSameOrigin(Q))return A.originalFetch(Q,E);let I=A.sessionIdGetter();if(!I)return A.originalFetch(Q,E);let C=new Headers(E?.headers);if(!C.has(B))C.set(B,I);return A.originalFetch(Q,{...E,headers:C})}}patchXHR(){this.originalXHROpen=XMLHttpRequest.prototype.open,this.originalXHRSend=XMLHttpRequest.prototype.send,this.originalXHRSetRequestHeader=XMLHttpRequest.prototype.setRequestHeader;let A=this,B=this.config.name||F.name;XMLHttpRequest.prototype.open=function(Q,E,I=!0,C,Y){let G=A.isSameOrigin(E);return A.xhrInjectionMap.set(this,G),A.originalXHROpen.call(this,Q,E,I,C,Y)},XMLHttpRequest.prototype.send=function(Q){if(A.xhrInjectionMap.get(this)){let E=A.sessionIdGetter();if(E)try{A.originalXHRSetRequestHeader.call(this,B,E)}catch{}}return A.originalXHRSend.call(this,Q)}}getHeaderName(){return this.config.name||F.name}isStarted(){return this.started}}var w={selector:"form",inputName:"_bsid"};function zA(A){if(!A)return null;if(A===!0)return{...w};return{...w,...A}}class e{config;sessionIdGetter;observer=null;started=!1;constructor(A,B){this.config={...w,...A},this.sessionIdGetter=B}start(){if(this.started)return;this.started=!0;let A=()=>{this.setupExistingForms(),this.setupObserver()};if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",A,{once:!0});else A();console.log(`[BotSigged] Form injector started (selector: ${this.config.selector})`)}stop(){if(!this.started)return;if(this.observer)this.observer.disconnect(),this.observer=null;let A=this.config.selector||w.selector,B=this.config.inputName||w.inputName;document.querySelectorAll(`${A}[data-bs-inject-setup]`).forEach((Q)=>{if(Q instanceof HTMLFormElement)Q.removeEventListener("submit",this.handleSubmit,{capture:!0});Q.removeAttribute("data-bs-inject-setup");let E=Q.querySelector(`input[name="${B}"][data-bs-injected]`);if(E)E.remove()}),this.started=!1,console.log("[BotSigged] Form injector stopped")}setupExistingForms(){let A=this.config.selector||w.selector;document.querySelectorAll(A).forEach((B)=>{if(B instanceof HTMLFormElement)this.setupForm(B)})}setupObserver(){if(!document.body)return;let A=this.config.selector||w.selector;this.observer=new MutationObserver((B)=>{B.forEach((Q)=>{Q.addedNodes.forEach((E)=>{if(E instanceof HTMLFormElement&&E.matches(A))this.setupForm(E);if(E instanceof HTMLElement)E.querySelectorAll(A).forEach((I)=>{if(I instanceof HTMLFormElement)this.setupForm(I)})})})}),this.observer.observe(document.body,{childList:!0,subtree:!0})}setupForm(A){if(A.hasAttribute("data-bs-inject-setup"))return;A.setAttribute("data-bs-inject-setup","true"),A.addEventListener("submit",this.handleSubmit,{capture:!0})}handleSubmit=(A)=>{let B=A.currentTarget;this.injectInput(B)};injectInput(A){let B=this.config.inputName||w.inputName,Q=A.querySelector(`input[name="${B}"]`);if(Q){if(Q.hasAttribute("data-bs-injected"))Q.value=this.sessionIdGetter();return}let E=document.createElement("input");E.type="hidden",E.name=B,E.value=this.sessionIdGetter(),E.setAttribute("data-bs-injected","true"),A.appendChild(E),console.log(`[BotSigged] Injected hidden input: ${B}=${E.value.substring(0,8)}...`)}getConfig(){return{...this.config}}isStarted(){return this.started}}class K{static instance=null;static init(A){if(K.instance)return console.warn("[BotSigged] SDK already initialized. Returning existing instance."),K.instance;return K.instance=new K(A),K.instance}static getInstance(){return K.instance}static async destroy(){if(K.instance)await K.instance.stop(),K.instance=null}config;mouseCollector;scrollCollector;formCollector;browserCollector;fingerprintGenerator;socket=null;sessionId;sequenceNumber=0;isRunning=!1;sendTimer=null;fingerprint=null;browserSignal=null;lastScore=null;hasSentInitial=!1;boundBeforeUnload=null;boundVisibilityChange=null;hashModule=null;formBlocked=!1;formObserver=null;highScoreTriggeredLevels=new Set;challengeManager=null;challengeManagerPromise=null;formProtectionManager=null;formSubmissionStatus="no_submission";cookieManager=null;headerInjector=null;formInjector=null;serverConfig=null;connectionState="disconnected";reconnectTimer=null;readyPromise;readyResolver=null;constructor(A){if(J.markConstructorStart(),!A.apiKey)throw Error("BotSigged: apiKey is required");if(this.config=IA(A),this.sessionId=this.generateSessionId(),this.readyPromise=new Promise((I)=>{this.readyResolver=I}),this.mouseCollector=new u({sampleRate:this.config.mouseSampleRate,maxBufferSize:this.config.maxBufferSize}),this.scrollCollector=new p({maxBufferSize:Math.floor(this.config.maxBufferSize/3)}),this.formCollector=new m({maxKeyEvents:this.config.maxBufferSize,onSubmit:()=>this.handleFormSubmit()}),this.browserCollector=new d,this.fingerprintGenerator=new s,this.config.hashVerification.enabled)this.initializeHashModule();if(this.config.action==="challenge"||this.config.challenge.enabled)this.challengeManagerPromise=this.initializeChallengeManager();if(this.config.formProtection.mode!=="none")this.formProtectionManager=new t({mode:this.config.formProtection.mode,minTimeBeforeSubmit:this.config.formProtection.minTimeBeforeSubmit,maxHoldTime:this.config.formProtection.maxHoldTime,showLoadingUI:this.config.formProtection.showLoadingUI,loadingMessage:this.config.formProtection.loadingMessage,onHold:(I)=>{this.updateFormStatus("challenged"),this.config.formProtection.onHold?.(I)},onRelease:(I,C)=>{if(!C)this.updateFormStatus("completed");this.config.formProtection.onRelease?.(I,C)},onBlock:(I,C)=>{this.updateFormStatus("blocked"),this.config.formProtection.onBlock?.(I,C)},flushAndWaitForScore:()=>this.sendSignalAndGetScore()}),this.log("Form protection enabled:",this.config.formProtection.mode);else this.log("Form protection disabled (mode='none')");let B=XA(this.config.cookie);if(B)this.cookieManager=new o(B,()=>this.sessionId),this.log("Cookie manager enabled:",B.name);let Q=RA(this.config.headers);if(Q)this.headerInjector=new r(Q,()=>this.sessionId),this.headerInjector.start(),this.log("Header injector enabled:",Q.name);let E=zA(this.config.formInject);if(E)this.formInjector=new e(E,()=>this.sessionId),this.formInjector.start(),this.log("Form injector enabled:",E.inputName);if(this.config.autoStart)if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",()=>this.start());else this.start();J.markConstructorEnd(),this.log("Constructor completed in",(J.getTimings().constructorEnd??0)-(J.getTimings().constructorStart??0),"ms")}async initializeHashModule(){try{let{initHashModule:A}=await Promise.resolve().then(() => (b(),JA));this.hashModule=await A({preferWasm:this.config.hashVerification.preferWasm,onWasmLoaded:()=>{this.log("WASM hash module loaded"),this.config.hashVerification.onWasmLoaded?.()},onFallback:(B)=>{this.log("Using JS hash fallback:",B),this.config.hashVerification.onWasmFallback?.(B)}})}catch(A){this.log("Failed to initialize hash module",A)}}async initializeChallengeManager(){try{let{ChallengeManager:A}=await Promise.resolve().then(() => (qA(),WA));this.challengeManager=new A(this.config.challenge,this.config.debug),this.log("Challenge manager loaded")}catch(A){this.log("Failed to initialize challenge manager",A)}}async start(){if(this.isRunning){this.log("Already running");return}J.markStartCalled(),this.log("Starting BotSigged SDK"),this.isRunning=!0,this.connectionState="connecting";try{this.browserSignal=this.browserCollector.collect(),J.markFormCollectorStart(),this.mouseCollector.start(),this.scrollCollector.start(),this.formCollector.start(),J.markFormCollectorReady(),this.log("Collectors started in",(J.getTimings().formCollectorReady??0)-(J.getTimings().formCollectorStart??0),"ms"),J.markFingerprintStart(),J.markWsConnectStart();let[A]=await Promise.all([this.fingerprintGenerator.generate(),this.connectWithRetry()]);this.fingerprint=A,J.markFingerprintEnd(),this.log("Fingerprint generated in",(J.getTimings().fingerprintEnd??0)-(J.getTimings().fingerprintStart??0),"ms"),await this.joinChannel(),this.connectionState="connected",this.readyResolver?.(),J.markSdkReady(),this.startSendInterval(),this.registerBeforeUnload();let B=J.getSummary();if(this.log("SDK started successfully"),this.log("Total startup time:",B.totalStartupMs,"ms"),this.log("Time to first score:",B.timeToFirstScoreMs,"ms"),this.log("Vulnerability window:",B.vulnerabilityWindowMs,"ms"),this.config.debug)J.logSummary()}catch(A){let B=A instanceof Error?A:Error(String(A));this.log("Failed to start",B),this.handleConnectionFailure(B)}}async stop(){if(!this.isRunning)return;if(this.log("Stopping BotSigged SDK"),this.formProtectionManager)this.formProtectionManager.destroy(),this.formProtectionManager=null;if(this.cookieManager)this.cookieManager.removeCookies(),this.cookieManager=null;if(this.headerInjector)this.headerInjector.stop(),this.headerInjector=null;if(this.formInjector)this.formInjector.stop(),this.formInjector=null;if(this.formObserver)this.formObserver.disconnect(),this.formObserver=null;this.unregisterBeforeUnload(),this.mouseCollector.stop(),this.scrollCollector.stop(),this.formCollector.stop(),this.stopSendInterval(),await this.sendSignal(),await this.disconnect(),this.isRunning=!1,this.log("SDK stopped")}async sendSignal(){if(!this.socket?.isReady()){this.log("Cannot send signal: not connected");return}let A=this.buildPayload(),B=A.seq;this.log("Sending signal seq:",B),J.markSignalSent(B);try{let Q=await this.socket.sendSignal(A);J.markSignalResponseReceived(B);let E=J.getTimings().signalRoundtrips||[],I=E[E.length-1];if(I)this.log("Signal roundtrip:",I.roundtripMs,"ms");if(Q.bot_score!==void 0){let C={bot_score:Q.bot_score,classification:Q.classification||"unknown",triggered_rules:Q.triggered_rules||[]};this.lastScore=C,this.config.onScoreUpdate?.(C),this.handleScoreUpdate(C)}this.mouseCollector.flush(),this.scrollCollector.flush(),this.formCollector.flush(),this.hasSentInitial=!0}catch(Q){let E=Q instanceof Error?Q:Error(String(Q));this.log("Failed to send signal",E),this.config.onError?.(E)}}async sendSignalAndGetScore(){if(!this.socket?.isReady())return this.log("Cannot send signal: not connected"),null;let A=this.buildPayload(),B=A.seq;this.log("Sending signal for form scoring, seq:",B);try{let Q=await this.socket.sendSignal(A);if(Q.bot_score!==void 0){let E={bot_score:Q.bot_score,classification:Q.classification||"unknown",triggered_rules:Q.triggered_rules||[]};return this.lastScore=E,this.config.onScoreUpdate?.(E),this.handleScoreUpdate(E),this.mouseCollector.flush(),this.scrollCollector.flush(),this.formCollector.flush(),this.hasSentInitial=!0,E.bot_score}return this.mouseCollector.flush(),this.scrollCollector.flush(),this.formCollector.flush(),this.hasSentInitial=!0,null}catch(Q){let E=Q instanceof Error?Q:Error(String(Q));return this.log("Failed to send signal for form scoring",E),this.config.onError?.(E),null}}getSessionId(){return this.sessionId}getFingerprint(){return this.fingerprint}getFormSubmissionStatus(){return this.formSubmissionStatus}getLastScore(){return this.lastScore}isConnected(){return this.socket?.isReady()??!1}whenReady(){if(this.connectionState==="connected")return Promise.resolve();return this.readyPromise}getConnectionState(){return this.connectionState}getServerConfig(){return this.serverConfig}async identify(A){let{accountId:B}=A;if(!B||typeof B!=="string")throw Error("BotSigged: accountId is required and must be a string");if(B.length>255)throw Error("BotSigged: accountId must be 255 characters or less");this.log("Identifying account:",B),await this.whenReady();try{let Q=await this.socket.sendEvent("identify",{account_id:B,timestamp:Date.now()});if(Q.identified)this.log("Account identified successfully");else throw Error(Q.reason?.toString()||"Failed to identify account")}catch(Q){let E=Q instanceof Error?Q:Error(String(Q));throw this.log("Failed to identify account:",E),this.config.onError?.(E),E}}isDegraded(){return this.connectionState==="degraded"||this.connectionState==="failed"}getCurrentSignals(){return{mouse:this.mouseCollector.getSignal(),scroll:this.scrollCollector.getSignal(),form:this.formCollector.getSignal(),browser:this.browserSignal}}getBufferSizes(){return{mouse:this.mouseCollector.getBufferSize(),scroll:this.scrollCollector.getBufferSize(),form:this.formCollector.getBufferSize()}}resetSignals(){this.mouseCollector.reset(),this.scrollCollector.reset(),this.formCollector.reset(),this.browserCollector.reset(),this.sequenceNumber=0,this.hasSentInitial=!1}async connectSocket(){this.socket=new n({endpoint:this.config.endpoint,apiKey:this.config.apiKey,debug:this.config.debug,onConnectionChange:(A)=>{this.config.onConnectionChange?.(A==="connected")},onError:(A)=>{this.config.onError?.(A)}}),await this.socket.connect(),J.markWsConnectEnd(),this.log("WebSocket connected in",(J.getTimings().wsConnectEnd??0)-(J.getTimings().wsConnectStart??0),"ms")}async connectWithRetry(){let B=[1000,2000,4000];for(let Q=0;Q<3;Q++)try{await this.connectSocket();return}catch(E){if(this.log(`Connection attempt ${Q+1} failed:`,E),Q<2)await this.sleep(B[Q]);else throw E}}sleep(A){return new Promise((B)=>setTimeout(B,A))}handleConnectionFailure(A){this.connectionState="failed";let B=this.config.fallbackMode||"degraded";switch(this.log("Connection failed, applying fallback mode:",B),B){case"open":if(this.connectionState="degraded",this.formProtectionManager)this.formProtectionManager.setMode("none"),this.formProtectionManager.notifyReady(0);break;case"closed":this.blockFormsUntilConnected(),this.scheduleReconnect();break;case"cached":let Q=this.loadCachedConfig();if(Q)this.applyServerConfig(Q),this.connectionState="degraded";else this.applyFallbackConfig();this.scheduleReconnect();break;case"degraded":default:this.applyFallbackConfig(),this.connectionState="degraded",this.scheduleReconnect();break}this.config.onError?.(A),this.config.onConnectionChange?.(!1)}applyFallbackConfig(){if(this.log("Applying fallback config"),this.serverConfig=EA,this.formProtectionManager&&this.serverConfig.form_protection_mode)this.formProtectionManager.setMode(this.serverConfig.form_protection_mode);this.config.onServerConfig?.(this.serverConfig,"fallback")}blockFormsUntilConnected(){if(this.formProtectionManager)this.formProtectionManager.setMode("holdUntilReady"),this.formProtectionManager.setMaxHoldTime(30000)}scheduleReconnect(){if(this.reconnectTimer)clearTimeout(this.reconnectTimer);this.reconnectTimer=setTimeout(()=>{this.attemptReconnect()},5000)}async attemptReconnect(){this.log("Attempting reconnection..."),this.connectionState="connecting";try{if(await this.connectWithRetry(),!this.fingerprint)this.fingerprint=await this.fingerprintGenerator.generate();if(await this.joinChannel(),this.connectionState="connected",this.readyResolver?.(),this.log("Reconnection successful"),!this.sendTimer)this.startSendInterval()}catch(A){this.log("Reconnection failed:",A),this.connectionState="failed"}}cacheServerConfig(A){try{localStorage.setItem(`botsigged_config_${this.config.apiKey}`,JSON.stringify({config:A,timestamp:Date.now()}))}catch{}}loadCachedConfig(){try{let A=localStorage.getItem(`botsigged_config_${this.config.apiKey}`);if(!A)return null;let{config:B,timestamp:Q}=JSON.parse(A);if(Date.now()-Q>86400000)return localStorage.removeItem(`botsigged_config_${this.config.apiKey}`),null;return B}catch{return null}}applyServerConfig(A){if(this.log("Applying server config:",A),this.serverConfig=A,this.formProtectionManager&&A.form_protection_mode)this.formProtectionManager.setMode(A.form_protection_mode);if(A.action&&A.action!=="none")this.applyServerAction(A.action,A.challenge);this.cacheServerConfig(A),this.config.onServerConfig?.(A,"server")}async applyServerAction(A,B){switch(this.log("Applying server action:",A),A){case"block":if(this.updateFormStatus("blocked"),!this.formBlocked)this.blockForms();break;case"challenge":if(this.updateFormStatus("challenged"),!this.challengeManager&&!this.challengeManagerPromise)this.log("Lazily loading challenge manager for server-requested challenge"),this.challengeManagerPromise=this.initializeChallengeManager();if(this.challengeManagerPromise)await this.challengeManagerPromise;if(this.challengeManager){let Q=B?.difficulty?.bot??16,E=Q>=18?"critical":Q>=16?"high":"medium";this.challengeManager.blockFormsUntilSolved(E)}else this.log("Challenge requested but challenge manager failed to load");break;case"flag":this.updateFormStatus("flagged"),this.log("Session flagged by server");break;case"none":default:break}}handleServerAction(A){this.log("Received server action:",A),this.config.onServerAction?.(A);let B=A.challenge?{difficulty:{suspicious:A.challenge.difficulty,bot:A.challenge.difficulty},timeout_ms:A.challenge.timeout_ms}:void 0;this.applyServerAction(A.type,B)}async joinChannel(){if(!this.socket)throw Error("WebSocket not initialized");J.markChannelJoinStart();let A;try{A=await this.socket.joinChannel(this.sessionId,this.fingerprint,this.getSessionData(),this.browserSignal,{onScoreUpdate:(B)=>{this.lastScore=B,this.config.onScoreUpdate?.(B),this.handleScoreUpdate(B)},onError:(B)=>{this.config.onError?.(B)},onAction:(B)=>{this.handleServerAction(B)}},this.config.accountId)}catch(B){if(QA(B)){if(this.log("Usage limit exceeded:",B),this.config.onUsageLimitExceeded)this.config.onUsageLimitExceeded(B);else this.config.onError?.(Error(`Usage limit exceeded: ${B.current_usage}/${B.limit} verifications (${B.plan_name} plan). Please upgrade your plan.`));return}throw B}if(J.markChannelJoinEnd(),this.log("Channel joined in",(J.getTimings().channelJoinEnd??0)-(J.getTimings().channelJoinStart??0),"ms"),A.config){let B=A.config;this.applyServerConfig(B)}if(A.initial_score!==void 0){J.markInitialScoreReceived();let B={bot_score:A.initial_score,classification:A.classification||"unknown",triggered_rules:A.triggered_rules||[]};if(this.lastScore=B,this.config.onScoreUpdate?.(B),this.handleScoreUpdate(B),this.formProtectionManager)this.formProtectionManager.notifyReady(B.bot_score);if(this.cookieManager)this.cookieManager.setCookie();this.log("Initial score received:",B.bot_score,"in",(J.getTimings().initialScoreReceived??0)-(J.getTimings().startCalled??0),"ms from start")}}handleScoreUpdate(A){if(this.cookieManager)this.cookieManager.updateRiskTier(A.bot_score);let B=this.getBotScoreLevel(A.bot_score),Q=A.bot_score>=this.config.actionThreshold;if(this.shouldTriggerAlert(B)){let E={score:A.bot_score,level:B,scoreUpdate:A,sessionId:this.sessionId,fingerprintHash:this.fingerprint?.hash};if(Q&&!this.highScoreTriggeredLevels.has(B))this.executeAction(E);this.config.onHighBotScore?.(E),this.highScoreTriggeredLevels.add(B)}}getBotScoreLevel(A){let B=this.config.botScoreThresholds;if(A>=B.critical)return"critical";if(A>=B.high)return"high";if(A>=B.medium)return"medium";return"low"}shouldTriggerAlert(A){if(this.highScoreTriggeredLevels.has(A))return!1;let B=["low","medium","high","critical"],Q=this.config.minAlertLevel,E=B.indexOf(A),I=B.indexOf(Q);return E>=I}async executeAction(A){let B=this.config.action;switch(this.log(`Executing action '${B}' for score ${A.score}`),B){case"challenge":if(this.challengeManagerPromise)await this.challengeManagerPromise;if(this.challengeManager)this.challengeManager.blockFormsUntilSolved(A.level);break;case"block":if(!this.formBlocked)this.blockForms();break;case"none":default:break}}blockForms(){if(this.formBlocked)return;this.formBlocked=!0,document.querySelectorAll("form").forEach((A)=>{A.addEventListener("submit",this.blockFormSubmit,!0)}),this.formObserver=new MutationObserver((A)=>{A.forEach((B)=>{B.addedNodes.forEach((Q)=>{if(Q instanceof HTMLFormElement)Q.addEventListener("submit",this.blockFormSubmit,!0);if(Q instanceof HTMLElement)Q.querySelectorAll("form").forEach((E)=>{E.addEventListener("submit",this.blockFormSubmit,!0)})})})}),this.formObserver.observe(document.body,{childList:!0,subtree:!0}),this.log("Forms blocked due to high bot score")}blockFormSubmit=(A)=>{A.preventDefault(),A.stopPropagation(),this.log("Form submission blocked due to high bot score");return};isFormsBlocked(){return this.formBlocked}unblockForms(){if(!this.formBlocked)return;if(this.formObserver)this.formObserver.disconnect(),this.formObserver=null;document.querySelectorAll("form").forEach((A)=>{A.removeEventListener("submit",this.blockFormSubmit,!0)}),this.formBlocked=!1,this.log("Forms unblocked")}getHashModule(){return this.hashModule}createSignature(A){let B=this.config.hashVerification.secret;if(!B)return this.log("Cannot create signature: no secret configured"),null;return createSignature(A,B)}verifySignature(A,B){let Q=this.config.hashVerification.secret;if(!Q)return this.log("Cannot verify signature: no secret configured"),!1;return verifySignature(A,B,Q)}isChallengeSolving(){return this.challengeManager?.isSolving()??!1}isChallengeSolved(){return this.challengeManager?.isSolved()??!1}getPerformanceSummary(){return J.getSummary()}logPerformance(){J.logSummary()}getPerformanceReport(){return J.getReport()}async waitUntilReady(){if(this.lastScore)return{score:this.lastScore.bot_score,timedOut:!1};if(this.formProtectionManager)return this.formProtectionManager.waitUntilReady();return new Promise((A)=>{let B=performance.now(),Q=5000,E=()=>{if(this.lastScore){A({score:this.lastScore.bot_score,timedOut:!1});return}if(performance.now()-B>=5000){A({score:null,timedOut:!0});return}setTimeout(E,50)};E()})}withProtection(A,B={}){let Q=B.blockThreshold??this.config.actionThreshold;return async(...E)=>{let{score:I,timedOut:C}=await this.waitUntilReady();if(J.markFirstSubmitAttempt(I!==null),I!==null&&I>=Q)throw this.log(`Blocking submission: score ${I} >= threshold ${Q}`),Error(`Submission blocked: bot score ${I} exceeds threshold`);if(C)this.log("Warning: submitting without detection score (timed out)");return A(...E)}}protectedFetch(A={}){return this.withProtection(async(B,Q)=>{return fetch(B,Q)},A)}canSubmit(){if(!this.lastScore)return{allowed:!1,reason:"waiting_for_score",score:null};if(this.lastScore.bot_score>=this.config.actionThreshold)return{allowed:!1,reason:"high_bot_score",score:this.lastScore.bot_score};return{allowed:!0,score:this.lastScore.bot_score}}async triggerChallenge(A="high"){if(this.challengeManagerPromise)await this.challengeManagerPromise;if(!this.challengeManager){this.log("Challenge not enabled");return}this.challengeManager.blockFormsUntilSolved(A)}async disconnect(){if(this.socket)await this.socket.leaveChannel(),this.socket.disconnect(),this.socket=null}startSendInterval(){this.stopSendInterval(),this.sendTimer=setInterval(()=>{this.sendSignal()},this.config.sendInterval)}stopSendInterval(){if(this.sendTimer)clearInterval(this.sendTimer),this.sendTimer=null}registerBeforeUnload(){this.boundBeforeUnload=()=>{this.handleBeforeUnload()},this.boundVisibilityChange=()=>{if(document.visibilityState==="hidden")this.handleBeforeUnload()},window.addEventListener("beforeunload",this.boundBeforeUnload),document.addEventListener("visibilitychange",this.boundVisibilityChange)}unregisterBeforeUnload(){if(this.boundBeforeUnload)window.removeEventListener("beforeunload",this.boundBeforeUnload),this.boundBeforeUnload=null;if(this.boundVisibilityChange)document.removeEventListener("visibilitychange",this.boundVisibilityChange),this.boundVisibilityChange=null}handleBeforeUnload(){if(!this.isRunning||!this.socket)return;try{let A=this.buildPayload();if(this.socket.isReady())this.socket.sendSignal(A).catch(()=>{})}catch{}}handleFormSubmit(){if(!this.isRunning)return;if(J.markFirstSubmitAttempt(this.lastScore!==null),this.log("Form submitted, flushing signals via beacon"),this.log("Had score before submit:",this.lastScore!==null),this.updateFormStatus("completed"),!this.sessionId){this.log("No session ID yet, cannot send beacon");return}let A=this.buildPayload();if(!this.sendViaBeacon(A))this.sendSignal().catch((Q)=>{this.log("Failed to flush signals on form submit",Q)});else this.mouseCollector.flush(),this.scrollCollector.flush(),this.formCollector.flush()}sendViaBeacon(A){if(!navigator.sendBeacon)return this.log("sendBeacon not available"),!1;try{let B=new URL(this.config.endpoint),Q=`${B.protocol==="wss:"?"https:":"http:"}//${B.host}/api/signal`,E=JSON.stringify({session_id:this.sessionId,api_key:this.config.apiKey,payload:A,form_status:this.formSubmissionStatus}),I=new Blob([E],{type:"application/json"}),C=navigator.sendBeacon(Q,I);return this.log("Beacon sent:",C),C}catch(B){return this.log("Beacon send failed:",B),!1}}buildPayload(){this.sequenceNumber++;let A={session_id:this.sessionId,seq:this.sequenceNumber,mouse:this.mouseCollector.getSignal(),scroll:this.scrollCollector.getSignal(),form:this.formCollector.getSignal(),timestamp:Date.now()};if(!this.hasSentInitial)A.session=this.getSessionData(),A.fingerprint=this.fingerprint,A.browser=this.browserSignal;return A}getSessionData(){let A=new URL(window.location.href),B={};A.searchParams.forEach((E,I)=>{B[I]=E});let Q=null;if(document.referrer)try{Q=new URL(document.referrer).hostname}catch{}return{url_path:A.pathname,url_params:B,referrer_url:document.referrer||null,referrer_domain:Q,user_agent:navigator.userAgent}}generateSessionId(){if(crypto.randomUUID)return crypto.randomUUID();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(A)=>{let B=Math.random()*16|0;return(A==="x"?B:B&3|8).toString(16)})}updateFormStatus(A){if(this.formSubmissionStatus==="challenged"||this.formSubmissionStatus==="flagged"||this.formSubmissionStatus==="blocked"||this.formSubmissionStatus==="completed"){this.log(`Form status already terminal (${this.formSubmissionStatus}), ignoring ${A}`);return}if(this.formSubmissionStatus=A,this.log(`Form status updated to: ${A}`),this.socket?.isReady())this.socket.sendFormStatus(A).catch((B)=>{this.log("Failed to send form status:",B)})}log(...A){if(this.config.debug)console.log("[BotSigged]",...A)}}var HB=K.init.bind(K),$B=K.getInstance.bind(K),VB=K.destroy.bind(K);if(typeof window<"u")window.BotSigged=K;})();
@@ -0,0 +1,3 @@
1
+ import{c as V}from"./hash-q46pgar4.js";class U{overlay=null;messageEl=null;progressEl=null;config;constructor(j){this.config=j}show(){return}setProgress(j){if(this.progressEl){let q=Math.min(100,Math.max(0,j*100));this.progressEl.style.width=`${q}%`}}showSuccess(){if(this.messageEl)this.messageEl.textContent=this.config.successMessage;if(this.progressEl)this.progressEl.style.width="100%"}hide(){if(this.overlay)this.overlay.remove(),this.overlay=null,this.messageEl=null,this.progressEl=null}isVisible(){return this.overlay!==null}}function _(){let j=new Uint8Array(16);if(typeof crypto<"u"&&crypto.getRandomValues)crypto.getRandomValues(j);else for(let q=0;q<16;q++)j[q]=Math.floor(Math.random()*256);return j}function $(j){if(j===0)return 32;let q=0;if((j&4294901760)===0)q+=16,j<<=16;if((j&4278190080)===0)q+=8,j<<=8;if((j&4026531840)===0)q+=4,j<<=4;if((j&3221225472)===0)q+=2,j<<=2;if((j&2147483648)===0)q+=1;return q}function B(j,q,A,E){let G=V(),F=new Uint8Array(j.length+4);F.set(j);let w=E,D=0;while(D<A){F[j.length]=w&255,F[j.length+1]=w>>>8&255,F[j.length+2]=w>>>16&255,F[j.length+3]=w>>>24&255;let K=G.xxHash32(F,0);if(D++,$(K)>=q)return{nonce:w,found:!0,iterations:D};w=w+1>>>0}return{nonce:w,found:!1,iterations:D}}class H{config;overlay;solving=!1;solved=!1;pendingForms=new Map;formHandler=null;formObserver=null;resubmitting=!1;debug;constructor(j,q=!1){this.config=j,this.debug=q,this.overlay=new U(j.ui)}getDifficultyForLevel(j){let q=this.config.difficulty;switch(j){case"critical":return q.critical;case"high":return q.high;case"medium":return q.medium;default:return 0}}shouldChallenge(j){if(!this.config.enabled||this.solved)return!1;let q=["low","medium","high","critical"],A=q.indexOf(j),E=q.indexOf(this.config.minLevel);return A>=E}blockFormsUntilSolved(j){if(this.formHandler)return;this.formHandler=(q)=>{if(this.solved||this.resubmitting)return;q.preventDefault(),q.stopPropagation();let A=q.target;if(!this.pendingForms.has(A))this.pendingForms.set(A,q);if(!this.solving)this.startChallenge(j)},document.querySelectorAll("form").forEach((q)=>{q.addEventListener("submit",this.formHandler,!0)}),this.formObserver=new MutationObserver((q)=>{q.forEach((A)=>{A.addedNodes.forEach((E)=>{if(E instanceof HTMLFormElement&&this.formHandler)E.addEventListener("submit",this.formHandler,!0);if(E instanceof HTMLElement&&this.formHandler)E.querySelectorAll("form").forEach((G)=>{G.addEventListener("submit",this.formHandler,!0)})})})}),this.formObserver.observe(document.body,{childList:!0,subtree:!0}),this.log("Forms blocked, challenge required")}async startChallenge(j){if(this.solving||this.solved)return;this.solving=!0;let q=this.getDifficultyForLevel(j),A=_(),E=performance.now();this.log(`Starting challenge: difficulty=${q}, level=${j}`),this.config.onChallengeStart?.(j,q),this.overlay.show();let G=1<<q,F=0,w=0,D;do{await new Promise((Y)=>setTimeout(Y,0)),D=B(A,q,this.config.chunkSize,F),w+=D.iterations,F=D.nonce+1;let Q=Math.min(1,w/G);this.overlay.setProgress(Q),this.config.onChallengeProgress?.(Q,w)}while(!D.found);let K=performance.now()-E;this.log(`Challenge solved: nonce=${D.nonce}, iterations=${w}, time=${K.toFixed(0)}ms`),this.overlay.showSuccess(),await new Promise((Q)=>setTimeout(Q,500)),this.overlay.hide(),this.solved=!0,this.solving=!1;let X={solveTimeMs:K,iterations:w,difficulty:q,level:j,nonce:D.nonce};this.config.onChallengeComplete?.(X),this.unblockForms()}unblockForms(){if(this.formObserver)this.formObserver.disconnect(),this.formObserver=null;if(this.formHandler)document.querySelectorAll("form").forEach((j)=>{j.removeEventListener("submit",this.formHandler,!0)}),this.formHandler=null;this.log("Forms unblocked"),this.resubmitting=!0,this.pendingForms.forEach((j,q)=>{if(this.log("Resubmitting pending form"),q.requestSubmit)q.requestSubmit();else q.submit()}),this.pendingForms.clear(),this.resubmitting=!1}isSolving(){return this.solving}isSolved(){return this.solved}reset(){if(this.formObserver)this.formObserver.disconnect(),this.formObserver=null;if(this.formHandler)document.querySelectorAll("form").forEach((j)=>{j.removeEventListener("submit",this.formHandler,!0)}),this.formHandler=null;this.solved=!1,this.solving=!1,this.resubmitting=!1,this.pendingForms.clear()}log(...j){if(this.debug);}}export{H as ChallengeManager};
2
+
3
+ //# debugId=B58B5FCA888C5C8764756E2164756E21