πΈ Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Bot blocking (#953)
Goldflagd1cd01cd3aee
diff --git a/server/public/script-full.js b/server/public/script-full.jsindex edcf1fe87..ad3597845 100644--- a/server/public/script-full.js+++ b/server/public/script-full.js@@ -380,6 +380,49 @@}};+ // botSignals.ts+ function getBotScore() {+ let score = 0;+ try {+ if (navigator.webdriver === true) {+ score++;+ }+ if (window.outerHeight === 0 || window.outerWidth === 0) {+ score++;+ }+ if (navigator.connection?.rtt === 0) {+ score++;+ }+ if (!window.chrome && /Chrome\//.test(navigator.userAgent)) {+ score++;+ }+ try {+ const canvas = document.createElement("canvas");+ const gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");+ if (gl) {+ const debugInfo = gl.getExtension("WEBGL_debug_renderer_info");+ if (debugInfo) {+ const renderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);+ if (typeof renderer === "string" && renderer.includes("SwiftShader")) {+ score++;+ }+ }+ }+ } catch (e2) {+ }+ if (navigator.plugins.length === 0 && /Chrome\//.test(navigator.userAgent)) {+ score++;+ }+ try {+ if (typeof Notification !== "undefined" && Notification.permission === "denied") {+ }+ } catch (e2) {+ }+ } catch (e2) {+ }+ return score;+ }+// tracking.tsvar Tracker = class {constructor(config) {@@ -452,7 +495,8 @@screenHeight: screen.height,language: navigator.language,page_title: document.title,- referrer: document.referrer+ referrer: document.referrer,+ _bs: getBotScore()};if (this.customUserId) {payload.user_id = this.customUserId;diff --git a/server/public/script.js b/server/public/script.jsindex 4af5a0a42..545cb3906 100644--- a/server/public/script.js+++ b/server/public/script.js@@ -1 +1 @@-"use strict";(()=>{var Ae=Object.defineProperty;var Le=(n,e,t)=>e in n?Ae(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var k=(n,e,t)=>Le(n,typeof e!="symbol"?e+"":e,t);function Be(n){if(n.startsWith("re:")){let l=n.slice(3);if(!l)throw new Error("Empty regex pattern");return new RegExp(l)}let t="__DOUBLE_ASTERISK_TOKEN__",r="__SINGLE_ASTERISK_TOKEN__",s=n.replace(/\*\*/g,t).replace(/\*/g,r).replace(/[.+?^${}()|[\]\\]/g,"\\$&");s=s.replace(new RegExp(`/${t}/`,"g"),"/(?:.+/)?"),s=s.replace(new RegExp(t,"g"),".*"),s=s.replace(/\//g,"\\/");let a=s.replace(new RegExp(r,"g"),"[^/]+");return new RegExp("^"+a+"$")}function F(n,e){for(let t of e)try{if(Be(t).test(n))return t}catch(r){console.error(`Invalid pattern: ${t}`,r)}return null}function se(n,e){let t=null;return(...r)=>{t&&clearTimeout(t),t=setTimeout(()=>n(...r),e)}}function ae(n){try{let e=window.location.hostname,t=new URL(n).hostname;return t!==e&&t!==""}catch{return!1}}function R(n,e){if(!n)return e;try{let t=JSON.parse(n);return Array.isArray(e)&&!Array.isArray(t)?e:t}catch(t){return console.error("Error parsing JSON:",t),e}}async function oe(n){let e=n.getAttribute("src");if(!e)return console.error("Script src attribute is missing"),null;let t=e.split("/script.js")[0];if(!t)return console.error("Please provide a valid analytics host"),null;let r=n.getAttribute("data-site-id")||n.getAttribute("site-id");if(!r)return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let i=n.getAttribute("data-namespace")||"rybbit",s=R(n.getAttribute("data-skip-patterns"),[]),a=R(n.getAttribute("data-mask-patterns"),[]),l=R(n.getAttribute("data-replay-mask-text-selectors"),[]),d=n.getAttribute("data-debounce")?Math.max(0,parseInt(n.getAttribute("data-debounce"))):500,u=n.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(n.getAttribute("data-replay-batch-size"))):250,h=n.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(n.getAttribute("data-replay-batch-interval"))):5e3,b=n.getAttribute("data-replay-block-class")||void 0,C=n.getAttribute("data-replay-block-selector")||void 0,v=n.getAttribute("data-replay-ignore-class")||void 0,o=n.getAttribute("data-replay-ignore-selector")||void 0,c=n.getAttribute("data-replay-mask-text-class")||void 0,p=n.getAttribute("data-replay-mask-all-inputs"),I=p!==null?p!=="false":void 0,T=n.getAttribute("data-replay-mask-input-options"),U=T?R(T,{password:!0,email:!0}):void 0,ee=n.getAttribute("data-replay-collect-fonts"),Ce=ee!==null?ee!=="false":void 0,te=n.getAttribute("data-replay-sampling"),we=te?R(te,{}):void 0,re=n.getAttribute("data-replay-slim-dom-options"),Pe=re?R(re,{}):void 0,ne=n.getAttribute("data-replay-sample-rate"),Ie=ne?Math.min(100,Math.max(0,parseInt(ne,10))):void 0,Me=n.getAttribute("data-tag")||"",g={namespace:i,analyticsHost:t,siteId:r,debounceDuration:d,sessionReplayBatchSize:u,sessionReplayBatchInterval:h,sessionReplayMaskTextSelectors:l,skipPatterns:s,maskPatterns:a,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,trackButtonClicks:!1,trackCopy:!1,trackFormInteractions:!1,tag:Me,sessionReplayBlockClass:b,sessionReplayBlockSelector:C,sessionReplayIgnoreClass:v,sessionReplayIgnoreSelector:o,sessionReplayMaskTextClass:c,sessionReplayMaskAllInputs:I,sessionReplayMaskInputOptions:U,sessionReplayCollectFonts:Ce,sessionReplaySampling:we,sessionReplaySlimDOMOptions:Pe,sessionReplaySampleRate:Ie};try{let H=`${t}/site/tracking-config/${r}`,ie=await fetch(H,{method:"GET",credentials:"omit"});if(ie.ok){let f=await ie.json();return{...g,autoTrackPageview:f.trackInitialPageView??g.autoTrackPageview,autoTrackSpa:f.trackSpaNavigation??g.autoTrackSpa,trackQuerystring:f.trackUrlParams??g.trackQuerystring,trackOutbound:f.trackOutbound??g.trackOutbound,enableWebVitals:f.webVitals??g.enableWebVitals,trackErrors:f.trackErrors??g.trackErrors,enableSessionReplay:f.sessionReplay??g.enableSessionReplay,trackButtonClicks:f.trackButtonClicks??g.trackButtonClicks,trackCopy:f.trackCopy??g.trackCopy,trackFormInteractions:f.trackFormInteractions??g.trackFormInteractions}}else return console.warn("Failed to fetch tracking config from API, using defaults"),g}catch(H){return console.warn("Error fetching tracking config:",H),g}}var ce="rybbit-replay-sampled";function xe(n){if(n>=100)return!0;if(n<=0)return!1;try{let e=sessionStorage.getItem(ce);if(e!==null)return e==="1";let t=Math.random()*100<n;return sessionStorage.setItem(ce,t?"1":"0"),t}catch{return Math.random()*100<n}}var M=class{constructor(e,t,r){this.isRecording=!1;this.eventBuffer=[];this.config=e,this.userId=t,this.sendBatch=r}async initialize(){if(!this.config.enableSessionReplay)return;let e=this.config.sessionReplaySampleRate;e!==void 0&&!xe(e)||(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((e,t)=>{let r=document.createElement("script");r.src=`${this.config.analyticsHost}/replay.js`,r.async=!1,r.onload=()=>{e()},r.onerror=()=>t(new Error("Failed to load rrweb")),document.head.appendChild(r)})}startRecording(){if(!(this.isRecording||!window.rrweb||!this.config.enableSessionReplay))try{let e={mousemove:!1,mouseInteraction:{MouseUp:!1,MouseDown:!1,Click:!0,ContextMenu:!1,DblClick:!0,Focus:!0,Blur:!0,TouchStart:!1,TouchEnd:!1},scroll:500,input:"last",media:800},t={script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},r={emit:i=>{this.addEvent({type:i.type,data:i.data,timestamp:i.timestamp||Date.now()})},recordCanvas:!1,checkoutEveryNms:6e4,checkoutEveryNth:500,blockClass:this.config.sessionReplayBlockClass??"rr-block",blockSelector:this.config.sessionReplayBlockSelector??null,ignoreClass:this.config.sessionReplayIgnoreClass??"rr-ignore",ignoreSelector:this.config.sessionReplayIgnoreSelector??null,maskTextClass:this.config.sessionReplayMaskTextClass??"rr-mask",maskAllInputs:this.config.sessionReplayMaskAllInputs??!0,maskInputOptions:this.config.sessionReplayMaskInputOptions??{password:!0,email:!0},collectFonts:this.config.sessionReplayCollectFonts??!0,sampling:this.config.sessionReplaySampling??e,slimDOMOptions:this.config.sessionReplaySlimDOMOptions??t};this.config.sessionReplayMaskTextSelectors&&this.config.sessionReplayMaskTextSelectors.length>0&&(r.maskTextSelector=this.config.sessionReplayMaskTextSelectors.join(", ")),this.stopRecordingFn=window.rrweb.record(r),this.isRecording=!0,this.setupBatchTimer()}catch{}}stopRecording(){this.isRecording&&(this.stopRecordingFn&&this.stopRecordingFn(),this.isRecording=!1,this.clearBatchTimer(),this.eventBuffer.length>0&&this.flushEvents())}isActive(){return this.isRecording}addEvent(e){this.eventBuffer.push(e),this.eventBuffer.length>=this.config.sessionReplayBatchSize&&this.flushEvents()}setupBatchTimer(){this.clearBatchTimer(),this.batchTimer=window.setInterval(()=>{this.eventBuffer.length>0&&this.flushEvents()},this.config.sessionReplayBatchInterval)}clearBatchTimer(){this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0)}async flushEvents(){if(this.eventBuffer.length===0)return;let e=[...this.eventBuffer];this.eventBuffer=[];let t={userId:this.userId,events:e,metadata:{pageUrl:window.location.href,viewportWidth:screen.width,viewportHeight:screen.height,language:navigator.language}};try{await this.sendBatch(t)}catch{this.eventBuffer.unshift(...e)}}updateUserId(e){this.userId=e}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var A=class{constructor(e){this.customUserId=null;this.errorDedupeCache=new Map;this.errorDedupeLastCleanup=0;this.config=e,this.loadUserId(),e.enableSessionReplay&&this.initializeSessionReplay()}loadUserId(){try{let e=localStorage.getItem(`${this.config.namespace}-user-id`);e&&(this.customUserId=e)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new M(this.config,this.customUserId||"",e=>this.sendSessionReplayBatch(e)),await this.sessionReplayRecorder.initialize()}catch(e){console.error("Failed to initialize session replay:",e)}}async sendSessionReplayBatch(e){try{await fetch(`${this.config.analyticsHost}/session-replay/record/${this.config.siteId}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),mode:"cors",keepalive:!1})}catch(t){throw console.error("Failed to send session replay batch:",t),t}}createBasePayload(){let e=new URL(window.location.href),t=e.pathname;if(e.hash&&e.hash.startsWith("#/")&&(t=e.hash.substring(1)),F(t,this.config.skipPatterns))return null;let r=F(t,this.config.maskPatterns);r&&(t=r);let i={site_id:this.config.siteId,hostname:e.hostname,pathname:t,querystring:this.config.trackQuerystring?e.search:"",screenWidth:screen.width,screenHeight:screen.height,language:navigator.language,page_title:document.title,referrer:document.referrer};return this.customUserId&&(i.user_id=this.customUserId),this.config.tag&&(i.tag=this.config.tag),i}async sendTrackingData(e){try{await fetch(`${this.config.analyticsHost}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),mode:"cors",keepalive:!0})}catch(t){console.error("Failed to send tracking data:",t)}}track(e,t="",r={}){if(e==="custom_event"&&(!t||typeof t!="string")){console.error("Event name is required and must be a string for custom events");return}let i=this.createBasePayload();if(!i)return;let a={...i,type:e,event_name:t,properties:["custom_event","outbound","error","button_click","copy","form_submit","input_change"].includes(e)?JSON.stringify(r):void 0};this.sendTrackingData(a)}trackPageview(){this.track("pageview")}trackEvent(e,t={}){this.track("custom_event",e,t)}trackOutbound(e,t="",r="_self"){this.track("outbound","",{url:e,text:t,target:r})}trackWebVitals(e){let t=this.createBasePayload();if(!t)return;let r={...t,type:"performance",event_name:"web-vitals",...e};this.sendTrackingData(r)}trackError(e,t={}){let r=e?.message||"";if(r.includes("ResizeObserver loop completed with undelivered notifications")||r.includes("ResizeObserver loop limit exceeded"))return;let i=window.location.origin,s=t.filename||"",a=e.stack||"";if(s)try{if(new URL(s).origin!==i)return}catch{}else if(a&&!a.includes(i))return;let d=[e.name||"Error",r,t.filename||"",t.lineno??"",t.colno??""].join("|"),u=Date.now(),h=6e4,b=this.errorDedupeCache.get(d);if(b&&u-b<h)return;this.errorDedupeCache.set(d,u);let C=10*6e4;if(u-this.errorDedupeLastCleanup>h){for(let[o,c]of this.errorDedupeCache.entries())u-c>C&&this.errorDedupeCache.delete(o);this.errorDedupeLastCleanup=u}let v={message:e.message?.substring(0,500)||"Unknown error",stack:a.substring(0,2e3)||""};if(s&&(v.fileName=s),t.lineno){let o=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;o&&o!==0&&(v.lineNumber=o)}if(t.colno){let o=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;o&&o!==0&&(v.columnNumber=o)}for(let o in t)!["lineno","colno"].includes(o)&&t[o]!==void 0&&(v[o]=t[o]);this.track("error",e.name||"Error",v)}trackButtonClick(e){this.track("button_click","",e)}trackCopy(e){this.track("copy","",e)}trackFormSubmit(e){this.track("form_submit","",e)}trackInputChange(e){this.track("input_change","",e)}identify(e,t){if(typeof e!="string"||e.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=e.trim();try{localStorage.setItem(`${this.config.namespace}-user-id`,this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}this.sendIdentifyEvent(this.customUserId,t,!0),this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(this.customUserId)}setTraits(e){if(!e||typeof e!="object"){console.error("Traits must be an object");return}let t=this.customUserId;if(!t){console.warn("Cannot set traits without identifying user first. Call identify() first.");return}this.sendIdentifyEvent(t,e,!1)}async sendIdentifyEvent(e,t,r=!0){try{await fetch(`${this.config.analyticsHost}/identify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({site_id:this.config.siteId,user_id:e,traits:t,is_new_identify:r}),mode:"cors",keepalive:!0})}catch(i){console.error("Failed to send identify event:",i)}}clearUserId(){this.customUserId=null;try{localStorage.removeItem(`${this.config.namespace}-user-id`)}catch{}}getUserId(){return this.customUserId}startSessionReplay(){this.sessionReplayRecorder?this.sessionReplayRecorder.startRecording():console.warn("Session replay not initialized")}stopSessionReplay(){this.sessionReplayRecorder&&this.sessionReplayRecorder.stopRecording()}isSessionReplayActive(){return this.sessionReplayRecorder?.isActive()??!1}onPageChange(){this.sessionReplayRecorder&&this.sessionReplayRecorder.onPageChange()}cleanup(){this.sessionReplayRecorder&&this.sessionReplayRecorder.cleanup()}};var ye=-1,S=n=>{addEventListener("pageshow",(e=>{e.persisted&&(ye=e.timeStamp,n(e))}),!0)},m=(n,e,t,r)=>{let i,s;return a=>{e.value>=0&&(a||r)&&(s=e.value-(i??0),(s||i===void 0)&&(i=e.value,e.delta=s,e.rating=((l,d)=>l>d[1]?"poor":l>d[0]?"needs-improvement":"good")(e.value,t),n(e)))}},G=n=>{requestAnimationFrame((()=>requestAnimationFrame((()=>n()))))},Q=()=>{let n=performance.getEntriesByType("navigation")[0];if(n&&n.responseStart>0&&n.responseStart<performance.now())return n},w=()=>Q()?.activationStart??0,y=(n,e=-1)=>{let t=Q(),r="navigate";return ye>=0?r="back-forward-cache":t&&(document.prerendering||w()>0?r="prerender":document.wasDiscarded?r="restore":t.type&&(r=t.type.replace(/_/g,"-"))),{name:n,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:r}},W=new WeakMap;function X(n,e){return W.get(n)||W.set(n,new e),W.get(n)}var V=class{constructor(){k(this,"t");k(this,"i",0);k(this,"o",[])}h(e){if(e.hadRecentInput)return;let t=this.o[0],r=this.o.at(-1);this.i&&t&&r&&e.startTime-r.startTime<1e3&&e.startTime-t.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}},P=(n,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(n)){let r=new PerformanceObserver((i=>{Promise.resolve().then((()=>{e(i.getEntries())}))}));return r.observe({type:n,buffered:!0,...t}),r}}catch{}},Y=n=>{let e=!1;return()=>{e||(n(),e=!0)}},E=-1,be=new Set,le=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,$=n=>{if(document.visibilityState==="hidden"){if(n.type==="visibilitychange")for(let e of be)e();isFinite(E)||(E=n.type==="visibilitychange"?n.timeStamp:0,removeEventListener("prerenderingchange",$,!0))}},B=()=>{if(E<0){let n=w();E=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((t=>t.name==="hidden"&&t.startTime>n))[0]?.startTime)??le(),addEventListener("visibilitychange",$,!0),addEventListener("prerenderingchange",$,!0),S((()=>{setTimeout((()=>{E=le()}))}))}return{get firstHiddenTime(){return E},onHidden(n){be.add(n)}}},x=n=>{document.prerendering?addEventListener("prerenderingchange",(()=>n()),!0):n()},ue=[1800,3e3],Z=(n,e={})=>{x((()=>{let t=B(),r,i=y("FCP"),s=P("paint",(a=>{for(let l of a)l.name==="first-contentful-paint"&&(s.disconnect(),l.startTime<t.firstHiddenTime&&(i.value=Math.max(l.startTime-w(),0),i.entries.push(l),r(!0)))}));s&&(r=m(n,i,ue,e.reportAllChanges),S((a=>{i=y("FCP"),r=m(n,i,ue,e.reportAllChanges),G((()=>{i.value=performance.now()-a.timeStamp,r(!0)}))})))}))},de=[.1,.25],ve=(n,e={})=>{let t=B();Z(Y((()=>{let r,i=y("CLS",0),s=X(e,V),a=d=>{for(let u of d)s.h(u);s.i>i.value&&(i.value=s.i,i.entries=s.o,r())},l=P("layout-shift",a);l&&(r=m(n,i,de,e.reportAllChanges),t.onHidden((()=>{a(l.takeRecords()),r(!0)})),S((()=>{s.i=0,i=y("CLS",0),r=m(n,i,de,e.reportAllChanges),G((()=>r()))})),setTimeout(r))})))},ke=0,z=1/0,L=0,Oe=n=>{for(let e of n)e.interactionId&&(z=Math.min(z,e.interactionId),L=Math.max(L,e.interactionId),ke=L?(L-z)/7+1:0)},j,pe=()=>j?ke:performance.interactionCount??0,De=()=>{"interactionCount"in performance||j||(j=P("event",Oe,{type:"event",buffered:!0,durationThreshold:0}))},he=0,K=class{constructor(){k(this,"u",[]);k(this,"l",new Map);k(this,"m");k(this,"p")}v(){he=pe(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor((pe()-he)/50));return this.u[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!=="first-input")return;let t=this.u.at(-1),r=this.l.get(e.interactionId);if(r||this.u.length<10||e.duration>t.P){if(r?e.duration>r.P?(r.entries=[e],r.P=e.duration):e.duration===r.P&&e.startTime===r.entries[0].startTime&&r.entries.push(e):(r={id:e.interactionId,entries:[e],P:e.duration},this.l.set(r.id,r),this.u.push(r)),this.u.sort(((i,s)=>s.P-i.P)),this.u.length>10){let i=this.u.splice(10);for(let s of i)this.l.delete(s.id)}this.p?.(r)}}},Re=n=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?n():(n=Y(n),addEventListener("visibilitychange",n,{once:!0,capture:!0}),e((()=>{n(),removeEventListener("visibilitychange",n,{capture:!0})})))},ge=[200,500],Te=(n,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let t=B();x((()=>{De();let r,i=y("INP"),s=X(e,K),a=d=>{Re((()=>{for(let h of d)s.h(h);let u=s.L();u&&u.P!==i.value&&(i.value=u.P,i.entries=u.entries,r())}))},l=P("event",a,{durationThreshold:e.durationThreshold??40});r=m(n,i,ge,e.reportAllChanges),l&&(l.observe({type:"first-input",buffered:!0}),t.onHidden((()=>{a(l.takeRecords()),r(!0)})),S((()=>{s.v(),i=y("INP"),r=m(n,i,ge,e.reportAllChanges)})))}))},J=class{constructor(){k(this,"m")}h(e){this.m?.(e)}},fe=[2500,4e3],Ee=(n,e={})=>{x((()=>{let t=B(),r,i=y("LCP"),s=X(e,J),a=d=>{e.reportAllChanges||(d=d.slice(-1));for(let u of d)s.h(u),u.startTime<t.firstHiddenTime&&(i.value=Math.max(u.startTime-w(),0),i.entries=[u],r())},l=P("largest-contentful-paint",a);if(l){r=m(n,i,fe,e.reportAllChanges);let d=Y((()=>{a(l.takeRecords()),l.disconnect(),r(!0)})),u=h=>{h.isTrusted&&(Re(d),removeEventListener(h.type,u,{capture:!0}))};for(let h of["keydown","click","visibilitychange"])addEventListener(h,u,{capture:!0});S((h=>{i=y("LCP"),r=m(n,i,fe,e.reportAllChanges),G((()=>{i.value=performance.now()-h.timeStamp,r(!0)}))}))}}))},me=[800,1800],q=n=>{document.prerendering?x((()=>q(n))):document.readyState!=="complete"?addEventListener("load",(()=>q(n)),!0):setTimeout(n)},Se=(n,e={})=>{let t=y("TTFB"),r=m(n,t,me,e.reportAllChanges);q((()=>{let i=Q();i&&(t.value=Math.max(i.responseStart-w(),0),t.entries=[i],r(!0),S((()=>{t=y("TTFB",0),r=m(n,t,me,e.reportAllChanges),r(!0)})))}))};var O=class{constructor(e){this.data={lcp:null,cls:null,inp:null,fcp:null,ttfb:null};this.sent=!1;this.timeout=null;this.onReadyCallback=null;this.onReadyCallback=e}initialize(){try{Ee(this.collectMetric.bind(this)),ve(this.collectMetric.bind(this)),Te(this.collectMetric.bind(this)),Z(this.collectMetric.bind(this)),Se(this.collectMetric.bind(this)),this.timeout=setTimeout(()=>{this.sent||this.sendData()},2e4),window.addEventListener("beforeunload",()=>{this.sent||this.sendData()})}catch(e){console.warn("Error initializing web vitals tracking:",e)}}collectMetric(e){if(this.sent)return;let t=e.name.toLowerCase();this.data[t]=e.value,Object.values(this.data).every(i=>i!==null)&&this.sendData()}sendData(){this.sent||(this.sent=!0,this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.onReadyCallback&&this.onReadyCallback(this.data))}getData(){return{...this.data}}};var D=class{constructor(e,t){this.tracker=e,this.config=t}initialize(){document.addEventListener("click",this.handleClick.bind(this),!0)}handleClick(e){let t=e.target;this.config.trackButtonClicks&&this.isButton(t)&&this.trackButtonClick(t)}isButton(e){if(e.tagName==="BUTTON"||e.getAttribute("role")==="button")return!0;if(e.tagName==="INPUT"){let i=e.type?.toLowerCase();if(i==="submit"||i==="button")return!0}let t=e.parentElement,r=0;for(;t&&r<3;){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return!0;t=t.parentElement,r++}return!1}trackButtonClick(e){let t=this.findButton(e);if(!t||t.hasAttribute("data-rybbit-event"))return;let r={text:this.getElementText(t),...this.extractDataAttributes(t)};this.tracker.trackButtonClick(r)}extractDataAttributes(e){let t={};for(let r of e.attributes)if(r.name.startsWith("data-rybbit-prop-")){let i=r.name.replace("data-rybbit-prop-","");t[i]=r.value}return t}findButton(e){if(e.tagName==="BUTTON"||e.getAttribute("role")==="button")return e;if(e.tagName==="INPUT"){let i=e.type?.toLowerCase();if(i==="submit"||i==="button")return e}let t=e.parentElement,r=0;for(;t&&r<3;){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return t;t=t.parentElement,r++}return null}getElementText(e){let t=e.textContent?.trim().substring(0,100);if(t)return t;let r=e.getAttribute("aria-label")?.trim().substring(0,100);if(r)return r;if(e.tagName==="INPUT"){let s=e.value?.trim().substring(0,100);if(s)return s}let i=e.getAttribute("title")?.trim().substring(0,100);if(i)return i}cleanup(){document.removeEventListener("click",this.handleClick.bind(this),!0)}};var _=class{constructor(e){this.tracker=e}initialize(){document.addEventListener("copy",this.handleCopy.bind(this))}handleCopy(){let e=window.getSelection();if(!e||e.isCollapsed)return;let t=e.toString(),r=t.length;if(r===0)return;let i=e.anchorNode,s=i instanceof HTMLElement?i:i?.parentElement;if(!s)return;let a={text:t.substring(0,500),...r>500&&{textLength:r},sourceElement:s.tagName.toLowerCase()};this.tracker.trackCopy(a)}cleanup(){document.removeEventListener("copy",this.handleCopy.bind(this))}};var N=class{constructor(e,t){this.tracker=e,this.config=t,this.boundHandleSubmit=this.handleSubmit.bind(this),this.boundHandleChange=this.handleChange.bind(this)}initialize(){document.addEventListener("submit",this.boundHandleSubmit,!0),document.addEventListener("change",this.boundHandleChange,!0)}cleanup(){document.removeEventListener("submit",this.boundHandleSubmit,!0),document.removeEventListener("change",this.boundHandleChange,!0)}handleSubmit(e){let t=e.target;if(t.tagName!=="FORM")return;let r={formId:t.id||"",formName:t.name||"",formAction:t.action||"",method:(t.method||"get").toUpperCase(),fieldCount:t.elements.length,ariaLabel:t.getAttribute("aria-label")||void 0,...this.extractDataAttributes(t)};this.tracker.trackFormSubmit(r)}handleChange(e){let t=e.target,r=t.tagName.toUpperCase();if(!["INPUT","SELECT","TEXTAREA"].includes(r)||t.disabled)return;if(r==="INPUT"){let a=t.type?.toLowerCase();if(a==="hidden"||a==="password")return}let i=t.name||t.id||t.getAttribute("aria-label")||t.placeholder||"",s={element:r.toLowerCase(),inputType:r==="INPUT"?t.type?.toLowerCase():void 0,inputName:i,formId:t.form?.id||void 0,formName:t.form?.name||void 0,...this.extractDataAttributes(t)};this.tracker.trackInputChange(s)}extractDataAttributes(e){let t={};for(let r of e.attributes)if(r.name.startsWith("data-rybbit-prop-")){let i=r.name.replace("data-rybbit-prop-","");t[i]=r.value}return t}};(async function(){let n=document.currentScript;if(!n){console.error("Could not find current script tag");return}let e=n.getAttribute("data-namespace")||"rybbit",t=`disable-${e}`;if(window.__RYBBIT_OPTOUT__||localStorage.getItem(t)!==null){window[e]={pageview:()=>{},event:()=>{},error:()=>{},trackOutbound:()=>{},identify:()=>{},setTraits:()=>{},clearUserId:()=>{},getUserId:()=>null,startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let r=[],i=o=>(...c)=>{r.push([o,c])};window[e]={pageview:i("pageview"),event:i("event"),error:i("error"),trackOutbound:i("trackOutbound"),identify:i("identify"),setTraits:i("setTraits"),clearUserId:i("clearUserId"),getUserId:()=>null,startSessionReplay:i("startSessionReplay"),stopSessionReplay:i("stopSessionReplay"),isSessionReplayActive:()=>!1};let s=await oe(n);if(!s)return;let a=new A(s);s.enableWebVitals&&new O(c=>{a.trackWebVitals(c)}).initialize();let l=null,d=null,u=null;s.trackButtonClicks&&(l=new D(a,s),l.initialize()),s.trackCopy&&(d=new _(a),d.initialize()),s.trackFormInteractions&&(u=new N(a,s),u.initialize()),s.trackErrors&&(window.addEventListener("error",o=>{a.trackError(o.error||new Error(o.message),{filename:o.filename,lineno:o.lineno,colno:o.colno})}),window.addEventListener("unhandledrejection",o=>{let c=o.reason instanceof Error?o.reason:new Error(String(o.reason));a.trackError(c,{type:"unhandledrejection"})}));let h=()=>a.trackPageview(),b=s.debounceDuration>0?se(h,s.debounceDuration):h;function C(){if(document.addEventListener("click",function(o){let c=o.target;for(;c&&c!==document.documentElement;){if(c.hasAttribute("data-rybbit-event")){let p=c.getAttribute("data-rybbit-event");if(p){let I={};for(let T of c.attributes)if(T.name.startsWith("data-rybbit-prop-")){let U=T.name.replace("data-rybbit-prop-","");I[U]=T.value}a.trackEvent(p,I)}break}c=c.parentElement}if(s.trackOutbound){let p=o.target.closest("a");p?.href&&ae(p.href)&&a.trackOutbound(p.href,p.innerText||p.textContent||"",p.target||"_self")}}),s.autoTrackSpa){let o=history.pushState,c=history.replaceState;history.pushState=function(...p){o.apply(this,p),b(),a.onPageChange()},history.replaceState=function(...p){c.apply(this,p),b(),a.onPageChange()},window.addEventListener("popstate",()=>{b(),a.onPageChange()}),window.addEventListener("hashchange",()=>{b(),a.onPageChange()})}}window[s.namespace]={pageview:()=>a.trackPageview(),event:(o,c={})=>a.trackEvent(o,c),error:(o,c={})=>a.trackError(o,c),trackOutbound:(o,c="",p="_self")=>a.trackOutbound(o,c,p),identify:(o,c)=>a.identify(o,c),setTraits:o=>a.setTraits(o),clearUserId:()=>a.clearUserId(),getUserId:()=>a.getUserId(),startSessionReplay:()=>a.startSessionReplay(),stopSessionReplay:()=>a.stopSessionReplay(),isSessionReplayActive:()=>a.isSessionReplayActive()};let v=window[s.namespace];for(let[o,c]of r)v[o](...c);C(),window.addEventListener("beforeunload",()=>{l?.cleanup(),d?.cleanup(),a.cleanup()}),s.autoTrackPageview&&a.trackPageview()})();})();+"use strict";(()=>{var Le=Object.defineProperty;var Be=(r,e,t)=>e in r?Le(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var k=(r,e,t)=>Be(r,typeof e!="symbol"?e+"":e,t);function xe(r){if(r.startsWith("re:")){let l=r.slice(3);if(!l)throw new Error("Empty regex pattern");return new RegExp(l)}let t="__DOUBLE_ASTERISK_TOKEN__",n="__SINGLE_ASTERISK_TOKEN__",s=r.replace(/\*\*/g,t).replace(/\*/g,n).replace(/[.+?^${}()|[\]\\]/g,"\\$&");s=s.replace(new RegExp(`/${t}/`,"g"),"/(?:.+/)?"),s=s.replace(new RegExp(t,"g"),".*"),s=s.replace(/\//g,"\\/");let a=s.replace(new RegExp(n,"g"),"[^/]+");return new RegExp("^"+a+"$")}function F(r,e){for(let t of e)try{if(xe(t).test(r))return t}catch(n){console.error(`Invalid pattern: ${t}`,n)}return null}function se(r,e){let t=null;return(...n)=>{t&&clearTimeout(t),t=setTimeout(()=>r(...n),e)}}function ae(r){try{let e=window.location.hostname,t=new URL(r).hostname;return t!==e&&t!==""}catch{return!1}}function R(r,e){if(!r)return e;try{let t=JSON.parse(r);return Array.isArray(e)&&!Array.isArray(t)?e:t}catch(t){return console.error("Error parsing JSON:",t),e}}async function oe(r){let e=r.getAttribute("src");if(!e)return console.error("Script src attribute is missing"),null;let t=e.split("/script.js")[0];if(!t)return console.error("Please provide a valid analytics host"),null;let n=r.getAttribute("data-site-id")||r.getAttribute("site-id");if(!n)return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let i=r.getAttribute("data-namespace")||"rybbit",s=R(r.getAttribute("data-skip-patterns"),[]),a=R(r.getAttribute("data-mask-patterns"),[]),l=R(r.getAttribute("data-replay-mask-text-selectors"),[]),d=r.getAttribute("data-debounce")?Math.max(0,parseInt(r.getAttribute("data-debounce"))):500,u=r.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(r.getAttribute("data-replay-batch-size"))):250,h=r.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(r.getAttribute("data-replay-batch-interval"))):5e3,b=r.getAttribute("data-replay-block-class")||void 0,C=r.getAttribute("data-replay-block-selector")||void 0,v=r.getAttribute("data-replay-ignore-class")||void 0,o=r.getAttribute("data-replay-ignore-selector")||void 0,c=r.getAttribute("data-replay-mask-text-class")||void 0,p=r.getAttribute("data-replay-mask-all-inputs"),I=p!==null?p!=="false":void 0,E=r.getAttribute("data-replay-mask-input-options"),U=E?R(E,{password:!0,email:!0}):void 0,ee=r.getAttribute("data-replay-collect-fonts"),Te=ee!==null?ee!=="false":void 0,te=r.getAttribute("data-replay-sampling"),Pe=te?R(te,{}):void 0,re=r.getAttribute("data-replay-slim-dom-options"),Ie=re?R(re,{}):void 0,ne=r.getAttribute("data-replay-sample-rate"),Me=ne?Math.min(100,Math.max(0,parseInt(ne,10))):void 0,Ae=r.getAttribute("data-tag")||"",g={namespace:i,analyticsHost:t,siteId:n,debounceDuration:d,sessionReplayBatchSize:u,sessionReplayBatchInterval:h,sessionReplayMaskTextSelectors:l,skipPatterns:s,maskPatterns:a,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,trackButtonClicks:!1,trackCopy:!1,trackFormInteractions:!1,tag:Ae,sessionReplayBlockClass:b,sessionReplayBlockSelector:C,sessionReplayIgnoreClass:v,sessionReplayIgnoreSelector:o,sessionReplayMaskTextClass:c,sessionReplayMaskAllInputs:I,sessionReplayMaskInputOptions:U,sessionReplayCollectFonts:Te,sessionReplaySampling:Pe,sessionReplaySlimDOMOptions:Ie,sessionReplaySampleRate:Me};try{let H=`${t}/site/tracking-config/${n}`,ie=await fetch(H,{method:"GET",credentials:"omit"});if(ie.ok){let f=await ie.json();return{...g,autoTrackPageview:f.trackInitialPageView??g.autoTrackPageview,autoTrackSpa:f.trackSpaNavigation??g.autoTrackSpa,trackQuerystring:f.trackUrlParams??g.trackQuerystring,trackOutbound:f.trackOutbound??g.trackOutbound,enableWebVitals:f.webVitals??g.enableWebVitals,trackErrors:f.trackErrors??g.trackErrors,enableSessionReplay:f.sessionReplay??g.enableSessionReplay,trackButtonClicks:f.trackButtonClicks??g.trackButtonClicks,trackCopy:f.trackCopy??g.trackCopy,trackFormInteractions:f.trackFormInteractions??g.trackFormInteractions}}else return console.warn("Failed to fetch tracking config from API, using defaults"),g}catch(H){return console.warn("Error fetching tracking config:",H),g}}var ce="rybbit-replay-sampled";function Oe(r){if(r>=100)return!0;if(r<=0)return!1;try{let e=sessionStorage.getItem(ce);if(e!==null)return e==="1";let t=Math.random()*100<r;return sessionStorage.setItem(ce,t?"1":"0"),t}catch{return Math.random()*100<r}}var M=class{constructor(e,t,n){this.isRecording=!1;this.eventBuffer=[];this.config=e,this.userId=t,this.sendBatch=n}async initialize(){if(!this.config.enableSessionReplay)return;let e=this.config.sessionReplaySampleRate;e!==void 0&&!Oe(e)||(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((e,t)=>{let n=document.createElement("script");n.src=`${this.config.analyticsHost}/replay.js`,n.async=!1,n.onload=()=>{e()},n.onerror=()=>t(new Error("Failed to load rrweb")),document.head.appendChild(n)})}startRecording(){if(!(this.isRecording||!window.rrweb||!this.config.enableSessionReplay))try{let e={mousemove:!1,mouseInteraction:{MouseUp:!1,MouseDown:!1,Click:!0,ContextMenu:!1,DblClick:!0,Focus:!0,Blur:!0,TouchStart:!1,TouchEnd:!1},scroll:500,input:"last",media:800},t={script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},n={emit:i=>{this.addEvent({type:i.type,data:i.data,timestamp:i.timestamp||Date.now()})},recordCanvas:!1,checkoutEveryNms:6e4,checkoutEveryNth:500,blockClass:this.config.sessionReplayBlockClass??"rr-block",blockSelector:this.config.sessionReplayBlockSelector??null,ignoreClass:this.config.sessionReplayIgnoreClass??"rr-ignore",ignoreSelector:this.config.sessionReplayIgnoreSelector??null,maskTextClass:this.config.sessionReplayMaskTextClass??"rr-mask",maskAllInputs:this.config.sessionReplayMaskAllInputs??!0,maskInputOptions:this.config.sessionReplayMaskInputOptions??{password:!0,email:!0},collectFonts:this.config.sessionReplayCollectFonts??!0,sampling:this.config.sessionReplaySampling??e,slimDOMOptions:this.config.sessionReplaySlimDOMOptions??t};this.config.sessionReplayMaskTextSelectors&&this.config.sessionReplayMaskTextSelectors.length>0&&(n.maskTextSelector=this.config.sessionReplayMaskTextSelectors.join(", ")),this.stopRecordingFn=window.rrweb.record(n),this.isRecording=!0,this.setupBatchTimer()}catch{}}stopRecording(){this.isRecording&&(this.stopRecordingFn&&this.stopRecordingFn(),this.isRecording=!1,this.clearBatchTimer(),this.eventBuffer.length>0&&this.flushEvents())}isActive(){return this.isRecording}addEvent(e){this.eventBuffer.push(e),this.eventBuffer.length>=this.config.sessionReplayBatchSize&&this.flushEvents()}setupBatchTimer(){this.clearBatchTimer(),this.batchTimer=window.setInterval(()=>{this.eventBuffer.length>0&&this.flushEvents()},this.config.sessionReplayBatchInterval)}clearBatchTimer(){this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0)}async flushEvents(){if(this.eventBuffer.length===0)return;let e=[...this.eventBuffer];this.eventBuffer=[];let t={userId:this.userId,events:e,metadata:{pageUrl:window.location.href,viewportWidth:screen.width,viewportHeight:screen.height,language:navigator.language}};try{await this.sendBatch(t)}catch{this.eventBuffer.unshift(...e)}}updateUserId(e){this.userId=e}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};function le(){let r=0;try{navigator.webdriver===!0&&r++,(window.outerHeight===0||window.outerWidth===0)&&r++,navigator.connection?.rtt===0&&r++,!window.chrome&&/Chrome\//.test(navigator.userAgent)&&r++;try{let e=document.createElement("canvas"),t=e.getContext("webgl")||e.getContext("experimental-webgl");if(t){let n=t.getExtension("WEBGL_debug_renderer_info");if(n){let i=t.getParameter(n.UNMASKED_RENDERER_WEBGL);typeof i=="string"&&i.includes("SwiftShader")&&r++}}}catch{}navigator.plugins.length===0&&/Chrome\//.test(navigator.userAgent)&&r++;try{typeof Notification<"u"&&Notification.permission}catch{}}catch{}return r}var A=class{constructor(e){this.customUserId=null;this.errorDedupeCache=new Map;this.errorDedupeLastCleanup=0;this.config=e,this.loadUserId(),e.enableSessionReplay&&this.initializeSessionReplay()}loadUserId(){try{let e=localStorage.getItem(`${this.config.namespace}-user-id`);e&&(this.customUserId=e)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new M(this.config,this.customUserId||"",e=>this.sendSessionReplayBatch(e)),await this.sessionReplayRecorder.initialize()}catch(e){console.error("Failed to initialize session replay:",e)}}async sendSessionReplayBatch(e){try{await fetch(`${this.config.analyticsHost}/session-replay/record/${this.config.siteId}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),mode:"cors",keepalive:!1})}catch(t){throw console.error("Failed to send session replay batch:",t),t}}createBasePayload(){let e=new URL(window.location.href),t=e.pathname;if(e.hash&&e.hash.startsWith("#/")&&(t=e.hash.substring(1)),F(t,this.config.skipPatterns))return null;let n=F(t,this.config.maskPatterns);n&&(t=n);let i={site_id:this.config.siteId,hostname:e.hostname,pathname:t,querystring:this.config.trackQuerystring?e.search:"",screenWidth:screen.width,screenHeight:screen.height,language:navigator.language,page_title:document.title,referrer:document.referrer,_bs:le()};return this.customUserId&&(i.user_id=this.customUserId),this.config.tag&&(i.tag=this.config.tag),i}async sendTrackingData(e){try{await fetch(`${this.config.analyticsHost}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),mode:"cors",keepalive:!0})}catch(t){console.error("Failed to send tracking data:",t)}}track(e,t="",n={}){if(e==="custom_event"&&(!t||typeof t!="string")){console.error("Event name is required and must be a string for custom events");return}let i=this.createBasePayload();if(!i)return;let a={...i,type:e,event_name:t,properties:["custom_event","outbound","error","button_click","copy","form_submit","input_change"].includes(e)?JSON.stringify(n):void 0};this.sendTrackingData(a)}trackPageview(){this.track("pageview")}trackEvent(e,t={}){this.track("custom_event",e,t)}trackOutbound(e,t="",n="_self"){this.track("outbound","",{url:e,text:t,target:n})}trackWebVitals(e){let t=this.createBasePayload();if(!t)return;let n={...t,type:"performance",event_name:"web-vitals",...e};this.sendTrackingData(n)}trackError(e,t={}){let n=e?.message||"";if(n.includes("ResizeObserver loop completed with undelivered notifications")||n.includes("ResizeObserver loop limit exceeded"))return;let i=window.location.origin,s=t.filename||"",a=e.stack||"";if(s)try{if(new URL(s).origin!==i)return}catch{}else if(a&&!a.includes(i))return;let d=[e.name||"Error",n,t.filename||"",t.lineno??"",t.colno??""].join("|"),u=Date.now(),h=6e4,b=this.errorDedupeCache.get(d);if(b&&u-b<h)return;this.errorDedupeCache.set(d,u);let C=10*6e4;if(u-this.errorDedupeLastCleanup>h){for(let[o,c]of this.errorDedupeCache.entries())u-c>C&&this.errorDedupeCache.delete(o);this.errorDedupeLastCleanup=u}let v={message:e.message?.substring(0,500)||"Unknown error",stack:a.substring(0,2e3)||""};if(s&&(v.fileName=s),t.lineno){let o=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;o&&o!==0&&(v.lineNumber=o)}if(t.colno){let o=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;o&&o!==0&&(v.columnNumber=o)}for(let o in t)!["lineno","colno"].includes(o)&&t[o]!==void 0&&(v[o]=t[o]);this.track("error",e.name||"Error",v)}trackButtonClick(e){this.track("button_click","",e)}trackCopy(e){this.track("copy","",e)}trackFormSubmit(e){this.track("form_submit","",e)}trackInputChange(e){this.track("input_change","",e)}identify(e,t){if(typeof e!="string"||e.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=e.trim();try{localStorage.setItem(`${this.config.namespace}-user-id`,this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}this.sendIdentifyEvent(this.customUserId,t,!0),this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(this.customUserId)}setTraits(e){if(!e||typeof e!="object"){console.error("Traits must be an object");return}let t=this.customUserId;if(!t){console.warn("Cannot set traits without identifying user first. Call identify() first.");return}this.sendIdentifyEvent(t,e,!1)}async sendIdentifyEvent(e,t,n=!0){try{await fetch(`${this.config.analyticsHost}/identify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({site_id:this.config.siteId,user_id:e,traits:t,is_new_identify:n}),mode:"cors",keepalive:!0})}catch(i){console.error("Failed to send identify event:",i)}}clearUserId(){this.customUserId=null;try{localStorage.removeItem(`${this.config.namespace}-user-id`)}catch{}}getUserId(){return this.customUserId}startSessionReplay(){this.sessionReplayRecorder?this.sessionReplayRecorder.startRecording():console.warn("Session replay not initialized")}stopSessionReplay(){this.sessionReplayRecorder&&this.sessionReplayRecorder.stopRecording()}isSessionReplayActive(){return this.sessionReplayRecorder?.isActive()??!1}onPageChange(){this.sessionReplayRecorder&&this.sessionReplayRecorder.onPageChange()}cleanup(){this.sessionReplayRecorder&&this.sessionReplayRecorder.cleanup()}};var be=-1,w=r=>{addEventListener("pageshow",(e=>{e.persisted&&(be=e.timeStamp,r(e))}),!0)},m=(r,e,t,n)=>{let i,s;return a=>{e.value>=0&&(a||n)&&(s=e.value-(i??0),(s||i===void 0)&&(i=e.value,e.delta=s,e.rating=((l,d)=>l>d[1]?"poor":l>d[0]?"needs-improvement":"good")(e.value,t),r(e)))}},q=r=>{requestAnimationFrame((()=>requestAnimationFrame((()=>r()))))},Q=()=>{let r=performance.getEntriesByType("navigation")[0];if(r&&r.responseStart>0&&r.responseStart<performance.now())return r},T=()=>Q()?.activationStart??0,y=(r,e=-1)=>{let t=Q(),n="navigate";return be>=0?n="back-forward-cache":t&&(document.prerendering||T()>0?n="prerender":document.wasDiscarded?n="restore":t.type&&(n=t.type.replace(/_/g,"-"))),{name:r,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:n}},W=new WeakMap;function X(r,e){return W.get(r)||W.set(r,new e),W.get(r)}var V=class{constructor(){k(this,"t");k(this,"i",0);k(this,"o",[])}h(e){if(e.hadRecentInput)return;let t=this.o[0],n=this.o.at(-1);this.i&&t&&n&&e.startTime-n.startTime<1e3&&e.startTime-t.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}},P=(r,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(r)){let n=new PerformanceObserver((i=>{Promise.resolve().then((()=>{e(i.getEntries())}))}));return n.observe({type:r,buffered:!0,...t}),n}}catch{}},Y=r=>{let e=!1;return()=>{e||(r(),e=!0)}},S=-1,ve=new Set,ue=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,$=r=>{if(document.visibilityState==="hidden"){if(r.type==="visibilitychange")for(let e of ve)e();isFinite(S)||(S=r.type==="visibilitychange"?r.timeStamp:0,removeEventListener("prerenderingchange",$,!0))}},B=()=>{if(S<0){let r=T();S=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((t=>t.name==="hidden"&&t.startTime>r))[0]?.startTime)??ue(),addEventListener("visibilitychange",$,!0),addEventListener("prerenderingchange",$,!0),w((()=>{setTimeout((()=>{S=ue()}))}))}return{get firstHiddenTime(){return S},onHidden(r){ve.add(r)}}},x=r=>{document.prerendering?addEventListener("prerenderingchange",(()=>r()),!0):r()},de=[1800,3e3],Z=(r,e={})=>{x((()=>{let t=B(),n,i=y("FCP"),s=P("paint",(a=>{for(let l of a)l.name==="first-contentful-paint"&&(s.disconnect(),l.startTime<t.firstHiddenTime&&(i.value=Math.max(l.startTime-T(),0),i.entries.push(l),n(!0)))}));s&&(n=m(r,i,de,e.reportAllChanges),w((a=>{i=y("FCP"),n=m(r,i,de,e.reportAllChanges),q((()=>{i.value=performance.now()-a.timeStamp,n(!0)}))})))}))},pe=[.1,.25],ke=(r,e={})=>{let t=B();Z(Y((()=>{let n,i=y("CLS",0),s=X(e,V),a=d=>{for(let u of d)s.h(u);s.i>i.value&&(i.value=s.i,i.entries=s.o,n())},l=P("layout-shift",a);l&&(n=m(r,i,pe,e.reportAllChanges),t.onHidden((()=>{a(l.takeRecords()),n(!0)})),w((()=>{s.i=0,i=y("CLS",0),n=m(r,i,pe,e.reportAllChanges),q((()=>n()))})),setTimeout(n))})))},Re=0,z=1/0,L=0,_e=r=>{for(let e of r)e.interactionId&&(z=Math.min(z,e.interactionId),L=Math.max(L,e.interactionId),Re=L?(L-z)/7+1:0)},j,he=()=>j?Re:performance.interactionCount??0,De=()=>{"interactionCount"in performance||j||(j=P("event",_e,{type:"event",buffered:!0,durationThreshold:0}))},ge=0,K=class{constructor(){k(this,"u",[]);k(this,"l",new Map);k(this,"m");k(this,"p")}v(){ge=he(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor((he()-ge)/50));return this.u[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!=="first-input")return;let t=this.u.at(-1),n=this.l.get(e.interactionId);if(n||this.u.length<10||e.duration>t.P){if(n?e.duration>n.P?(n.entries=[e],n.P=e.duration):e.duration===n.P&&e.startTime===n.entries[0].startTime&&n.entries.push(e):(n={id:e.interactionId,entries:[e],P:e.duration},this.l.set(n.id,n),this.u.push(n)),this.u.sort(((i,s)=>s.P-i.P)),this.u.length>10){let i=this.u.splice(10);for(let s of i)this.l.delete(s.id)}this.p?.(n)}}},Ee=r=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?r():(r=Y(r),addEventListener("visibilitychange",r,{once:!0,capture:!0}),e((()=>{r(),removeEventListener("visibilitychange",r,{capture:!0})})))},fe=[200,500],Se=(r,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let t=B();x((()=>{De();let n,i=y("INP"),s=X(e,K),a=d=>{Ee((()=>{for(let h of d)s.h(h);let u=s.L();u&&u.P!==i.value&&(i.value=u.P,i.entries=u.entries,n())}))},l=P("event",a,{durationThreshold:e.durationThreshold??40});n=m(r,i,fe,e.reportAllChanges),l&&(l.observe({type:"first-input",buffered:!0}),t.onHidden((()=>{a(l.takeRecords()),n(!0)})),w((()=>{s.v(),i=y("INP"),n=m(r,i,fe,e.reportAllChanges)})))}))},G=class{constructor(){k(this,"m")}h(e){this.m?.(e)}},me=[2500,4e3],we=(r,e={})=>{x((()=>{let t=B(),n,i=y("LCP"),s=X(e,G),a=d=>{e.reportAllChanges||(d=d.slice(-1));for(let u of d)s.h(u),u.startTime<t.firstHiddenTime&&(i.value=Math.max(u.startTime-T(),0),i.entries=[u],n())},l=P("largest-contentful-paint",a);if(l){n=m(r,i,me,e.reportAllChanges);let d=Y((()=>{a(l.takeRecords()),l.disconnect(),n(!0)})),u=h=>{h.isTrusted&&(Ee(d),removeEventListener(h.type,u,{capture:!0}))};for(let h of["keydown","click","visibilitychange"])addEventListener(h,u,{capture:!0});w((h=>{i=y("LCP"),n=m(r,i,me,e.reportAllChanges),q((()=>{i.value=performance.now()-h.timeStamp,n(!0)}))}))}}))},ye=[800,1800],J=r=>{document.prerendering?x((()=>J(r))):document.readyState!=="complete"?addEventListener("load",(()=>J(r)),!0):setTimeout(r)},Ce=(r,e={})=>{let t=y("TTFB"),n=m(r,t,ye,e.reportAllChanges);J((()=>{let i=Q();i&&(t.value=Math.max(i.responseStart-T(),0),t.entries=[i],n(!0),w((()=>{t=y("TTFB",0),n=m(r,t,ye,e.reportAllChanges),n(!0)})))}))};var O=class{constructor(e){this.data={lcp:null,cls:null,inp:null,fcp:null,ttfb:null};this.sent=!1;this.timeout=null;this.onReadyCallback=null;this.onReadyCallback=e}initialize(){try{we(this.collectMetric.bind(this)),ke(this.collectMetric.bind(this)),Se(this.collectMetric.bind(this)),Z(this.collectMetric.bind(this)),Ce(this.collectMetric.bind(this)),this.timeout=setTimeout(()=>{this.sent||this.sendData()},2e4),window.addEventListener("beforeunload",()=>{this.sent||this.sendData()})}catch(e){console.warn("Error initializing web vitals tracking:",e)}}collectMetric(e){if(this.sent)return;let t=e.name.toLowerCase();this.data[t]=e.value,Object.values(this.data).every(i=>i!==null)&&this.sendData()}sendData(){this.sent||(this.sent=!0,this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.onReadyCallback&&this.onReadyCallback(this.data))}getData(){return{...this.data}}};var _=class{constructor(e,t){this.tracker=e,this.config=t}initialize(){document.addEventListener("click",this.handleClick.bind(this),!0)}handleClick(e){let t=e.target;this.config.trackButtonClicks&&this.isButton(t)&&this.trackButtonClick(t)}isButton(e){if(e.tagName==="BUTTON"||e.getAttribute("role")==="button")return!0;if(e.tagName==="INPUT"){let i=e.type?.toLowerCase();if(i==="submit"||i==="button")return!0}let t=e.parentElement,n=0;for(;t&&n<3;){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return!0;t=t.parentElement,n++}return!1}trackButtonClick(e){let t=this.findButton(e);if(!t||t.hasAttribute("data-rybbit-event"))return;let n={text:this.getElementText(t),...this.extractDataAttributes(t)};this.tracker.trackButtonClick(n)}extractDataAttributes(e){let t={};for(let n of e.attributes)if(n.name.startsWith("data-rybbit-prop-")){let i=n.name.replace("data-rybbit-prop-","");t[i]=n.value}return t}findButton(e){if(e.tagName==="BUTTON"||e.getAttribute("role")==="button")return e;if(e.tagName==="INPUT"){let i=e.type?.toLowerCase();if(i==="submit"||i==="button")return e}let t=e.parentElement,n=0;for(;t&&n<3;){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return t;t=t.parentElement,n++}return null}getElementText(e){let t=e.textContent?.trim().substring(0,100);if(t)return t;let n=e.getAttribute("aria-label")?.trim().substring(0,100);if(n)return n;if(e.tagName==="INPUT"){let s=e.value?.trim().substring(0,100);if(s)return s}let i=e.getAttribute("title")?.trim().substring(0,100);if(i)return i}cleanup(){document.removeEventListener("click",this.handleClick.bind(this),!0)}};var D=class{constructor(e){this.tracker=e}initialize(){document.addEventListener("copy",this.handleCopy.bind(this))}handleCopy(){let e=window.getSelection();if(!e||e.isCollapsed)return;let t=e.toString(),n=t.length;if(n===0)return;let i=e.anchorNode,s=i instanceof HTMLElement?i:i?.parentElement;if(!s)return;let a={text:t.substring(0,500),...n>500&&{textLength:n},sourceElement:s.tagName.toLowerCase()};this.tracker.trackCopy(a)}cleanup(){document.removeEventListener("copy",this.handleCopy.bind(this))}};var N=class{constructor(e,t){this.tracker=e,this.config=t,this.boundHandleSubmit=this.handleSubmit.bind(this),this.boundHandleChange=this.handleChange.bind(this)}initialize(){document.addEventListener("submit",this.boundHandleSubmit,!0),document.addEventListener("change",this.boundHandleChange,!0)}cleanup(){document.removeEventListener("submit",this.boundHandleSubmit,!0),document.removeEventListener("change",this.boundHandleChange,!0)}handleSubmit(e){let t=e.target;if(t.tagName!=="FORM")return;let n={formId:t.id||"",formName:t.name||"",formAction:t.action||"",method:(t.method||"get").toUpperCase(),fieldCount:t.elements.length,ariaLabel:t.getAttribute("aria-label")||void 0,...this.extractDataAttributes(t)};this.tracker.trackFormSubmit(n)}handleChange(e){let t=e.target,n=t.tagName.toUpperCase();if(!["INPUT","SELECT","TEXTAREA"].includes(n)||t.disabled)return;if(n==="INPUT"){let a=t.type?.toLowerCase();if(a==="hidden"||a==="password")return}let i=t.name||t.id||t.getAttribute("aria-label")||t.placeholder||"",s={element:n.toLowerCase(),inputType:n==="INPUT"?t.type?.toLowerCase():void 0,inputName:i,formId:t.form?.id||void 0,formName:t.form?.name||void 0,...this.extractDataAttributes(t)};this.tracker.trackInputChange(s)}extractDataAttributes(e){let t={};for(let n of e.attributes)if(n.name.startsWith("data-rybbit-prop-")){let i=n.name.replace("data-rybbit-prop-","");t[i]=n.value}return t}};(async function(){let r=document.currentScript;if(!r){console.error("Could not find current script tag");return}let e=r.getAttribute("data-namespace")||"rybbit",t=`disable-${e}`;if(window.__RYBBIT_OPTOUT__||localStorage.getItem(t)!==null){window[e]={pageview:()=>{},event:()=>{},error:()=>{},trackOutbound:()=>{},identify:()=>{},setTraits:()=>{},clearUserId:()=>{},getUserId:()=>null,startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let n=[],i=o=>(...c)=>{n.push([o,c])};window[e]={pageview:i("pageview"),event:i("event"),error:i("error"),trackOutbound:i("trackOutbound"),identify:i("identify"),setTraits:i("setTraits"),clearUserId:i("clearUserId"),getUserId:()=>null,startSessionReplay:i("startSessionReplay"),stopSessionReplay:i("stopSessionReplay"),isSessionReplayActive:()=>!1};let s=await oe(r);if(!s)return;let a=new A(s);s.enableWebVitals&&new O(c=>{a.trackWebVitals(c)}).initialize();let l=null,d=null,u=null;s.trackButtonClicks&&(l=new _(a,s),l.initialize()),s.trackCopy&&(d=new D(a),d.initialize()),s.trackFormInteractions&&(u=new N(a,s),u.initialize()),s.trackErrors&&(window.addEventListener("error",o=>{a.trackError(o.error||new Error(o.message),{filename:o.filename,lineno:o.lineno,colno:o.colno})}),window.addEventListener("unhandledrejection",o=>{let c=o.reason instanceof Error?o.reason:new Error(String(o.reason));a.trackError(c,{type:"unhandledrejection"})}));let h=()=>a.trackPageview(),b=s.debounceDuration>0?se(h,s.debounceDuration):h;function C(){if(document.addEventListener("click",function(o){let c=o.target;for(;c&&c!==document.documentElement;){if(c.hasAttribute("data-rybbit-event")){let p=c.getAttribute("data-rybbit-event");if(p){let I={};for(let E of c.attributes)if(E.name.startsWith("data-rybbit-prop-")){let U=E.name.replace("data-rybbit-prop-","");I[U]=E.value}a.trackEvent(p,I)}break}c=c.parentElement}if(s.trackOutbound){let p=o.target.closest("a");p?.href&&ae(p.href)&&a.trackOutbound(p.href,p.innerText||p.textContent||"",p.target||"_self")}}),s.autoTrackSpa){let o=history.pushState,c=history.replaceState;history.pushState=function(...p){o.apply(this,p),b(),a.onPageChange()},history.replaceState=function(...p){c.apply(this,p),b(),a.onPageChange()},window.addEventListener("popstate",()=>{b(),a.onPageChange()}),window.addEventListener("hashchange",()=>{b(),a.onPageChange()})}}window[s.namespace]={pageview:()=>a.trackPageview(),event:(o,c={})=>a.trackEvent(o,c),error:(o,c={})=>a.trackError(o,c),trackOutbound:(o,c="",p="_self")=>a.trackOutbound(o,c,p),identify:(o,c)=>a.identify(o,c),setTraits:o=>a.setTraits(o),clearUserId:()=>a.clearUserId(),getUserId:()=>a.getUserId(),startSessionReplay:()=>a.startSessionReplay(),stopSessionReplay:()=>a.stopSessionReplay(),isSessionReplayActive:()=>a.isSessionReplayActive()};let v=window[s.namespace];for(let[o,c]of n)v[o](...c);C(),window.addEventListener("beforeunload",()=>{l?.cleanup(),d?.cleanup(),a.cleanup()}),s.autoTrackPageview&&a.trackPageview()})();})();diff --git a/server/src/analytics-script/botSignals.ts b/server/src/analytics-script/botSignals.tsnew file mode 100644index 000000000..a265e9f76--- /dev/null+++ b/server/src/analytics-script/botSignals.ts@@ -0,0 +1,71 @@+/**+ * Client-side bot detection signals.+ *+ * Checks browser environment characteristics that distinguish real browsers+ * from headless/automated ones. Returns a single integer score β the number+ * of bot-like signals detected. Only the score is transmitted, never the+ * individual signal values, preserving user privacy.+ */+export function getBotScore(): number {+ let score = 0;++ try {+ // 1. navigator.webdriver β set to true when controlled by automation (Selenium, Puppeteer, Playwright)+ if ((navigator as any).webdriver === true) {+ score++;+ }++ // 2. Zero outer dimensions β headless browsers return 0 for outer window size+ if (window.outerHeight === 0 || window.outerWidth === 0) {+ score++;+ }++ // 3. Zero network RTT β real networks always have latency > 0+ if ((navigator as any).connection?.rtt === 0) {+ score++;+ }++ // 4. Missing window.chrome on a Chrome UA β real Chrome always exposes this object+ if (!((window as any).chrome) && /Chrome\//.test(navigator.userAgent)) {+ score++;+ }++ // 5. WebGL renderer check β headless Chrome uses "Google SwiftShader" (software renderer)+ try {+ const canvas = document.createElement("canvas");+ const gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");+ if (gl) {+ const debugInfo = (gl as WebGLRenderingContext).getExtension("WEBGL_debug_renderer_info");+ if (debugInfo) {+ const renderer = (gl as WebGLRenderingContext).getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);+ if (typeof renderer === "string" && renderer.includes("SwiftShader")) {+ score++;+ }+ }+ }+ } catch (e) {+ // WebGL not available β not a bot signal by itself+ }++ // 6. No plugins β headless Chrome has 0 plugins, real Chrome has at least PDF viewer+ // Only flag for Chrome UAs since Firefox legitimately has 0+ if (navigator.plugins.length === 0 && /Chrome\//.test(navigator.userAgent)) {+ score++;+ }++ // 7. Notification permission inconsistency β headless mode can return contradictory values+ try {+ if (typeof Notification !== "undefined" && Notification.permission === "denied") {+ // In headless, permission is always "denied" but permission query may say "prompt"+ // We only count this if other signals are also present (it's a weak signal alone)+ // Skip β too many false positives on mobile browsers+ }+ } catch (e) {+ // Not available+ }+ } catch (e) {+ // If any top-level access fails, return whatever we've accumulated+ }++ return score;+}diff --git a/server/src/analytics-script/tracking.ts b/server/src/analytics-script/tracking.tsindex 1a2d0f716..7c0d23b52 100644--- a/server/src/analytics-script/tracking.ts+++ b/server/src/analytics-script/tracking.ts@@ -1,6 +1,7 @@import { BasePayload, ScriptConfig, TrackingPayload, WebVitalsData, SessionReplayBatch, ButtonClickProperties, CopyProperties, FormSubmitProperties, InputChangeProperties } from "./types.js";import { findMatchingPattern } from "./utils.js";import { SessionReplayRecorder } from "./sessionReplay.js";+import { getBotScore } from "./botSignals.js";export class Tracker {private config: ScriptConfig;@@ -8,7 +9,6 @@ export class Tracker {private sessionReplayRecorder?: SessionReplayRecorder;private errorDedupeCache: Map<string, number> = new Map();private errorDedupeLastCleanup = 0;-constructor(config: ScriptConfig) {this.config = config;this.loadUserId();@@ -87,6 +87,7 @@ export class Tracker {language: navigator.language,page_title: document.title,referrer: document.referrer,+ _bs: getBotScore(),};if (this.customUserId) {diff --git a/server/src/analytics-script/types.ts b/server/src/analytics-script/types.tsindex 231a70fd5..17b5d3a5b 100644--- a/server/src/analytics-script/types.ts+++ b/server/src/analytics-script/types.ts@@ -45,6 +45,7 @@ export interface BasePayload {referrer: string;user_id?: string;tag?: string;+ _bs?: number; // Client-side bot detection score}export interface TrackingPayload extends BasePayload {diff --git a/server/src/api/analytics/sessions/getSessions.ts b/server/src/api/analytics/sessions/getSessions.tsindex bdf06a2f5..8304f6c2c 100644--- a/server/src/api/analytics/sessions/getSessions.ts+++ b/server/src/api/analytics/sessions/getSessions.ts@@ -1,8 +1,8 @@+import { FilterParams } from "@rybbit/shared";import { FastifyReply, FastifyRequest } from "fastify";import { clickhouse } from "../../../db/clickhouse/clickhouse.js";-import { enrichWithTraits, getTimeStatement, processResults } from "../utils/utils.js";-import { FilterParams } from "@rybbit/shared";import { getFilterStatement } from "../utils/getFilterStatement.js";+import { enrichWithTraits, getTimeStatement, processResults } from "../utils/utils.js";export type GetSessionsResponse = {session_id: string;diff --git a/server/src/api/analytics/utils/getFilterStatement.ts b/server/src/api/analytics/utils/getFilterStatement.tsindex 8c84b3017..f979fc04a 100644--- a/server/src/api/analytics/utils/getFilterStatement.ts+++ b/server/src/api/analytics/utils/getFilterStatement.ts@@ -313,4 +313,3 @@ export function getFilterStatement(return result;}-diff --git a/server/src/lib/ipUtils.ts b/server/src/lib/ipUtils.tsindex 92ee3ea2b..56d088c8d 100644--- a/server/src/lib/ipUtils.ts+++ b/server/src/lib/ipUtils.ts@@ -85,17 +85,45 @@ export function validateIPPattern(pattern: string): { valid: boolean; error?: st*/export function matchesCIDR(ipAddress: string, cidr: string): boolean {try {- // Try IPv4 first+ // Try IPv4+ let isIPv4 = false;+ let isIPv6 = false;+ let ipv4: Address4 | undefined;+ let ipv6: Address6 | undefined;+try {- const ipv4 = new Address4(ipAddress);- const cidrv4 = new Address4(cidr);- return ipv4.isInSubnet(cidrv4);+ ipv4 = new Address4(ipAddress);+ isIPv4 = true;} catch {- // Try IPv6- const ipv6 = new Address6(ipAddress);- const cidrv6 = new Address6(cidr);- return ipv6.isInSubnet(cidrv6);+ try {+ ipv6 = new Address6(ipAddress);+ isIPv6 = true;+ } catch {+ return false;+ }+ }++ if (isIPv4 && ipv4) {+ try {+ const cidrv4 = new Address4(cidr);+ return ipv4.isInSubnet(cidrv4);+ } catch {+ // CIDR is not IPv4 (likely IPv6), so it can't match an IPv4 address+ return false;+ }+ }++ if (isIPv6 && ipv6) {+ try {+ const cidrv6 = new Address6(cidr);+ return ipv6.isInSubnet(cidrv6);+ } catch {+ // CIDR is not IPv6, so it can't match an IPv6 address+ return false;+ }}++ return false;} catch (error) {logger.warn(error, `Error matching CIDR ${cidr} for IP ${ipAddress}`);return false;diff --git a/server/src/services/tracker/botDetection.ts b/server/src/services/tracker/botDetection.tsnew file mode 100644index 000000000..b784f4759--- /dev/null+++ b/server/src/services/tracker/botDetection.ts@@ -0,0 +1,155 @@+import { FastifyRequest } from "fastify";+import { BOT_SCORE_THRESHOLD } from "./const.js";++interface BotDetectionResult {+ isBot: boolean;+ score: number;+ reason?: string;+}++// Known bot/scripting framework signatures in User-Agent strings+const BOT_FRAMEWORK_PATTERNS = [+ "python-requests",+ "python-urllib",+ "go-http-client",+ "java/",+ "okhttp",+ "node-fetch",+ "undici",+ "curl/",+ "wget",+ "httpie",+ "scrapy",+ "phantomjs",+ "selenium",+ "puppeteer",+ "playwright",+ "headlesschrome",+ "apache-httpclient",+ "libwww-perl",+ "mechanize",+ "aiohttp",+ "httpx",+ "got/",+ "superagent",+ "postman",+ "insomnia",+];++// Headless browser indicators in UA+const HEADLESS_PATTERNS = ["headlesschrome", "headless", "phantomjs"];++/**+ * Extract Chrome major version from a User-Agent string.+ * Returns null if Chrome version cannot be determined.+ */+function getChromeVersion(ua: string): number | null {+ const match = ua.match(/Chrome\/(\d+)/);+ return match ? parseInt(match[1], 10) : null;+}++/**+ * Check if the UA claims a modern OS (Windows 10+, macOS 11+).+ */+function claimsModernOS(ua: string): boolean {+ // Windows 10+ reports as "Windows NT 10.0"+ if (/Windows NT (1[0-9]|[2-9][0-9])/.test(ua)) return true;+ // macOS 11+ (Big Sur and later) β reported as "Mac OS X 10_15" or "Mac OS X 11" etc.+ const macMatch = ua.match(/Mac OS X (\d+)[_.](\d+)/);+ if (macMatch) {+ const major = parseInt(macMatch[1], 10);+ if (major >= 11) return true;+ // macOS 10.15+ (Catalina) is still fairly modern+ if (major === 10 && parseInt(macMatch[2], 10) >= 15) return true;+ }+ return false;+}++/**+ * Score-based bot detection using HTTP header heuristics.+ *+ * Supplements the isbot() UA-string check with analysis of headers+ * that real browsers always send but scripting clients typically miss.+ */+export function detectBot(+ request: FastifyRequest,+ userAgent: string+): BotDetectionResult {+ let score = 0;+ const reasons: string[] = [];+ const headers = request.headers;+ const lowerUA = userAgent.toLowerCase();++ // 1. Known bot framework signatures in UA (instant kill)+ for (const pattern of BOT_FRAMEWORK_PATTERNS) {+ if (lowerUA.includes(pattern)) {+ return {+ isBot: true,+ score: 5,+ reason: `bot_framework:${pattern}`,+ };+ }+ }++ // 2. Headless browser patterns in UA+ for (const pattern of HEADLESS_PATTERNS) {+ if (lowerUA.includes(pattern)) {+ score += 3;+ reasons.push(`headless:${pattern}`);+ break;+ }+ }++ // 3. Missing Accept-Language header β every real browser sends this+ if (!headers["accept-language"]) {+ score += 3;+ reasons.push("missing_accept_language");+ }++ // 4. Missing Accept header+ if (!headers["accept"]) {+ score += 2;+ reasons.push("missing_accept");+ }++ // 5. Missing Accept-Encoding or no gzip support+ const acceptEncoding = headers["accept-encoding"];+ if (!acceptEncoding) {+ score += 2;+ reasons.push("missing_accept_encoding");+ } else if (+ typeof acceptEncoding === "string" &&+ !acceptEncoding.includes("gzip")+ ) {+ score += 2;+ reasons.push("no_gzip_support");+ }++ // 6. Missing sec-fetch-site when UA claims Chrome 76+ (which always sends fetch metadata)+ const chromeVersion = getChromeVersion(userAgent);+ if (chromeVersion && chromeVersion >= 76) {+ if (!headers["sec-fetch-site"]) {+ score += 2;+ reasons.push("missing_sec_fetch_site");+ }++ // 7. sec-fetch-mode mismatch β browser fetch() to /api/track uses "cors" mode, not "navigate"+ const secFetchMode = headers["sec-fetch-mode"];+ if (secFetchMode === "navigate") {+ score += 2;+ reasons.push("sec_fetch_mode_navigate");+ }+ }++ // 8. Stale Chrome version (< 80) claiming modern OS+ if (chromeVersion && chromeVersion < 80 && claimsModernOS(userAgent)) {+ score += 2;+ reasons.push("stale_chrome_version");+ }++ return {+ isBot: score >= BOT_SCORE_THRESHOLD,+ score,+ reason: reasons.length > 0 ? reasons.join(",") : undefined,+ };+}diff --git a/server/src/services/tracker/const.ts b/server/src/services/tracker/const.tsindex 9d4c7e1d6..aa081478b 100644--- a/server/src/services/tracker/const.ts+++ b/server/src/services/tracker/const.ts@@ -4,6 +4,20 @@*/export const DISABLE_ORIGIN_CHECK = process.env.DISABLE_ORIGIN_CHECK === "true";+/**+ * Minimum score from header heuristic checks to classify a request as a bot.+ * Each detection signal contributes points; if the total meets or exceeds this+ * threshold the request is silently rejected.+ */+export const BOT_SCORE_THRESHOLD = 5;++/**+ * Minimum client-side bot signal score to classify a request as a bot.+ * The client runs checks (webdriver, outerHeight===0, SwiftShader, etc.)+ * and sends a single integer. A score >= this threshold is rejected.+ */+export const CLIENT_BOT_SCORE_THRESHOLD = 3;+const searchDomains = [// Google and variants"google.com",diff --git a/server/src/services/tracker/pageviewQueue.ts b/server/src/services/tracker/pageviewQueue.tsindex d29f62e06..458144a1b 100644--- a/server/src/services/tracker/pageviewQueue.ts+++ b/server/src/services/tracker/pageviewQueue.ts@@ -47,7 +47,7 @@ class PageviewQueue {// Process each pageview with its geo dataconst processedPageviews = batch.filter(pv => {if (pv.site_id == 9133 && pv.screenWidth == 800 && pv.screenHeight == 600) {- return false+ return false;}return true;}).map(pv => {diff --git a/server/src/services/tracker/trackEvent.ts b/server/src/services/tracker/trackEvent.tsindex f3f893552..2059321b6 100644--- a/server/src/services/tracker/trackEvent.ts+++ b/server/src/services/tracker/trackEvent.ts@@ -3,6 +3,8 @@ import { isbot } from "isbot";import { z, ZodError } from "zod";import { createServiceLogger } from "../../lib/logger/logger.js";import { siteConfig } from "../../lib/siteConfig.js";+import { detectBot } from "./botDetection.js";+import { CLIENT_BOT_SCORE_THRESHOLD } from "./const.js";import { sessionsService } from "../sessions/sessionsService.js";import { usageService } from "../usageService.js";import { pageviewQueue } from "./pageviewQueue.js";@@ -24,6 +26,7 @@ const baseEventFields = {tag: z.string().max(256).optional(),ip_address: z.string().ip().optional(),user_agent: z.string().max(512).optional(),+ _bs: z.number().int().min(0).max(10).optional(),};// Default event_name and properties used by pageview and performance@@ -269,7 +272,7 @@ export async function trackEvent(request: FastifyRequest, reply: FastifyReply) {// Skip bot check for Bearer token authenticated requestsconst authHeader = request.headers["authorization"];const hasBearerToken = typeof authHeader === "string" && authHeader.startsWith("Bearer ");- if (!hasBearerToken && siteConfiguration.blockBots) {+ if (!hasBearerToken) {// Use custom user agent if provided, otherwise fall back to headerconst userAgent = validatedPayload.user_agent || (request.headers["user-agent"] as string);if (userAgent && isbot(userAgent)) {@@ -279,6 +282,49 @@ export async function trackEvent(request: FastifyRequest, reply: FastifyReply) {message: "Event not tracked - bot detected",});}++ // Layer 1: Header heuristic bot detection+ const detection = detectBot(request, userAgent || "");+ if (detection.isBot) {+ logger.info(+ { siteId: validatedPayload.site_id, userAgent, reason: detection.reason, score: detection.score },+ "Bot request filtered (heuristics)"+ );+ return reply.status(200).send({+ success: true,+ message: "Event not tracked - bot detected",+ });+ }++ // Client-side bot signal score check+ const clientBotScore = validatedPayload._bs;+ if (typeof clientBotScore === "number" && clientBotScore >= CLIENT_BOT_SCORE_THRESHOLD) {+ logger.info(+ { siteId: validatedPayload.site_id, clientBotScore },+ "Bot request filtered (client signals)"+ );+ return reply.status(200).send({+ success: true,+ message: "Event not tracked - bot detected",+ });+ }++ // Desktop 800x600 detection β Puppeteer default viewport, near-zero real desktop usage+ if (+ validatedPayload.screenWidth === 800 &&+ validatedPayload.screenHeight === 600 &&+ userAgent &&+ /Windows NT|Macintosh|X11/.test(userAgent)+ ) {+ logger.info(+ { siteId: validatedPayload.site_id, userAgent },+ "Bot request filtered (desktop 800x600)"+ );+ return reply.status(200).send({+ success: true,+ message: "Event not tracked - bot detected",+ });+ }}// Check if the site has exceeded its monthly limit (using numeric siteId)