πΈ Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Enhance bot detection logic with new screen dimension handling and tests
Bill Yangf7da5034d6de
diff --git a/server/public/script-full.js b/server/public/script-full.jsindex 4b095e5af..13cd9b4d6 100644--- a/server/public/script-full.js+++ b/server/public/script-full.js@@ -483,8 +483,14 @@impossibleDimensions: 1 << 7,outerDimensionsWeird: 1 << 8,pluginApiAbsence: 1 << 9,- defaultViewport1280x1200: 1 << 10+ defaultViewport1280x1200: 1 << 10,+ squareScreen: 1 << 11};+ var MIN_PLAUSIBLE_SCREEN_DIMENSION = 200;+ var MAX_PLAUSIBLE_SCREEN_DIMENSION = 8192;+ function isPlausibleScreenDimensions(width, height) {+ return Number.isFinite(width) && Number.isFinite(height) && width >= MIN_PLAUSIBLE_SCREEN_DIMENSION && height >= MIN_PLAUSIBLE_SCREEN_DIMENSION && width <= MAX_PLAUSIBLE_SCREEN_DIMENSION && height <= MAX_PLAUSIBLE_SCREEN_DIMENSION;+ }var cachedBotSignals = null;var MAX_BOT_SCORE = 10;function getBotScore() {@@ -548,8 +554,10 @@if ((outerHeight === 0 || outerWidth === 0) && !isPrerendering()) {addSignal(CLIENT_BOT_SIGNAL_MASKS.zeroOuterDimensions, 2);}- if (!Number.isFinite(screenWidth) || !Number.isFinite(screenHeight) || screenWidth <= 0 || screenHeight <= 0 || screenWidth > 1e5 || screenHeight > 1e5) {+ if (!isPlausibleScreenDimensions(screenWidth, screenHeight)) {addSignal(CLIENT_BOT_SIGNAL_MASKS.impossibleDimensions, 3);+ } else if (screenWidth === screenHeight) {+ addSignal(CLIENT_BOT_SIGNAL_MASKS.squareScreen, 3);}if (isDesktopUA && screenWidth === 800 && screenHeight === 600) {addSignal(CLIENT_BOT_SIGNAL_MASKS.defaultViewport800x600, 3);diff --git a/server/public/script.js b/server/public/script.jsindex 873579227..d61c42296 100644--- a/server/public/script.js+++ b/server/public/script.js@@ -1 +1 @@-"use strict";(()=>{var He=Object.defineProperty;var We=(n,e,t)=>e in n?He(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var R=(n,e,t)=>We(n,typeof e!="symbol"?e+"":e,t);function Ve(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 $(n,e){for(let t of e)try{if(Ve(t).test(n))return t}catch(r){console.error(`Invalid pattern: ${t}`,r)}return null}function ce(n,e){let t=null;return(...r)=>{t&&clearTimeout(t),t=setTimeout(()=>n(...r),e)}}function le(n){try{let e=window.location.hostname,t=new URL(n).hostname;return t!==e&&t!==""}catch{return!1}}function S(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}}var $e=2e3;function ue(){try{if(crypto?.randomUUID)return crypto.randomUUID()}catch{}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function ze(n){let e=`${n}-visitor-id`;try{let t=localStorage.getItem(e);if(t)return t;let r=ue();return localStorage.setItem(e,r),r}catch{return ue()}}function je(n){try{return localStorage.getItem(`${n}-user-id`)||void 0}catch{return}}function Ge(n){return n.hash&&n.hash.startsWith("#/")?n.hash.substring(1):n.pathname}async function Ke(n,e,t,r){let i=new AbortController,s=window.setTimeout(()=>i.abort(),$e);try{let a=new URL(window.location.href),l=await fetch(`${n}/site/${e}/feature-flags/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"omit",signal:i.signal,body:JSON.stringify({anonymousId:r,identifiedUserId:je(t),hostname:a.hostname,pathname:Ge(a),querystring:a.search,query:Object.fromEntries(a.searchParams.entries()),referrer:document.referrer,language:navigator.language,screenWidth:screen.width,screenHeight:screen.height})});if(!l.ok)return{enabled:!0,flags:{}};let u=await l.json();return{enabled:u?.featureFlagsEnabled!==!1,flags:u?.flags&&typeof u.flags=="object"?u.flags:{}}}catch{return{enabled:!0,flags:{}}}finally{window.clearTimeout(s)}}async function de(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=ze(i),a=S(n.getAttribute("data-skip-patterns"),[]),l=S(n.getAttribute("data-mask-patterns"),[]),u=S(n.getAttribute("data-replay-mask-text-selectors"),[]),d=n.getAttribute("data-debounce")?Math.max(0,parseInt(n.getAttribute("data-debounce"))):500,g=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,C=n.getAttribute("data-replay-block-class")||void 0,m=n.getAttribute("data-replay-block-selector")||void 0,o=n.getAttribute("data-replay-ignore-class")||void 0,c=n.getAttribute("data-replay-ignore-selector")||void 0,p=n.getAttribute("data-replay-mask-text-class")||void 0,w=n.getAttribute("data-replay-mask-all-inputs"),E=w!==null?w!=="false":void 0,T=n.getAttribute("data-replay-mask-input-options"),L=T?S(T,{password:!0,email:!0}):void 0,ne=n.getAttribute("data-replay-collect-fonts"),Be=ne!==null?ne!=="false":void 0,ie=n.getAttribute("data-replay-sampling"),Oe=ie?S(ie,{}):void 0,se=n.getAttribute("data-replay-slim-dom-options"),Ne=se?S(se,{}):void 0,ae=n.getAttribute("data-replay-sample-rate"),Ue=ae?Math.min(100,Math.max(0,parseInt(ae,10))):void 0,De=n.getAttribute("data-tag")||"",f={namespace:i,analyticsHost:t,siteId:r,visitorId:s,debounceDuration:d,sessionReplayBatchSize:g,sessionReplayBatchInterval:h,sessionReplayMaskTextSelectors:u,skipPatterns:a,maskPatterns:l,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,trackButtonClicks:!1,trackCopy:!1,trackFormInteractions:!1,tag:De,featureFlagsEnabled:!1,featureFlags:{},sessionReplayBlockClass:C,sessionReplayBlockSelector:m,sessionReplayIgnoreClass:o,sessionReplayIgnoreSelector:c,sessionReplayMaskTextClass:p,sessionReplayMaskAllInputs:E,sessionReplayMaskInputOptions:L,sessionReplayCollectFonts:Be,sessionReplaySampling:Oe,sessionReplaySlimDOMOptions:Ne,sessionReplaySampleRate:Ue},_=f;try{let P=`${t}/site/tracking-config/${r}`,oe=await fetch(P,{method:"GET",credentials:"omit"});if(oe.ok){let y=await oe.json();_={...f,autoTrackPageview:y.trackInitialPageView??f.autoTrackPageview,autoTrackSpa:y.trackSpaNavigation??f.autoTrackSpa,trackQuerystring:y.trackUrlParams??f.trackQuerystring,trackOutbound:y.trackOutbound??f.trackOutbound,enableWebVitals:y.webVitals??f.enableWebVitals,trackErrors:y.trackErrors??f.trackErrors,enableSessionReplay:y.sessionReplay??f.enableSessionReplay,trackButtonClicks:y.trackButtonClicks??f.trackButtonClicks,trackCopy:y.trackCopy??f.trackCopy,trackFormInteractions:y.trackFormInteractions??f.trackFormInteractions,featureFlagsEnabled:y.featureFlagsEnabled===!0}}else console.warn("Failed to fetch tracking config from API, using defaults")}catch(P){console.warn("Error fetching tracking config:",P)}if(_.featureFlagsEnabled){let P=await Ke(t,r,i,s);_.featureFlagsEnabled=P.enabled,_.featureFlags=P.flags}return _}var pe="rybbit-replay-sampled";function Je(n){if(n>=100)return!0;if(n<=0)return!1;try{let e=sessionStorage.getItem(pe);if(e!==null)return e==="1";let t=Math.random()*100<n;return sessionStorage.setItem(pe,t?"1":"0"),t}catch{return Math.random()*100<n}}var x=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&&!Je(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){e!==this.userId&&(this.eventBuffer.length>0&&this.flushEvents(),this.userId=e)}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var b={automationApi:1,webdriver:1,zeroOuterDimensions:2,missingChrome:4,swiftShader:8,emptyPlugins:16,defaultViewport800x600:32,defaultViewport1024x768:64,impossibleDimensions:128,outerDimensionsWeird:256,pluginApiAbsence:512,defaultViewport1280x1200:1024},ge=null,qe=10;function fe(){return be().score}function me(){return be().mask}function ye(){return document.prerendering===!0}function be(){return ye()?he():(ge??(ge=he()),ge)}function he(){let n=0,e=0;function t(r,i){(e&r)===0&&(e|=r,n+=i)}try{let r=navigator.userAgent,i=/Chrome\//.test(r)&&!/\bwv\b|; wv\)/.test(r),s=/Windows NT|Macintosh|X11|Linux x86_64/.test(r)&&!/Mobile|Android|iPhone|iPad/.test(r),a=Number(window.screen?.width),l=Number(window.screen?.height),u=Number(window.outerWidth),d=Number(window.outerHeight),g=Number(window.innerWidth),h=Number(window.innerHeight),m=["__webdriver_evaluate","__selenium_evaluate","__webdriver_script_function","__webdriver_script_func","__webdriver_script_fn","__fxdriver_evaluate","__driver_unwrapped","__webdriver_unwrapped","__driver_evaluate","__selenium_unwrapped","__fxdriver_unwrapped","_phantom","callPhantom","__nightmare","domAutomation","domAutomationController"].some(c=>c in window||c in document);(navigator.webdriver===!0||m)&&t(b.automationApi,3),(d===0||u===0)&&!ye()&&t(b.zeroOuterDimensions,2),(!Number.isFinite(a)||!Number.isFinite(l)||a<=0||l<=0||a>1e5||l>1e5)&&t(b.impossibleDimensions,3),s&&a===800&&l===600&&t(b.defaultViewport800x600,3),s&&a===1024&&l===768&&t(b.defaultViewport1024x768,3),s&&a===1280&&l===1200&&t(b.defaultViewport1280x1200,3),Number.isFinite(u)&&Number.isFinite(d)&&Number.isFinite(g)&&Number.isFinite(h)&&u>0&&d>0&&g>0&&h>0&&(u+8<g||d+8<h)&&t(b.outerDimensionsWeird,2);let o=!1;!window.chrome&&i&&(t(b.missingChrome,1),o=!0);try{let c=document.createElement("canvas"),p=c.getContext("webgl")||c.getContext("experimental-webgl");if(p)try{let w=[],E=p.getParameter(p.RENDERER);typeof E=="string"&&w.push(E);try{let T=p.getExtension("WEBGL_debug_renderer_info");if(T){let L=p.getParameter(T.UNMASKED_RENDERER_WEBGL);typeof L=="string"&&w.push(L)}}catch{}w.join(" ").toLowerCase().includes("swiftshader")&&t(b.swiftShader,1)}finally{Qe(c,p)}}catch{}(!navigator.plugins||navigator.plugins.length===0)&&i&&(t(b.emptyPlugins,1),o=!0),o&&t(b.pluginApiAbsence,0)}catch{}return{score:Math.min(n,qe),mask:e}}function Qe(n,e){try{e.getExtension("WEBGL_lose_context")?.loseContext?.()}catch{}n.width=0,n.height=0}var Xe=2e3,B=class{constructor(e){this.customUserId=null;this.errorDedupeCache=new Map;this.errorDedupeLastCleanup=0;this.exposedFeatureFlags=new Set;this.config=e,this.loadUserId(),e.enableSessionReplay&&this.initializeSessionReplay()}serializeFeatureFlagValue(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return""}}getFeatureFlagEventPayload(){let e={};for(let[t,r]of Object.entries(this.config.featureFlags||{}))e[t]=this.serializeFeatureFlagValue(r.value);return e}getCurrentUrlContext(){let e=new URL(window.location.href),t=e.hash&&e.hash.startsWith("#/")?e.hash.substring(1):e.pathname;return{hostname:e.hostname,pathname:t,querystring:e.search,query:Object.fromEntries(e.searchParams.entries()),referrer:document.referrer,language:navigator.language,screenWidth:screen.width,screenHeight:screen.height}}async refreshFeatureFlags(){if(!this.config.featureFlagsEnabled)return;let e=new AbortController,t=window.setTimeout(()=>e.abort(),Xe);try{let r=await fetch(`${this.config.analyticsHost}/site/${this.config.siteId}/feature-flags/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({anonymousId:this.config.visitorId,identifiedUserId:this.customUserId||void 0,...this.getCurrentUrlContext()}),mode:"cors",credentials:"omit",keepalive:!0,signal:e.signal});if(!r.ok)return;let i=await r.json();this.config.featureFlags=i?.flags&&typeof i.flags=="object"?i.flags:{},i?.featureFlagsEnabled===!1&&(this.config.featureFlagsEnabled=!1)}catch{}finally{window.clearTimeout(t)}}loadUserId(){try{let e=localStorage.getItem(`${this.config.namespace}-user-id`);e&&(this.customUserId=e)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new x(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)),$(t,this.config.skipPatterns))return null;let r=$(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,_bs:fe(),_bsm:me()};this.customUserId&&(i.user_id=this.customUserId),this.config.tag&&(i.tag=this.config.tag);let s=this.getFeatureFlagEventPayload();return Object.keys(s).length>0&&(i.feature_flags=s),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)}getFeatureFlag(e,t){let r=this.config.featureFlags?.[e];if(!r)return t;let i=`${e}:${r.version}:${this.serializeFeatureFlagValue(r.value)}`;return this.exposedFeatureFlags.has(i)||(this.exposedFeatureFlags.add(i),this.trackEvent("feature_flag_exposure",{key:e,value:this.serializeFeatureFlagValue(r.value),version:r.version,reason:r.reason})),r.value}getFeatureFlags(){return Object.fromEntries(Object.entries(this.config.featureFlags||{}).map(([e,t])=>[e,t.value]))}getFeatureFlagPayload(e,t){let r=this.config.featureFlags?.[e];return!r||r.payload===void 0?t:r.payload}getFeatureFlagPayloads(){return Object.fromEntries(Object.entries(this.config.featureFlags||{}).filter(([,e])=>e.payload!==void 0).map(([e,t])=>[e,t.payload]))}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 u=[e.name||"Error",r,t.filename||"",t.lineno??"",t.colno??""].join("|"),d=Date.now(),g=6e4,h=this.errorDedupeCache.get(u);if(h&&d-h<g)return;this.errorDedupeCache.set(u,d);let C=10*6e4;if(d-this.errorDedupeLastCleanup>g){for(let[o,c]of this.errorDedupeCache.entries())d-c>C&&this.errorDedupeCache.delete(o);this.errorDedupeLastCleanup=d}let m={message:e.message?.substring(0,500)||"Unknown error",stack:a.substring(0,2e3)||""};if(s&&(m.fileName=s),t.lineno){let o=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;o&&o!==0&&(m.lineNumber=o)}if(t.colno){let o=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;o&&o!==0&&(m.columnNumber=o)}for(let o in t)!["lineno","colno"].includes(o)&&t[o]!==void 0&&(m[o]=t[o]);this.track("error",e.name||"Error",m)}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).then(()=>this.refreshFeatureFlags()),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).then(()=>this.refreshFeatureFlags())}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{}this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(""),this.refreshFeatureFlags()}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.refreshFeatureFlags(),this.sessionReplayRecorder&&this.sessionReplayRecorder.onPageChange()}cleanup(){this.sessionReplayRecorder&&this.sessionReplayRecorder.cleanup()}};var Pe=-1,F=n=>{addEventListener("pageshow",(e=>{e.persisted&&(Pe=e.timeStamp,n(e))}),!0)},v=(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,u)=>l>u[1]?"poor":l>u[0]?"needs-improvement":"good")(e.value,t),n(e)))}},Y=n=>{requestAnimationFrame((()=>requestAnimationFrame((()=>n()))))},Z=()=>{let n=performance.getEntriesByType("navigation")[0];if(n&&n.responseStart>0&&n.responseStart<performance.now())return n},A=()=>Z()?.activationStart??0,k=(n,e=-1)=>{let t=Z(),r="navigate";return Pe>=0?r="back-forward-cache":t&&(document.prerendering||A()>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}},z=new WeakMap;function ee(n,e){return z.get(n)||z.set(n,new e),z.get(n)}var G=class{constructor(){R(this,"t");R(this,"i",0);R(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)}},M=(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{}},te=n=>{let e=!1;return()=>{e||(n(),e=!0)}},I=-1,Ie=new Set,ve=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,K=n=>{if(document.visibilityState==="hidden"){if(n.type==="visibilitychange")for(let e of Ie)e();isFinite(I)||(I=n.type==="visibilitychange"?n.timeStamp:0,removeEventListener("prerenderingchange",K,!0))}},N=()=>{if(I<0){let n=A();I=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((t=>t.name==="hidden"&&t.startTime>n))[0]?.startTime)??ve(),addEventListener("visibilitychange",K,!0),addEventListener("prerenderingchange",K,!0),F((()=>{setTimeout((()=>{I=ve()}))}))}return{get firstHiddenTime(){return I},onHidden(n){Ie.add(n)}}},U=n=>{document.prerendering?addEventListener("prerenderingchange",(()=>n()),!0):n()},ke=[1800,3e3],re=(n,e={})=>{U((()=>{let t=N(),r,i=k("FCP"),s=M("paint",(a=>{for(let l of a)l.name==="first-contentful-paint"&&(s.disconnect(),l.startTime<t.firstHiddenTime&&(i.value=Math.max(l.startTime-A(),0),i.entries.push(l),r(!0)))}));s&&(r=v(n,i,ke,e.reportAllChanges),F((a=>{i=k("FCP"),r=v(n,i,ke,e.reportAllChanges),Y((()=>{i.value=performance.now()-a.timeStamp,r(!0)}))})))}))},we=[.1,.25],Fe=(n,e={})=>{let t=N();re(te((()=>{let r,i=k("CLS",0),s=ee(e,G),a=u=>{for(let d of u)s.h(d);s.i>i.value&&(i.value=s.i,i.entries=s.o,r())},l=M("layout-shift",a);l&&(r=v(n,i,we,e.reportAllChanges),t.onHidden((()=>{a(l.takeRecords()),r(!0)})),F((()=>{s.i=0,i=k("CLS",0),r=v(n,i,we,e.reportAllChanges),Y((()=>r()))})),setTimeout(r))})))},_e=0,j=1/0,O=0,Ye=n=>{for(let e of n)e.interactionId&&(j=Math.min(j,e.interactionId),O=Math.max(O,e.interactionId),_e=O?(O-j)/7+1:0)},J,Re=()=>J?_e:performance.interactionCount??0,Ze=()=>{"interactionCount"in performance||J||(J=M("event",Ye,{type:"event",buffered:!0,durationThreshold:0}))},Ee=0,q=class{constructor(){R(this,"u",[]);R(this,"l",new Map);R(this,"m");R(this,"p")}v(){Ee=Re(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor((Re()-Ee)/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)}}},Ae=n=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?n():(n=te(n),addEventListener("visibilitychange",n,{once:!0,capture:!0}),e((()=>{n(),removeEventListener("visibilitychange",n,{capture:!0})})))},Te=[200,500],Me=(n,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let t=N();U((()=>{Ze();let r,i=k("INP"),s=ee(e,q),a=u=>{Ae((()=>{for(let g of u)s.h(g);let d=s.L();d&&d.P!==i.value&&(i.value=d.P,i.entries=d.entries,r())}))},l=M("event",a,{durationThreshold:e.durationThreshold??40});r=v(n,i,Te,e.reportAllChanges),l&&(l.observe({type:"first-input",buffered:!0}),t.onHidden((()=>{a(l.takeRecords()),r(!0)})),F((()=>{s.v(),i=k("INP"),r=v(n,i,Te,e.reportAllChanges)})))}))},Q=class{constructor(){R(this,"m")}h(e){this.m?.(e)}},Se=[2500,4e3],Le=(n,e={})=>{U((()=>{let t=N(),r,i=k("LCP"),s=ee(e,Q),a=u=>{e.reportAllChanges||(u=u.slice(-1));for(let d of u)s.h(d),d.startTime<t.firstHiddenTime&&(i.value=Math.max(d.startTime-A(),0),i.entries=[d],r())},l=M("largest-contentful-paint",a);if(l){r=v(n,i,Se,e.reportAllChanges);let u=te((()=>{a(l.takeRecords()),l.disconnect(),r(!0)})),d=g=>{g.isTrusted&&(Ae(u),removeEventListener(g.type,d,{capture:!0}))};for(let g of["keydown","click","visibilitychange"])addEventListener(g,d,{capture:!0});F((g=>{i=k("LCP"),r=v(n,i,Se,e.reportAllChanges),Y((()=>{i.value=performance.now()-g.timeStamp,r(!0)}))}))}}))},Ce=[800,1800],X=n=>{document.prerendering?U((()=>X(n))):document.readyState!=="complete"?addEventListener("load",(()=>X(n)),!0):setTimeout(n)},xe=(n,e={})=>{let t=k("TTFB"),r=v(n,t,Ce,e.reportAllChanges);X((()=>{let i=Z();i&&(t.value=Math.max(i.responseStart-A(),0),t.entries=[i],r(!0),F((()=>{t=k("TTFB",0),r=v(n,t,Ce,e.reportAllChanges),r(!0)})))}))};var D=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{Le(this.collectMetric.bind(this)),Fe(this.collectMetric.bind(this)),Me(this.collectMetric.bind(this)),re(this.collectMetric.bind(this)),xe(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 et=1e3,H=class{constructor(e,t){this.lastClickAt=new WeakMap;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=Date.now(),i=this.lastClickAt.get(t);if(i!==void 0&&r-i<et)return;this.lastClickAt.set(t,r);let s={text:this.getElementText(t),...this.extractDataAttributes(t)};this.tracker.trackButtonClick(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}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 W=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 V=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||t.readOnly)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,flag:(o,c)=>c,flagPayload:(o,c)=>c,flags:()=>({}),flagPayloads:()=>({}),onReady:()=>{},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,flag:(o,c)=>c,flagPayload:(o,c)=>c,flags:()=>({}),flagPayloads:()=>({}),onReady:i("onReady"),startSessionReplay:i("startSessionReplay"),stopSessionReplay:i("stopSessionReplay"),isSessionReplayActive:()=>!1};let s=await de(n);if(!s)return;let a=new B(s);s.enableWebVitals&&new D(c=>{a.trackWebVitals(c)}).initialize();let l=null,u=null,d=null;s.trackButtonClicks&&(l=new H(a,s),l.initialize()),s.trackCopy&&(u=new W(a),u.initialize()),s.trackFormInteractions&&(d=new V(a,s),d.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 g=()=>a.trackPageview(),h=s.debounceDuration>0?ce(g,s.debounceDuration):g;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 w={};for(let E of c.attributes)if(E.name.startsWith("data-rybbit-prop-")){let T=E.name.replace("data-rybbit-prop-","");w[T]=E.value}a.trackEvent(p,w)}break}c=c.parentElement}if(s.trackOutbound){let p=o.target.closest("a");p?.href&&le(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),h(),a.onPageChange()},history.replaceState=function(...p){c.apply(this,p),h(),a.onPageChange()},window.addEventListener("popstate",()=>{h(),a.onPageChange()}),window.addEventListener("hashchange",()=>{h(),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(),flag:(o,c)=>a.getFeatureFlag(o,c),flagPayload:(o,c)=>a.getFeatureFlagPayload(o,c),flags:()=>a.getFeatureFlags(),flagPayloads:()=>a.getFeatureFlagPayloads(),onReady:o=>o(window[s.namespace]),startSessionReplay:()=>a.startSessionReplay(),stopSessionReplay:()=>a.stopSessionReplay(),isSessionReplayActive:()=>a.isSessionReplayActive()};let m=window[s.namespace];for(let[o,c]of r)m[o](...c);C(),window.addEventListener("beforeunload",()=>{l?.cleanup(),u?.cleanup(),a.cleanup()}),s.autoTrackPageview&&a.trackPageview()})();})();+"use strict";(()=>{var Ve=Object.defineProperty;var $e=(n,e,t)=>e in n?Ve(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var R=(n,e,t)=>$e(n,typeof e!="symbol"?e+"":e,t);function ze(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 $(n,e){for(let t of e)try{if(ze(t).test(n))return t}catch(r){console.error(`Invalid pattern: ${t}`,r)}return null}function ce(n,e){let t=null;return(...r)=>{t&&clearTimeout(t),t=setTimeout(()=>n(...r),e)}}function le(n){try{let e=window.location.hostname,t=new URL(n).hostname;return t!==e&&t!==""}catch{return!1}}function T(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}}var je=2e3;function ue(){try{if(crypto?.randomUUID)return crypto.randomUUID()}catch{}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function Ge(n){let e=`${n}-visitor-id`;try{let t=localStorage.getItem(e);if(t)return t;let r=ue();return localStorage.setItem(e,r),r}catch{return ue()}}function Ke(n){try{return localStorage.getItem(`${n}-user-id`)||void 0}catch{return}}function qe(n){return n.hash&&n.hash.startsWith("#/")?n.hash.substring(1):n.pathname}async function Je(n,e,t,r){let i=new AbortController,s=window.setTimeout(()=>i.abort(),je);try{let a=new URL(window.location.href),l=await fetch(`${n}/site/${e}/feature-flags/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"omit",signal:i.signal,body:JSON.stringify({anonymousId:r,identifiedUserId:Ke(t),hostname:a.hostname,pathname:qe(a),querystring:a.search,query:Object.fromEntries(a.searchParams.entries()),referrer:document.referrer,language:navigator.language,screenWidth:screen.width,screenHeight:screen.height})});if(!l.ok)return{enabled:!0,flags:{}};let u=await l.json();return{enabled:u?.featureFlagsEnabled!==!1,flags:u?.flags&&typeof u.flags=="object"?u.flags:{}}}catch{return{enabled:!0,flags:{}}}finally{window.clearTimeout(s)}}async function de(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=Ge(i),a=T(n.getAttribute("data-skip-patterns"),[]),l=T(n.getAttribute("data-mask-patterns"),[]),u=T(n.getAttribute("data-replay-mask-text-selectors"),[]),d=n.getAttribute("data-debounce")?Math.max(0,parseInt(n.getAttribute("data-debounce"))):500,g=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,C=n.getAttribute("data-replay-block-class")||void 0,y=n.getAttribute("data-replay-block-selector")||void 0,o=n.getAttribute("data-replay-ignore-class")||void 0,c=n.getAttribute("data-replay-ignore-selector")||void 0,p=n.getAttribute("data-replay-mask-text-class")||void 0,w=n.getAttribute("data-replay-mask-all-inputs"),E=w!==null?w!=="false":void 0,S=n.getAttribute("data-replay-mask-input-options"),L=S?T(S,{password:!0,email:!0}):void 0,ne=n.getAttribute("data-replay-collect-fonts"),Ne=ne!==null?ne!=="false":void 0,ie=n.getAttribute("data-replay-sampling"),Ue=ie?T(ie,{}):void 0,se=n.getAttribute("data-replay-slim-dom-options"),De=se?T(se,{}):void 0,ae=n.getAttribute("data-replay-sample-rate"),He=ae?Math.min(100,Math.max(0,parseInt(ae,10))):void 0,We=n.getAttribute("data-tag")||"",f={namespace:i,analyticsHost:t,siteId:r,visitorId:s,debounceDuration:d,sessionReplayBatchSize:g,sessionReplayBatchInterval:h,sessionReplayMaskTextSelectors:u,skipPatterns:a,maskPatterns:l,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,trackButtonClicks:!1,trackCopy:!1,trackFormInteractions:!1,tag:We,featureFlagsEnabled:!1,featureFlags:{},sessionReplayBlockClass:C,sessionReplayBlockSelector:y,sessionReplayIgnoreClass:o,sessionReplayIgnoreSelector:c,sessionReplayMaskTextClass:p,sessionReplayMaskAllInputs:E,sessionReplayMaskInputOptions:L,sessionReplayCollectFonts:Ne,sessionReplaySampling:Ue,sessionReplaySlimDOMOptions:De,sessionReplaySampleRate:He},F=f;try{let P=`${t}/site/tracking-config/${r}`,oe=await fetch(P,{method:"GET",credentials:"omit"});if(oe.ok){let b=await oe.json();F={...f,autoTrackPageview:b.trackInitialPageView??f.autoTrackPageview,autoTrackSpa:b.trackSpaNavigation??f.autoTrackSpa,trackQuerystring:b.trackUrlParams??f.trackQuerystring,trackOutbound:b.trackOutbound??f.trackOutbound,enableWebVitals:b.webVitals??f.enableWebVitals,trackErrors:b.trackErrors??f.trackErrors,enableSessionReplay:b.sessionReplay??f.enableSessionReplay,trackButtonClicks:b.trackButtonClicks??f.trackButtonClicks,trackCopy:b.trackCopy??f.trackCopy,trackFormInteractions:b.trackFormInteractions??f.trackFormInteractions,featureFlagsEnabled:b.featureFlagsEnabled===!0}}else console.warn("Failed to fetch tracking config from API, using defaults")}catch(P){console.warn("Error fetching tracking config:",P)}if(F.featureFlagsEnabled){let P=await Je(t,r,i,s);F.featureFlagsEnabled=P.enabled,F.featureFlags=P.flags}return F}var pe="rybbit-replay-sampled";function Xe(n){if(n>=100)return!0;if(n<=0)return!1;try{let e=sessionStorage.getItem(pe);if(e!==null)return e==="1";let t=Math.random()*100<n;return sessionStorage.setItem(pe,t?"1":"0"),t}catch{return Math.random()*100<n}}var x=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){e!==this.userId&&(this.eventBuffer.length>0&&this.flushEvents(),this.userId=e)}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var m={automationApi:1,webdriver:1,zeroOuterDimensions:2,missingChrome:4,swiftShader:8,emptyPlugins:16,defaultViewport800x600:32,defaultViewport1024x768:64,impossibleDimensions:128,outerDimensionsWeird:256,pluginApiAbsence:512,defaultViewport1280x1200:1024,squareScreen:2048},ge=200,he=8192;function Qe(n,e){return Number.isFinite(n)&&Number.isFinite(e)&&n>=ge&&e>=ge&&n<=he&&e<=he}var fe=null,Ye=10;function ye(){return ke().score}function be(){return ke().mask}function ve(){return document.prerendering===!0}function ke(){return ve()?me():(fe??(fe=me()),fe)}function me(){let n=0,e=0;function t(r,i){(e&r)===0&&(e|=r,n+=i)}try{let r=navigator.userAgent,i=/Chrome\//.test(r)&&!/\bwv\b|; wv\)/.test(r),s=/Windows NT|Macintosh|X11|Linux x86_64/.test(r)&&!/Mobile|Android|iPhone|iPad/.test(r),a=Number(window.screen?.width),l=Number(window.screen?.height),u=Number(window.outerWidth),d=Number(window.outerHeight),g=Number(window.innerWidth),h=Number(window.innerHeight),y=["__webdriver_evaluate","__selenium_evaluate","__webdriver_script_function","__webdriver_script_func","__webdriver_script_fn","__fxdriver_evaluate","__driver_unwrapped","__webdriver_unwrapped","__driver_evaluate","__selenium_unwrapped","__fxdriver_unwrapped","_phantom","callPhantom","__nightmare","domAutomation","domAutomationController"].some(c=>c in window||c in document);(navigator.webdriver===!0||y)&&t(m.automationApi,3),(d===0||u===0)&&!ve()&&t(m.zeroOuterDimensions,2),Qe(a,l)?a===l&&t(m.squareScreen,3):t(m.impossibleDimensions,3),s&&a===800&&l===600&&t(m.defaultViewport800x600,3),s&&a===1024&&l===768&&t(m.defaultViewport1024x768,3),s&&a===1280&&l===1200&&t(m.defaultViewport1280x1200,3),Number.isFinite(u)&&Number.isFinite(d)&&Number.isFinite(g)&&Number.isFinite(h)&&u>0&&d>0&&g>0&&h>0&&(u+8<g||d+8<h)&&t(m.outerDimensionsWeird,2);let o=!1;!window.chrome&&i&&(t(m.missingChrome,1),o=!0);try{let c=document.createElement("canvas"),p=c.getContext("webgl")||c.getContext("experimental-webgl");if(p)try{let w=[],E=p.getParameter(p.RENDERER);typeof E=="string"&&w.push(E);try{let S=p.getExtension("WEBGL_debug_renderer_info");if(S){let L=p.getParameter(S.UNMASKED_RENDERER_WEBGL);typeof L=="string"&&w.push(L)}}catch{}w.join(" ").toLowerCase().includes("swiftshader")&&t(m.swiftShader,1)}finally{Ze(c,p)}}catch{}(!navigator.plugins||navigator.plugins.length===0)&&i&&(t(m.emptyPlugins,1),o=!0),o&&t(m.pluginApiAbsence,0)}catch{}return{score:Math.min(n,Ye),mask:e}}function Ze(n,e){try{e.getExtension("WEBGL_lose_context")?.loseContext?.()}catch{}n.width=0,n.height=0}var et=2e3,B=class{constructor(e){this.customUserId=null;this.errorDedupeCache=new Map;this.errorDedupeLastCleanup=0;this.exposedFeatureFlags=new Set;this.config=e,this.loadUserId(),e.enableSessionReplay&&this.initializeSessionReplay()}serializeFeatureFlagValue(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return""}}getFeatureFlagEventPayload(){let e={};for(let[t,r]of Object.entries(this.config.featureFlags||{}))e[t]=this.serializeFeatureFlagValue(r.value);return e}getCurrentUrlContext(){let e=new URL(window.location.href),t=e.hash&&e.hash.startsWith("#/")?e.hash.substring(1):e.pathname;return{hostname:e.hostname,pathname:t,querystring:e.search,query:Object.fromEntries(e.searchParams.entries()),referrer:document.referrer,language:navigator.language,screenWidth:screen.width,screenHeight:screen.height}}async refreshFeatureFlags(){if(!this.config.featureFlagsEnabled)return;let e=new AbortController,t=window.setTimeout(()=>e.abort(),et);try{let r=await fetch(`${this.config.analyticsHost}/site/${this.config.siteId}/feature-flags/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({anonymousId:this.config.visitorId,identifiedUserId:this.customUserId||void 0,...this.getCurrentUrlContext()}),mode:"cors",credentials:"omit",keepalive:!0,signal:e.signal});if(!r.ok)return;let i=await r.json();this.config.featureFlags=i?.flags&&typeof i.flags=="object"?i.flags:{},i?.featureFlagsEnabled===!1&&(this.config.featureFlagsEnabled=!1)}catch{}finally{window.clearTimeout(t)}}loadUserId(){try{let e=localStorage.getItem(`${this.config.namespace}-user-id`);e&&(this.customUserId=e)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new x(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)),$(t,this.config.skipPatterns))return null;let r=$(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,_bs:ye(),_bsm:be()};this.customUserId&&(i.user_id=this.customUserId),this.config.tag&&(i.tag=this.config.tag);let s=this.getFeatureFlagEventPayload();return Object.keys(s).length>0&&(i.feature_flags=s),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)}getFeatureFlag(e,t){let r=this.config.featureFlags?.[e];if(!r)return t;let i=`${e}:${r.version}:${this.serializeFeatureFlagValue(r.value)}`;return this.exposedFeatureFlags.has(i)||(this.exposedFeatureFlags.add(i),this.trackEvent("feature_flag_exposure",{key:e,value:this.serializeFeatureFlagValue(r.value),version:r.version,reason:r.reason})),r.value}getFeatureFlags(){return Object.fromEntries(Object.entries(this.config.featureFlags||{}).map(([e,t])=>[e,t.value]))}getFeatureFlagPayload(e,t){let r=this.config.featureFlags?.[e];return!r||r.payload===void 0?t:r.payload}getFeatureFlagPayloads(){return Object.fromEntries(Object.entries(this.config.featureFlags||{}).filter(([,e])=>e.payload!==void 0).map(([e,t])=>[e,t.payload]))}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 u=[e.name||"Error",r,t.filename||"",t.lineno??"",t.colno??""].join("|"),d=Date.now(),g=6e4,h=this.errorDedupeCache.get(u);if(h&&d-h<g)return;this.errorDedupeCache.set(u,d);let C=10*6e4;if(d-this.errorDedupeLastCleanup>g){for(let[o,c]of this.errorDedupeCache.entries())d-c>C&&this.errorDedupeCache.delete(o);this.errorDedupeLastCleanup=d}let y={message:e.message?.substring(0,500)||"Unknown error",stack:a.substring(0,2e3)||""};if(s&&(y.fileName=s),t.lineno){let o=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;o&&o!==0&&(y.lineNumber=o)}if(t.colno){let o=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;o&&o!==0&&(y.columnNumber=o)}for(let o in t)!["lineno","colno"].includes(o)&&t[o]!==void 0&&(y[o]=t[o]);this.track("error",e.name||"Error",y)}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).then(()=>this.refreshFeatureFlags()),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).then(()=>this.refreshFeatureFlags())}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{}this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(""),this.refreshFeatureFlags()}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.refreshFeatureFlags(),this.sessionReplayRecorder&&this.sessionReplayRecorder.onPageChange()}cleanup(){this.sessionReplayRecorder&&this.sessionReplayRecorder.cleanup()}};var _e=-1,_=n=>{addEventListener("pageshow",(e=>{e.persisted&&(_e=e.timeStamp,n(e))}),!0)},v=(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,u)=>l>u[1]?"poor":l>u[0]?"needs-improvement":"good")(e.value,t),n(e)))}},Y=n=>{requestAnimationFrame((()=>requestAnimationFrame((()=>n()))))},Z=()=>{let n=performance.getEntriesByType("navigation")[0];if(n&&n.responseStart>0&&n.responseStart<performance.now())return n},A=()=>Z()?.activationStart??0,k=(n,e=-1)=>{let t=Z(),r="navigate";return _e>=0?r="back-forward-cache":t&&(document.prerendering||A()>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}},z=new WeakMap;function ee(n,e){return z.get(n)||z.set(n,new e),z.get(n)}var G=class{constructor(){R(this,"t");R(this,"i",0);R(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)}},M=(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{}},te=n=>{let e=!1;return()=>{e||(n(),e=!0)}},I=-1,Fe=new Set,we=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,K=n=>{if(document.visibilityState==="hidden"){if(n.type==="visibilitychange")for(let e of Fe)e();isFinite(I)||(I=n.type==="visibilitychange"?n.timeStamp:0,removeEventListener("prerenderingchange",K,!0))}},N=()=>{if(I<0){let n=A();I=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((t=>t.name==="hidden"&&t.startTime>n))[0]?.startTime)??we(),addEventListener("visibilitychange",K,!0),addEventListener("prerenderingchange",K,!0),_((()=>{setTimeout((()=>{I=we()}))}))}return{get firstHiddenTime(){return I},onHidden(n){Fe.add(n)}}},U=n=>{document.prerendering?addEventListener("prerenderingchange",(()=>n()),!0):n()},Re=[1800,3e3],re=(n,e={})=>{U((()=>{let t=N(),r,i=k("FCP"),s=M("paint",(a=>{for(let l of a)l.name==="first-contentful-paint"&&(s.disconnect(),l.startTime<t.firstHiddenTime&&(i.value=Math.max(l.startTime-A(),0),i.entries.push(l),r(!0)))}));s&&(r=v(n,i,Re,e.reportAllChanges),_((a=>{i=k("FCP"),r=v(n,i,Re,e.reportAllChanges),Y((()=>{i.value=performance.now()-a.timeStamp,r(!0)}))})))}))},Ee=[.1,.25],Ae=(n,e={})=>{let t=N();re(te((()=>{let r,i=k("CLS",0),s=ee(e,G),a=u=>{for(let d of u)s.h(d);s.i>i.value&&(i.value=s.i,i.entries=s.o,r())},l=M("layout-shift",a);l&&(r=v(n,i,Ee,e.reportAllChanges),t.onHidden((()=>{a(l.takeRecords()),r(!0)})),_((()=>{s.i=0,i=k("CLS",0),r=v(n,i,Ee,e.reportAllChanges),Y((()=>r()))})),setTimeout(r))})))},Me=0,j=1/0,O=0,tt=n=>{for(let e of n)e.interactionId&&(j=Math.min(j,e.interactionId),O=Math.max(O,e.interactionId),Me=O?(O-j)/7+1:0)},q,Se=()=>q?Me:performance.interactionCount??0,rt=()=>{"interactionCount"in performance||q||(q=M("event",tt,{type:"event",buffered:!0,durationThreshold:0}))},Te=0,J=class{constructor(){R(this,"u",[]);R(this,"l",new Map);R(this,"m");R(this,"p")}v(){Te=Se(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor((Se()-Te)/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)}}},Le=n=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?n():(n=te(n),addEventListener("visibilitychange",n,{once:!0,capture:!0}),e((()=>{n(),removeEventListener("visibilitychange",n,{capture:!0})})))},Ce=[200,500],xe=(n,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let t=N();U((()=>{rt();let r,i=k("INP"),s=ee(e,J),a=u=>{Le((()=>{for(let g of u)s.h(g);let d=s.L();d&&d.P!==i.value&&(i.value=d.P,i.entries=d.entries,r())}))},l=M("event",a,{durationThreshold:e.durationThreshold??40});r=v(n,i,Ce,e.reportAllChanges),l&&(l.observe({type:"first-input",buffered:!0}),t.onHidden((()=>{a(l.takeRecords()),r(!0)})),_((()=>{s.v(),i=k("INP"),r=v(n,i,Ce,e.reportAllChanges)})))}))},X=class{constructor(){R(this,"m")}h(e){this.m?.(e)}},Pe=[2500,4e3],Be=(n,e={})=>{U((()=>{let t=N(),r,i=k("LCP"),s=ee(e,X),a=u=>{e.reportAllChanges||(u=u.slice(-1));for(let d of u)s.h(d),d.startTime<t.firstHiddenTime&&(i.value=Math.max(d.startTime-A(),0),i.entries=[d],r())},l=M("largest-contentful-paint",a);if(l){r=v(n,i,Pe,e.reportAllChanges);let u=te((()=>{a(l.takeRecords()),l.disconnect(),r(!0)})),d=g=>{g.isTrusted&&(Le(u),removeEventListener(g.type,d,{capture:!0}))};for(let g of["keydown","click","visibilitychange"])addEventListener(g,d,{capture:!0});_((g=>{i=k("LCP"),r=v(n,i,Pe,e.reportAllChanges),Y((()=>{i.value=performance.now()-g.timeStamp,r(!0)}))}))}}))},Ie=[800,1800],Q=n=>{document.prerendering?U((()=>Q(n))):document.readyState!=="complete"?addEventListener("load",(()=>Q(n)),!0):setTimeout(n)},Oe=(n,e={})=>{let t=k("TTFB"),r=v(n,t,Ie,e.reportAllChanges);Q((()=>{let i=Z();i&&(t.value=Math.max(i.responseStart-A(),0),t.entries=[i],r(!0),_((()=>{t=k("TTFB",0),r=v(n,t,Ie,e.reportAllChanges),r(!0)})))}))};var D=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{Be(this.collectMetric.bind(this)),Ae(this.collectMetric.bind(this)),xe(this.collectMetric.bind(this)),re(this.collectMetric.bind(this)),Oe(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 nt=1e3,H=class{constructor(e,t){this.lastClickAt=new WeakMap;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=Date.now(),i=this.lastClickAt.get(t);if(i!==void 0&&r-i<nt)return;this.lastClickAt.set(t,r);let s={text:this.getElementText(t),...this.extractDataAttributes(t)};this.tracker.trackButtonClick(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}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 W=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 V=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||t.readOnly)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,flag:(o,c)=>c,flagPayload:(o,c)=>c,flags:()=>({}),flagPayloads:()=>({}),onReady:()=>{},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,flag:(o,c)=>c,flagPayload:(o,c)=>c,flags:()=>({}),flagPayloads:()=>({}),onReady:i("onReady"),startSessionReplay:i("startSessionReplay"),stopSessionReplay:i("stopSessionReplay"),isSessionReplayActive:()=>!1};let s=await de(n);if(!s)return;let a=new B(s);s.enableWebVitals&&new D(c=>{a.trackWebVitals(c)}).initialize();let l=null,u=null,d=null;s.trackButtonClicks&&(l=new H(a,s),l.initialize()),s.trackCopy&&(u=new W(a),u.initialize()),s.trackFormInteractions&&(d=new V(a,s),d.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 g=()=>a.trackPageview(),h=s.debounceDuration>0?ce(g,s.debounceDuration):g;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 w={};for(let E of c.attributes)if(E.name.startsWith("data-rybbit-prop-")){let S=E.name.replace("data-rybbit-prop-","");w[S]=E.value}a.trackEvent(p,w)}break}c=c.parentElement}if(s.trackOutbound){let p=o.target.closest("a");p?.href&&le(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),h(),a.onPageChange()},history.replaceState=function(...p){c.apply(this,p),h(),a.onPageChange()},window.addEventListener("popstate",()=>{h(),a.onPageChange()}),window.addEventListener("hashchange",()=>{h(),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(),flag:(o,c)=>a.getFeatureFlag(o,c),flagPayload:(o,c)=>a.getFeatureFlagPayload(o,c),flags:()=>a.getFeatureFlags(),flagPayloads:()=>a.getFeatureFlagPayloads(),onReady:o=>o(window[s.namespace]),startSessionReplay:()=>a.startSessionReplay(),stopSessionReplay:()=>a.stopSessionReplay(),isSessionReplayActive:()=>a.isSessionReplayActive()};let y=window[s.namespace];for(let[o,c]of r)y[o](...c);C(),window.addEventListener("beforeunload",()=>{l?.cleanup(),u?.cleanup(),a.cleanup()}),s.autoTrackPageview&&a.trackPageview()})();})();diff --git a/server/src/analytics-script/botSignals.test.ts b/server/src/analytics-script/botSignals.test.tsindex a44bb5f96..0bbd35552 100644--- a/server/src/analytics-script/botSignals.test.ts+++ b/server/src/analytics-script/botSignals.test.ts@@ -90,6 +90,42 @@ describe("getBotScore", () => {expect(getBotSignalMask()).toBe(CLIENT_BOT_SIGNAL_MASKS.impossibleDimensions);});+ it("treats dimensions outside the plausible display range as impossible", () => {+ for (const screen of [+ { width: 1, height: 1 },+ { width: 16384, height: 16384 },+ { width: 1920, height: 10000 },+ { width: 199, height: 800 },+ ]) {+ resetBotScoreCacheForTests();+ setWindowProperty("screen", screen);++ expect(getBotSignalMask(), `${screen.width}x${screen.height}`).toBe(+ CLIENT_BOT_SIGNAL_MASKS.impossibleDimensions+ );+ }+ });++ it("leaves real displays at the edges of the plausible range alone", () => {+ for (const screen of [+ { width: 200, height: 320 },+ { width: 320, height: 480 },+ { width: 7680, height: 4320 },+ ]) {+ resetBotScoreCacheForTests();+ setWindowProperty("screen", screen);++ expect(getBotSignalMask(), `${screen.width}x${screen.height}`).toBe(0);+ }+ });++ it("weights a square screen as a blocking-strength signal", () => {+ setWindowProperty("screen", { width: 2000, height: 2000 });++ expect(getBotScore()).toBe(3);+ expect(getBotSignalMask()).toBe(CLIENT_BOT_SIGNAL_MASKS.squareScreen);+ });+it("counts outer dimension anomalies as a supporting signal", () => {setWindowProperty("outerWidth", 800);setWindowProperty("innerWidth", 1000);diff --git a/server/src/analytics-script/botSignals.ts b/server/src/analytics-script/botSignals.tsindex e6504ecf3..c8c9ae5c1 100644--- a/server/src/analytics-script/botSignals.ts+++ b/server/src/analytics-script/botSignals.ts@@ -18,8 +18,31 @@ export const CLIENT_BOT_SIGNAL_MASKS = {outerDimensionsWeird: 1 << 8,pluginApiAbsence: 1 << 9,defaultViewport1280x1200: 1 << 10,+ squareScreen: 1 << 11,} as const;+/**+ * Plausible bounds for `screen.width`/`screen.height` β the physical display,+ * not the window, so neither a resized window nor a zoomed page moves them.+ * The smallest real phone screens report ~240 CSS px; the largest single+ * display (8K) reports 7680. Values outside this range come from synthetic+ * renderers: production traffic outside it is 1x1, 16384x16384, and+ * 1920x10000-style screenshot viewports on cloud ASNs, with no engagement.+ */+const MIN_PLAUSIBLE_SCREEN_DIMENSION = 200;+const MAX_PLAUSIBLE_SCREEN_DIMENSION = 8192;++function isPlausibleScreenDimensions(width: number, height: number): boolean {+ return (+ Number.isFinite(width) &&+ Number.isFinite(height) &&+ width >= MIN_PLAUSIBLE_SCREEN_DIMENSION &&+ height >= MIN_PLAUSIBLE_SCREEN_DIMENSION &&+ width <= MAX_PLAUSIBLE_SCREEN_DIMENSION &&+ height <= MAX_PLAUSIBLE_SCREEN_DIMENSION+ );+}+interface BotSignalResult {score: number;mask: number;@@ -106,18 +129,22 @@ function calculateBotSignals(): BotSignalResult {addSignal(CLIENT_BOT_SIGNAL_MASKS.zeroOuterDimensions, 2);}- // 3. Impossible screen dimensions β invalid values from a browser-side payload- if (- !Number.isFinite(screenWidth) ||- !Number.isFinite(screenHeight) ||- screenWidth <= 0 ||- screenHeight <= 0 ||- screenWidth > 100000 ||- screenHeight > 100000- ) {+ // 3. Screen dimensions outside the range any real display reports+ if (!isPlausibleScreenDimensions(screenWidth, screenHeight)) {addSignal(CLIENT_BOT_SIGNAL_MASKS.impossibleDimensions, 3);}+ // 3b. Square screen. No shipping display is square, and every square value+ // in production traffic belongs to a renderer default β 2000x2000 on+ // Facebook/Amazon/Google infrastructure, 1024x1024 and 1280x1280 on+ // Google's, 1366x1366 and 1600x1600 on proxy fleets. Over a full day of+ // traffic, square-screen visitors fired interaction events on 0.5% of+ // their events against 6.1% for current-version traffic, so this+ // convicts rather than corroborates.+ else if (screenWidth === screenHeight) {+ addSignal(CLIENT_BOT_SIGNAL_MASKS.squareScreen, 3);+ }+// 4. Default automation/display server viewport sizes. 1280x1200 is not a// panel size any desktop ships; it is a headless window geometry, and in// production it appears essentially only on scraper fleets (27M events indiff --git a/server/src/services/tracker/botBlocking/botDetectionStats.ts b/server/src/services/tracker/botBlocking/botDetectionStats.tsindex 27ac02127..f64f5396a 100644--- a/server/src/services/tracker/botBlocking/botDetectionStats.ts+++ b/server/src/services/tracker/botBlocking/botDetectionStats.ts@@ -49,6 +49,8 @@ const CLIENT_BOT_SIGNAL_COMPONENTS = [["impossibleDimensions", 1 << 7],["outerDimensionsWeird", 1 << 8],["pluginApiAbsence", 1 << 9],+ ["defaultViewport1280x1200", 1 << 10],+ ["squareScreen", 1 << 11],] as const;type ClientBotSignalComponent = (typeof CLIENT_BOT_SIGNAL_COMPONENTS)[number][0];@@ -68,6 +70,8 @@ const clientBotSignalTotals: Record<ClientBotSignalTotal, number> = {impossibleDimensions: 0,outerDimensionsWeird: 0,pluginApiAbsence: 0,+ defaultViewport1280x1200: 0,+ squareScreen: 0,unknownMaskBits: 0,};diff --git a/server/src/services/tracker/botBlocking/botProviderAsns.test.ts b/server/src/services/tracker/botBlocking/botProviderAsns.test.tsindex 0a38fe744..34df4e660 100644--- a/server/src/services/tracker/botBlocking/botProviderAsns.test.ts+++ b/server/src/services/tracker/botBlocking/botProviderAsns.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from "vitest";-import { classifyBotAsn, CURATED_BOT_PROVIDER_ASN_COUNT } from "./botProviderAsns.js";+import { classifyBotAsn, CURATED_BOT_PROVIDER_ASN_COUNT, EXTRA_DATACENTER_ASNS } from "./botProviderAsns.js";describe("bot ASN classification", () => {it("matches ipverse hosting ASNs", () => {@@ -33,6 +33,32 @@ describe("bot ASN classification", () => {});});+ it("matches curated scraping infrastructure ipverse does not categorize as hosting", () => {+ expect(classifyBotAsn(64267)).toMatchObject({+ isBotInfrastructure: true,+ source: "curated_bot_provider",+ provider: "Sprious",+ category: "scraping_infrastructure",+ });+ expect(classifyBotAsn(64286)).toMatchObject({+ isBotInfrastructure: true,+ source: "curated_bot_provider",+ provider: "LogicWeb",+ });+ });++ it("treats curated hosting ASNs as corroborating, like an ipverse hosting match", () => {+ // These are general-purpose networks a real visitor could sit behind, so+ // they carry hosting weight rather than the convicting curated-provider+ // source β checkBotBlocking blocks only on "curated_bot_provider".+ for (const asn of EXTRA_DATACENTER_ASNS) {+ expect(classifyBotAsn(asn), String(asn)).toMatchObject({+ isBotInfrastructure: true,+ source: "curated_hosting",+ });+ }+ });+it("does not match arbitrary business ASNs", () => {expect(classifyBotAsn(13949)).toEqual({ isBotInfrastructure: false });expect(CURATED_BOT_PROVIDER_ASN_COUNT).toBeGreaterThan(0);diff --git a/server/src/services/tracker/botBlocking/botProviderAsns.ts b/server/src/services/tracker/botBlocking/botProviderAsns.tsindex d69e7b301..7e1b163c4 100644--- a/server/src/services/tracker/botBlocking/botProviderAsns.ts+++ b/server/src/services/tracker/botBlocking/botProviderAsns.ts@@ -1,7 +1,7 @@import { isDatacenterAsn } from "./datacenterAsns.js";-export type BotAsnSource = "ipverse_hosting" | "curated_bot_provider";-export type CuratedBotProviderCategory = "ai" | "security_scanner" | "internet_measurement";+export type BotAsnSource = "ipverse_hosting" | "curated_bot_provider" | "curated_hosting";+export type CuratedBotProviderCategory = "ai" | "security_scanner" | "internet_measurement" | "scraping_infrastructure";interface CuratedBotProviderAsnEntry {asn: number;@@ -49,8 +49,50 @@ export const CURATED_BOT_PROVIDER_ASNS: readonly CuratedBotProviderAsnEntry[] =category: "internet_measurement",note: "internet measurement scanner provider",},++ // Crawler infrastructure ipverse does not categorize as hosting. Each was+ // added from measured traffic shape, not from the organization name: over+ // three days each reached hundreds of distinct sites while producing at most+ // a handful of interaction events in total, which no access network does.+ {+ asn: 64267,+ provider: "Sprious",+ category: "scraping_infrastructure",+ note: "710 sites / 1203 visitors / 4 interaction events in 3d; desktop Linux Chrome",+ },+ {+ asn: 64286,+ provider: "LogicWeb",+ category: "scraping_infrastructure",+ note: "1001 sites / 774 visitors / 4 interaction events in 3d; desktop Linux Chrome",+ },+ {+ asn: 398464,+ provider: "Buddy Software",+ category: "scraping_infrastructure",+ note: "175 sites / 166 visitors / 0 interaction events in 3d; web vitals on 0.1% of events",+ },];+/**+ * Hosting/proxy networks missing from the ipverse `hosting` category. These+ * carry the same weight as an ipverse hosting match β corroborating only, never+ * convicting β because unlike the curated list above they are general-purpose+ * networks a real visitor could plausibly sit behind (corporate VPN, browser+ * isolation, mobile proxy). Their traffic here is bot-shaped, but the shape is+ * evidence, not proof of what the ASN is for.+ */+export const EXTRA_DATACENTER_ASNS: readonly number[] = [+ 30236, // Cronomagic Canada Inc. β 103 sites / 168 visitors / 0 interactions in 3d+ 50077, // SYN LTD β 141 sites / 691 visitors / 0 interactions in 3d+ 64445, // NetJoin srl β 117 sites / 458 visitors / 0 interactions in 3d+ 134756, // CHINANET Nanjing Jishan IDC network β 295 sites / 204 visitors / 0 interactions in 3d+ 209372, // WS Telecom Inc β 384 sites / 1286 visitors / 1 interaction in 3d+ 213541, // WS Telecom Inc β 166 sites / 311 visitors / 0 interactions in 3d+];++const EXTRA_DATACENTER_ASN_SET: ReadonlySet<number> = new Set(EXTRA_DATACENTER_ASNS);+export const CURATED_BOT_PROVIDER_ASN_COUNT = CURATED_BOT_PROVIDER_ASNS.length;const CURATED_BOT_PROVIDER_ASN_MAP: ReadonlyMap<number, CuratedBotProviderAsnEntry> = new Map(@@ -80,5 +122,12 @@ export function classifyBotAsn(asn: number | null | undefined): BotAsnMatch {};}+ if (EXTRA_DATACENTER_ASN_SET.has(asn)) {+ return {+ isBotInfrastructure: true,+ source: "curated_hosting",+ };+ }+return { isBotInfrastructure: false };}diff --git a/server/src/services/tracker/botBlocking/index.test.ts b/server/src/services/tracker/botBlocking/index.test.tsindex 189606db5..1234e2e92 100644--- a/server/src/services/tracker/botBlocking/index.test.ts+++ b/server/src/services/tracker/botBlocking/index.test.ts@@ -535,4 +535,133 @@ describe("checkBotBlocking", () => {expect(result?.detections.map(detection => detection.layer)).toEqual(["rate_anomaly"]);expect(result?.detections[0].anomalyReasons?.map(reason => reason.rule)).toContain("tuple_events_10s");});++ it("convicts a browser release too old to have run the tracker", async () => {+ const userAgent =+ "Mozilla/5.0 (Linux; Android 8.0; SM-G930F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.0.0 Mobile Safari/537.36";++ const result = await checkBotBlocking({+ request: requestWithHeaders({ ...browserHeaders, "user-agent": userAgent }),+ blockBots: true,+ payload: {+ ...basePayload,+ userAgent,+ clientBotScore: 0,+ clientBotSignalMask: 0,+ screenWidth: 375,+ screenHeight: 812,+ },+ });++ expect(result).toMatchObject({+ isBot: true,+ message: "Bot detected using ua-pattern",+ eventProperties: {+ detectedUaPattern: true,+ botCategory: "stale_version",+ matchedUaPattern: "Chrome/40",+ },+ });+ expect(result?.detections.map(detection => detection.layer)).toEqual(["ua_pattern"]);+ });++ it("keeps a stale version from overriding a more specific UA pattern match", async () => {+ const userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) HeadlessChrome/40.0.0.0 Safari/537.36";++ const result = await checkBotBlocking({+ request: requestWithHeaders({ ...browserHeaders, "user-agent": userAgent }),+ blockBots: true,+ payload: { ...basePayload, userAgent, clientBotScore: 0, clientBotSignalMask: 0 },+ });++ expect(result).toMatchObject({+ eventProperties: { botCategory: "headless", matchedUaPattern: "headlesschrome" },+ });+ });++ it("skips the stale-version rule for mobile sites, where native SDK traffic is not browser-shaped", async () => {+ const userAgent =+ "Mozilla/5.0 (Linux; Android 8.0; SM-G930F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.0.0 Mobile Safari/537.36";++ const result = await checkBotBlocking({+ request: requestWithHeaders({ ...browserHeaders, "user-agent": userAgent }),+ blockBots: true,+ isMobileSite: true,+ payload: { ...basePayload, userAgent, clientBotScore: 0, clientBotSignalMask: 0 },+ });++ expect(result).toBeNull();+ });++ it("convicts a square screen, which no shipping display reports", async () => {+ const result = await checkBotBlocking({+ request: requestWithHeaders(browserHeaders),+ blockBots: true,+ payload: {+ ...basePayload,+ clientBotScore: 0,+ clientBotSignalMask: 0,+ screenWidth: 2000,+ screenHeight: 2000,+ },+ });++ expect(result).toMatchObject({+ isBot: true,+ message: "Bot detected using client signals",+ eventProperties: { detectedClientSignals: true },+ });+ expect(result?.detections[0]).toMatchObject({ clientSignals: ["squareScreen"] });+ });++ it("convicts a square screen on a mobile UA too", async () => {+ // The square fleets claim Android and iOS as well as desktop, so unlike the+ // default-viewport rules this one is not gated on a desktop user-agent.+ const result = await checkBotBlocking({+ request: requestWithHeaders({+ ...browserHeaders,+ "user-agent":+ "Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/150.0.0.0 Mobile Safari/537.36",+ }),+ blockBots: true,+ payload: { ...basePayload, clientBotScore: 0, clientBotSignalMask: 0, screenWidth: 2000, screenHeight: 2000 },+ });++ expect(result?.detections[0]).toMatchObject({ clientSignals: ["squareScreen"] });+ });++ it("convicts screen dimensions outside the range a real display reports", async () => {+ for (const [screenWidth, screenHeight] of [+ [1, 1],+ [16384, 16384],+ [1920, 10000],+ ]) {+ resetBotDetectionStatsForTests();+ const result = await checkBotBlocking({+ request: requestWithHeaders(browserHeaders),+ blockBots: true,+ payload: { ...basePayload, clientBotScore: 0, clientBotSignalMask: 0, screenWidth, screenHeight },+ });++ expect(result?.detections[0], `${screenWidth}x${screenHeight}`).toMatchObject({+ clientSignals: ["impossibleDimensions"],+ });+ }+ });++ it("leaves real displays at the edges of the plausible range alone", async () => {+ for (const [screenWidth, screenHeight] of [+ [320, 480], // smallest phones+ [7680, 4320], // 8K desktop+ [1920, 1080],+ ]) {+ const result = await checkBotBlocking({+ request: requestWithHeaders(browserHeaders),+ blockBots: true,+ payload: { ...basePayload, clientBotScore: 0, clientBotSignalMask: 0, screenWidth, screenHeight },+ });++ expect(result, `${screenWidth}x${screenHeight}`).toBeNull();+ }+ });});diff --git a/server/src/services/tracker/botBlocking/index.ts b/server/src/services/tracker/botBlocking/index.tsindex 3ba03ade4..421167325 100644--- a/server/src/services/tracker/botBlocking/index.ts+++ b/server/src/services/tracker/botBlocking/index.ts@@ -8,6 +8,7 @@ import { recordBotBlockingRequest, recordBotDetections } from "./botDetectionStaimport { classifyBotAsn } from "./botProviderAsns.js";import { CLIENT_BOT_SCORE_THRESHOLD } from "./config.js";import { detectBot } from "./headerHeuristics.js";+import { classifyStaleBrowserVersion } from "./staleBrowserVersion.js";import { classifyUA } from "./uaBots/index.js";// Per-detection logging is verbose and costly at high traffic; off by default.@@ -60,6 +61,7 @@ const CLIENT_SIGNAL_MASKS = {outerDimensionsWeird: 1 << 8,pluginApiAbsence: 1 << 9,defaultViewport1280x1200: 1 << 10,+ squareScreen: 1 << 11,} as const;type ClientSignalName = keyof typeof CLIENT_SIGNAL_MASKS;@@ -79,6 +81,7 @@ const CLIENT_SIGNAL_WEIGHTS: Record<ClientSignalName, number> = {outerDimensionsWeird: 2,pluginApiAbsence: 0,defaultViewport1280x1200: 3,+ squareScreen: 3,};// Signals that are automation-specific enough to convict on their own. The@@ -91,7 +94,8 @@ const STRONG_CLIENT_SIGNAL_BITS =CLIENT_SIGNAL_MASKS.impossibleDimensions |CLIENT_SIGNAL_MASKS.defaultViewport800x600 |CLIENT_SIGNAL_MASKS.defaultViewport1024x768 |- CLIENT_SIGNAL_MASKS.defaultViewport1280x1200;+ CLIENT_SIGNAL_MASKS.defaultViewport1280x1200 |+ CLIENT_SIGNAL_MASKS.squareScreen;function sumClientSignalWeights(mask: number): number {return Object.entries(CLIENT_SIGNAL_MASKS).reduce(@@ -169,6 +173,23 @@ function isFiniteDimension(value: unknown): value is number {return typeof value === "number" && Number.isFinite(value);}+// Mirrors MIN/MAX_PLAUSIBLE_SCREEN_DIMENSION in analytics-script/botSignals.ts.+// The payload carries screen.width/height β the physical display, not the+// window β so no amount of resizing or zoom moves a real value outside these.+const MIN_PLAUSIBLE_SCREEN_DIMENSION = 200;+const MAX_PLAUSIBLE_SCREEN_DIMENSION = 8192;++function isPlausibleScreenDimensions(width: unknown, height: unknown): boolean {+ return (+ isFiniteDimension(width) &&+ isFiniteDimension(height) &&+ width >= MIN_PLAUSIBLE_SCREEN_DIMENSION &&+ height >= MIN_PLAUSIBLE_SCREEN_DIMENSION &&+ width <= MAX_PLAUSIBLE_SCREEN_DIMENSION &&+ height <= MAX_PLAUSIBLE_SCREEN_DIMENSION+ );+}+function isDesktopUserAgent(userAgent: string) {return /Windows NT|Macintosh|X11|Linux x86_64/.test(userAgent) && !/Mobile|Android|iPhone|iPad/.test(userAgent);}@@ -197,27 +218,30 @@ function getClientSignalResult(payload: BotBlockingPayload, userAgent: string) {}}+ // Re-derived server-side rather than trusted from the client mask, so the+ // rules apply to every hit regardless of which tracker version sent it.const { screenWidth, screenHeight } = payload;const hasScreenDimensions = screenWidth !== undefined || screenHeight !== undefined;- if (- hasScreenDimensions &&- (!isFiniteDimension(screenWidth) ||- !isFiniteDimension(screenHeight) ||- screenWidth <= 0 ||- screenHeight <= 0 ||- screenWidth > 100000 ||- screenHeight > 100000)- ) {+ if (hasScreenDimensions && !isPlausibleScreenDimensions(screenWidth, screenHeight)) {addInferredSignal("impossibleDimensions", 3);- } else if (isFiniteDimension(screenWidth) && isFiniteDimension(screenHeight) && isDesktopUserAgent(userAgent)) {- if (screenWidth === 800 && screenHeight === 600) {- addInferredSignal("defaultViewport800x600", 3);+ } else if (isFiniteDimension(screenWidth) && isFiniteDimension(screenHeight)) {+ // No shipping display is square; every square value in production traffic+ // is a renderer default (2000x2000, 1024x1024, 1280x1280, 1366x1366).+ // Not gated on a desktop UA β the square fleets also claim Android and iOS.+ if (screenWidth === screenHeight) {+ addInferredSignal("squareScreen", 3);}- if (screenWidth === 1024 && screenHeight === 768) {- addInferredSignal("defaultViewport1024x768", 3);- }- if (screenWidth === 1280 && screenHeight === 1200) {- addInferredSignal("defaultViewport1280x1200", 3);++ if (isDesktopUserAgent(userAgent)) {+ if (screenWidth === 800 && screenHeight === 600) {+ addInferredSignal("defaultViewport800x600", 3);+ }+ if (screenWidth === 1024 && screenHeight === 768) {+ addInferredSignal("defaultViewport1024x768", 3);+ }+ if (screenWidth === 1280 && screenHeight === 1200) {+ addInferredSignal("defaultViewport1280x1200", 3);+ }}}@@ -276,6 +300,18 @@ export async function checkBotBlocking({botCategory: uaClassification.category,matchedPattern: uaClassification.matchedPattern,});+ } else {+ // Layer 1b: a browser release too old to have run the tracker that+ // reported the hit. Shares the ua_pattern layer so it lands in the+ // existing bot_category/matched_ua_pattern columns for auditing.+ const staleBrowser = classifyStaleBrowserVersion(userAgent);+ if (staleBrowser.isStale) {+ addDetection("Bot detected using ua-pattern", {+ layer: "ua_pattern",+ botCategory: "stale_version",+ matchedPattern: staleBrowser.matchedVersion,+ });+ }}// Layer 2: Header heuristic bot detectiondiff --git a/server/src/services/tracker/botBlocking/staleBrowserVersion.test.ts b/server/src/services/tracker/botBlocking/staleBrowserVersion.test.tsnew file mode 100644index 000000000..f62802530--- /dev/null+++ b/server/src/services/tracker/botBlocking/staleBrowserVersion.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from "vitest";+import { classifyStaleBrowserVersion } from "./staleBrowserVersion.js";++const androidChrome = (version: number) =>+ `Mozilla/5.0 (Linux; Android 8.0; SM-G930F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${version}.0.0.0 Mobile Safari/537.36`;++const desktopChrome = (version: number) =>+ `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${version}.0.0.0 Safari/537.36`;++describe("classifyStaleBrowserVersion", () => {+ it("flags the rotating old-Chrome fleet", () => {+ // The fleet spans Chrome 39-60 uniformly; spot-check both ends.+ expect(classifyStaleBrowserVersion(androidChrome(39))).toMatchObject({+ isStale: true,+ matchedVersion: "Chrome/39",+ majorVersion: 39,+ });+ expect(classifyStaleBrowserVersion(androidChrome(60))).toMatchObject({ isStale: true, majorVersion: 60 });+ });++ it("leaves current browsers alone", () => {+ expect(classifyStaleBrowserVersion(desktopChrome(151))).toMatchObject({ isStale: false });+ expect(classifyStaleBrowserVersion(androidChrome(150))).toMatchObject({ isStale: false });+ });++ it("leaves the cutoff itself and the older-but-real range alone", () => {+ // Versions in the 90-110 range do show engagement in production and stay+ // out of scope; 70 is the first supported major.+ expect(classifyStaleBrowserVersion(desktopChrome(70))).toMatchObject({ isStale: false });+ expect(classifyStaleBrowserVersion(desktopChrome(95))).toMatchObject({ isStale: false });+ expect(classifyStaleBrowserVersion(desktopChrome(69))).toMatchObject({ isStale: true });+ });++ it("ignores Android WebView, where an old Chrome major is genuine", () => {+ expect(+ classifyStaleBrowserVersion(+ "Mozilla/5.0 (Linux; Android 11; SM-A115M Build/RP1A; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/43.0.2357.121 Mobile Safari/537.36"+ )+ ).toMatchObject({ isStale: false });+ });++ it("ignores Safari, whose numbering tracks the OS rather than a release train", () => {+ expect(+ classifyStaleBrowserVersion(+ "Mozilla/5.0 (iPhone; CPU iPhone OS 15_8 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.6 Mobile/15E148 Safari/604.1"+ )+ ).toMatchObject({ isStale: false });+ });++ it("reads the version token of each supported release train", () => {+ expect(classifyStaleBrowserVersion("Mozilla/5.0 Firefox/52.0")).toMatchObject({+ isStale: true,+ matchedVersion: "Firefox/52",+ });+ expect(+ classifyStaleBrowserVersion("Mozilla/5.0 (iPhone) AppleWebKit/605.1.15 CriOS/48.0.2564.87 Mobile/15E148 Safari/604.1")+ ).toMatchObject({ isStale: true, matchedVersion: "CriOS/48" });+ expect(classifyStaleBrowserVersion("Mozilla/5.0 (Windows NT 10.0) Chrome/151.0.0.0 Safari/537.36 Edg/151.0.0.0")).toMatchObject(+ { isStale: false }+ );+ });++ it("ignores user-agents with no recognizable version token", () => {+ expect(classifyStaleBrowserVersion("okhttp/4.12.0")).toMatchObject({ isStale: false });+ expect(classifyStaleBrowserVersion("")).toMatchObject({ isStale: false });+ expect(classifyStaleBrowserVersion(undefined)).toMatchObject({ isStale: false });+ });+});diff --git a/server/src/services/tracker/botBlocking/staleBrowserVersion.ts b/server/src/services/tracker/botBlocking/staleBrowserVersion.tsnew file mode 100644index 000000000..b5953d579--- /dev/null+++ b/server/src/services/tracker/botBlocking/staleBrowserVersion.ts@@ -0,0 +1,79 @@+/**+ * Stale browser major version detection.+ *+ * A user-agent claiming a browser release that predates the cutoff below is,+ * in practice, a fabricated one. The fleets that motivated this rule rotate a+ * fixed list of old version strings to mint fresh identities: one of them spans+ * Chrome 39-60 x Android 5.0-8.0 uniformly (~400 identities per cell, ~1 event+ * each) across 40+ countries and thousands of sites, which defeats every+ * per-identity rate rule and stays under the cohort-uniformity rule's volume+ * gate by spreading thinly across sites.+ *+ * Measured over a full day of production traffic, Chrome/Edge/Firefox traffic+ * reporting a major version below the cutoff was 36,807 visitors producing+ * 1.04-1.18 events each, with 15 interaction events in total (0.035% of events,+ * against 6.1% for current-version traffic) and web vitals on 2.5% of pageviews+ * (against 26%). The population is not human, so this convicts.+ */++/**+ * Chrome 70 shipped 2018-10; Firefox 70 shipped 2019-10. Both auto-update+ * aggressively, and a browser this old could not run the tracker that reported+ * the hit. Deliberately far behind current (150+) so that genuinely old but+ * real installs β which cluster in the 90-110 range and do show engagement β+ * stay out of scope.+ */+const MIN_SUPPORTED_MAJOR_VERSION = 70;++/**+ * Version tokens whose numbering tracks a fast-moving, auto-updating release+ * train, so a low value is meaningful.+ *+ * Excluded on purpose:+ * - `Version/` (Safari) β its numbering is slow and tied to the OS, so real+ * devices legitimately sit many majors back.+ * - `SamsungBrowser`, `OPR` β separate numbering schemes on their own cadence.+ * - Android WebView (`; wv`) β an unupdated system WebView genuinely reports an+ * old Chrome major, and native app traffic is not browser-shaped anyway.+ */+const VERSION_TOKEN_PATTERN = /(?:EdgiOS|EdgA|Edge|Edg|CriOS|FxiOS|Firefox|Chrome)\/(\d{1,4})/;++const WEBVIEW_PATTERN = /\bwv\b|;\s?wv\)/;++export interface StaleBrowserClassification {+ isStale: boolean;+ /** e.g. "Chrome/40" β stored as the matched pattern for auditing. */+ matchedVersion: string | null;+ majorVersion: number | null;+}++const NOT_STALE: StaleBrowserClassification = { isStale: false, matchedVersion: null, majorVersion: null };++/**+ * Classify a user-agent by the major version of its browser release token.+ */+export function classifyStaleBrowserVersion(userAgent: string | null | undefined): StaleBrowserClassification {+ if (typeof userAgent !== "string" || userAgent.length === 0) {+ return NOT_STALE;+ }++ if (WEBVIEW_PATTERN.test(userAgent)) {+ return NOT_STALE;+ }++ const match = VERSION_TOKEN_PATTERN.exec(userAgent);+ if (!match) {+ return NOT_STALE;+ }++ const majorVersion = Number(match[1]);+ if (!Number.isFinite(majorVersion) || majorVersion <= 0 || majorVersion >= MIN_SUPPORTED_MAJOR_VERSION) {+ return NOT_STALE;+ }++ return {+ isStale: true,+ matchedVersion: `${match[0].split("/")[0]}/${majorVersion}`,+ majorVersion,+ };+}