Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

fix(tracker): give the Bot Signal contract one module instead of three hand-copies (#1116)

Goldflagb858276fc8a7
diff --git a/server/public/script-full.js b/server/public/script-full.js
index 13cd9b4d6..997c20488 100644
--- a/server/public/script-full.js
+++ b/server/public/script-full.js
@@ -470,10 +470,9 @@
}
};
- // botSignals.ts
+ // ../../../shared/src/botSignalContract.ts
var CLIENT_BOT_SIGNAL_MASKS = {
automationApi: 1 << 0,
- webdriver: 1 << 0,
zeroOuterDimensions: 1 << 1,
missingChrome: 1 << 2,
swiftShader: 1 << 3,
@@ -486,13 +485,60 @@
defaultViewport1280x1200: 1 << 10,
squareScreen: 1 << 11
};
+ var CLIENT_BOT_SIGNAL_NAMES = Object.keys(CLIENT_BOT_SIGNAL_MASKS);
+ var CLIENT_BOT_SIGNAL_WEIGHTS = {
+ automationApi: 3,
+ zeroOuterDimensions: 2,
+ missingChrome: 1,
+ swiftShader: 1,
+ emptyPlugins: 1,
+ defaultViewport800x600: 3,
+ defaultViewport1024x768: 3,
+ impossibleDimensions: 3,
+ outerDimensionsWeird: 2,
+ pluginApiAbsence: 0,
+ defaultViewport1280x1200: 3,
+ squareScreen: 3
+ };
+ var ALL_CLIENT_BOT_SIGNAL_BITS = CLIENT_BOT_SIGNAL_NAMES.reduce(
+ (mask, name) => mask | CLIENT_BOT_SIGNAL_MASKS[name],
+ 0
+ );
+ var STRONG_CLIENT_BOT_SIGNAL_BITS = CLIENT_BOT_SIGNAL_MASKS.automationApi | CLIENT_BOT_SIGNAL_MASKS.impossibleDimensions | CLIENT_BOT_SIGNAL_MASKS.defaultViewport800x600 | CLIENT_BOT_SIGNAL_MASKS.defaultViewport1024x768 | CLIENT_BOT_SIGNAL_MASKS.defaultViewport1280x1200 | CLIENT_BOT_SIGNAL_MASKS.squareScreen;
+ var MAX_CLIENT_BOT_SCORE = 10;
var MIN_PLAUSIBLE_SCREEN_DIMENSION = 200;
var MAX_PLAUSIBLE_SCREEN_DIMENSION = 8192;
+ var IMPLAUSIBLE_DESKTOP_VIEWPORTS = [
+ { width: 800, height: 600, signal: "defaultViewport800x600" },
+ { width: 1024, height: 768, signal: "defaultViewport1024x768" },
+ { width: 1280, height: 1200, signal: "defaultViewport1280x1200" }
+ ];
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;
}
+ function isDesktopUserAgent(userAgent) {
+ return /Windows NT|Macintosh|X11|Linux x86_64/.test(userAgent) && !/Mobile|Android|iPhone|iPad/.test(userAgent);
+ }
+ function getScreenDimensionSignals(width, height, userAgent) {
+ if (!isPlausibleScreenDimensions(width, height)) {
+ return ["impossibleDimensions"];
+ }
+ const signals = [];
+ if (width === height) {
+ signals.push("squareScreen");
+ }
+ if (isDesktopUserAgent(userAgent)) {
+ for (const viewport of IMPLAUSIBLE_DESKTOP_VIEWPORTS) {
+ if (width === viewport.width && height === viewport.height) {
+ signals.push(viewport.signal);
+ }
+ }
+ }
+ return signals;
+ }
+
+ // botSignals.ts
var cachedBotSignals = null;
- var MAX_BOT_SCORE = 10;
function getBotScore() {
return getBotSignals().score;
}
@@ -512,17 +558,17 @@
function calculateBotSignals() {
let score = 0;
let mask = 0;
- function addSignal(signalMask, weight) {
+ function addSignal(name) {
+ const signalMask = CLIENT_BOT_SIGNAL_MASKS[name];
if ((mask & signalMask) !== 0) {
return;
}
mask |= signalMask;
- score += weight;
+ score += CLIENT_BOT_SIGNAL_WEIGHTS[name];
}
try {
const userAgent = navigator.userAgent;
const isChromeLike = /Chrome\//.test(userAgent) && !/\bwv\b|; wv\)/.test(userAgent);
- const isDesktopUA = /Windows NT|Macintosh|X11|Linux x86_64/.test(userAgent) && !/Mobile|Android|iPhone|iPad/.test(userAgent);
const screenWidth = Number(window.screen?.width);
const screenHeight = Number(window.screen?.height);
const outerWidth = Number(window.outerWidth);
@@ -549,31 +595,20 @@
];
const hasAutomationGlobal = automationGlobalNames.some((name) => name in window || name in document);
if (navigator.webdriver === true || hasAutomationGlobal) {
- addSignal(CLIENT_BOT_SIGNAL_MASKS.automationApi, 3);
+ addSignal("automationApi");
}
if ((outerHeight === 0 || outerWidth === 0) && !isPrerendering()) {
- addSignal(CLIENT_BOT_SIGNAL_MASKS.zeroOuterDimensions, 2);
- }
- 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);
- }
- if (isDesktopUA && screenWidth === 1024 && screenHeight === 768) {
- addSignal(CLIENT_BOT_SIGNAL_MASKS.defaultViewport1024x768, 3);
+ addSignal("zeroOuterDimensions");
}
- if (isDesktopUA && screenWidth === 1280 && screenHeight === 1200) {
- addSignal(CLIENT_BOT_SIGNAL_MASKS.defaultViewport1280x1200, 3);
+ for (const signal of getScreenDimensionSignals(screenWidth, screenHeight, userAgent)) {
+ addSignal(signal);
}
if (Number.isFinite(outerWidth) && Number.isFinite(outerHeight) && Number.isFinite(innerWidth) && Number.isFinite(innerHeight) && outerWidth > 0 && outerHeight > 0 && innerWidth > 0 && innerHeight > 0 && (outerWidth + 8 < innerWidth || outerHeight + 8 < innerHeight)) {
- addSignal(CLIENT_BOT_SIGNAL_MASKS.outerDimensionsWeird, 2);
+ addSignal("outerDimensionsWeird");
}
let hasPluginOrApiAbsence = false;
if (!window.chrome && isChromeLike) {
- addSignal(CLIENT_BOT_SIGNAL_MASKS.missingChrome, 1);
+ addSignal("missingChrome");
hasPluginOrApiAbsence = true;
}
try {
@@ -597,7 +632,7 @@
} catch {
}
if (rendererParts.join(" ").toLowerCase().includes("swiftshader")) {
- addSignal(CLIENT_BOT_SIGNAL_MASKS.swiftShader, 1);
+ addSignal("swiftShader");
}
} finally {
releaseWebGlContext(canvas, gl);
@@ -606,16 +641,16 @@
} catch {
}
if ((!navigator.plugins || navigator.plugins.length === 0) && isChromeLike) {
- addSignal(CLIENT_BOT_SIGNAL_MASKS.emptyPlugins, 1);
+ addSignal("emptyPlugins");
hasPluginOrApiAbsence = true;
}
if (hasPluginOrApiAbsence) {
- addSignal(CLIENT_BOT_SIGNAL_MASKS.pluginApiAbsence, 0);
+ addSignal("pluginApiAbsence");
}
} catch (e2) {
}
return {
- score: Math.min(score, MAX_BOT_SCORE),
+ score: Math.min(score, MAX_CLIENT_BOT_SCORE),
mask
};
}
diff --git a/server/public/script.js b/server/public/script.js
index d61c42296..9450b8709 100644
--- a/server/public/script.js
+++ b/server/public/script.js
@@ -1 +1 @@
-"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()})();})();
+"use strict";(()=>{var $e=Object.defineProperty;var je=(r,e,t)=>e in r?$e(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var w=(r,e,t)=>je(r,typeof e!="symbol"?e+"":e,t);function Ke(r){if(r.startsWith("re:")){let c=r.slice(3);if(!c)throw new Error("Empty regex pattern");return new RegExp(c)}let t="__DOUBLE_ASTERISK_TOKEN__",n="__SINGLE_ASTERISK_TOKEN__",s=r.replace(/\*\*/g,t).replace(/\*/g,n).replace(/[.+?^${}()|[\]\\]/g,"\\$&");s=s.replace(new RegExp(`/${t}/`,"g"),"/(?:.+/)?"),s=s.replace(new RegExp(t,"g"),".*"),s=s.replace(/\//g,"\\/");let a=s.replace(new RegExp(n,"g"),"[^/]+");return new RegExp("^"+a+"$")}function V(r,e){for(let t of e)try{if(Ke(t).test(r))return t}catch(n){console.error(`Invalid pattern: ${t}`,n)}return null}function oe(r,e){let t=null;return(...n)=>{t&&clearTimeout(t),t=setTimeout(()=>r(...n),e)}}function le(r){try{let e=window.location.hostname,t=new URL(r).hostname;return t!==e&&t!==""}catch{return!1}}function C(r,e){if(!r)return e;try{let t=JSON.parse(r);return Array.isArray(e)&&!Array.isArray(t)?e:t}catch(t){return console.error("Error parsing JSON:",t),e}}var qe=2e3;function ce(){try{if(crypto?.randomUUID)return crypto.randomUUID()}catch{}return`${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function Je(r){let e=`${r}-visitor-id`;try{let t=localStorage.getItem(e);if(t)return t;let n=ce();return localStorage.setItem(e,n),n}catch{return ce()}}function Xe(r){try{return localStorage.getItem(`${r}-user-id`)||void 0}catch{return}}function Qe(r){return r.hash&&r.hash.startsWith("#/")?r.hash.substring(1):r.pathname}async function Ye(r,e,t,n){let i=new AbortController,s=window.setTimeout(()=>i.abort(),qe);try{let a=new URL(window.location.href),c=await fetch(`${r}/site/${e}/feature-flags/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"omit",signal:i.signal,body:JSON.stringify({anonymousId:n,identifiedUserId:Xe(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(!c.ok)return{enabled:!0,flags:{}};let u=await c.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 ue(r){let e=r.getAttribute("src");if(!e)return console.error("Script src attribute is missing"),null;let t=e.split("/script.js")[0];if(!t)return console.error("Please provide a valid analytics host"),null;let n=r.getAttribute("data-site-id")||r.getAttribute("site-id");if(!n)return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let i=r.getAttribute("data-namespace")||"rybbit",s=Je(i),a=C(r.getAttribute("data-skip-patterns"),[]),c=C(r.getAttribute("data-mask-patterns"),[]),u=C(r.getAttribute("data-replay-mask-text-selectors"),[]),d=r.getAttribute("data-debounce")?Math.max(0,parseInt(r.getAttribute("data-debounce"))):500,g=r.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(r.getAttribute("data-replay-batch-size"))):250,y=r.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(r.getAttribute("data-replay-batch-interval"))):5e3,T=r.getAttribute("data-replay-block-class")||void 0,h=r.getAttribute("data-replay-block-selector")||void 0,o=r.getAttribute("data-replay-ignore-class")||void 0,l=r.getAttribute("data-replay-ignore-selector")||void 0,p=r.getAttribute("data-replay-mask-text-class")||void 0,S=r.getAttribute("data-replay-mask-all-inputs"),E=S!==null?S!=="false":void 0,R=r.getAttribute("data-replay-mask-input-options"),Ue=R?C(R,{password:!0,email:!0}):void 0,ne=r.getAttribute("data-replay-collect-fonts"),He=ne!==null?ne!=="false":void 0,re=r.getAttribute("data-replay-sampling"),We=re?C(re,{}):void 0,ie=r.getAttribute("data-replay-slim-dom-options"),Ve=ie?C(ie,{}):void 0,se=r.getAttribute("data-replay-sample-rate"),Ge=se?Math.min(100,Math.max(0,parseInt(se,10))):void 0,ze=r.getAttribute("data-tag")||"",f={namespace:i,analyticsHost:t,siteId:n,visitorId:s,debounceDuration:d,sessionReplayBatchSize:g,sessionReplayBatchInterval:y,sessionReplayMaskTextSelectors:u,skipPatterns:a,maskPatterns:c,autoTrackPageview:!0,autoTrackSpa:!0,trackQuerystring:!0,trackOutbound:!0,enableWebVitals:!1,trackErrors:!1,enableSessionReplay:!1,trackButtonClicks:!1,trackCopy:!1,trackFormInteractions:!1,tag:ze,featureFlagsEnabled:!1,featureFlags:{},sessionReplayBlockClass:T,sessionReplayBlockSelector:h,sessionReplayIgnoreClass:o,sessionReplayIgnoreSelector:l,sessionReplayMaskTextClass:p,sessionReplayMaskAllInputs:E,sessionReplayMaskInputOptions:Ue,sessionReplayCollectFonts:He,sessionReplaySampling:We,sessionReplaySlimDOMOptions:Ve,sessionReplaySampleRate:Ge},A=f;try{let I=`${t}/site/tracking-config/${n}`,ae=await fetch(I,{method:"GET",credentials:"omit"});if(ae.ok){let m=await ae.json();A={...f,autoTrackPageview:m.trackInitialPageView??f.autoTrackPageview,autoTrackSpa:m.trackSpaNavigation??f.autoTrackSpa,trackQuerystring:m.trackUrlParams??f.trackQuerystring,trackOutbound:m.trackOutbound??f.trackOutbound,enableWebVitals:m.webVitals??f.enableWebVitals,trackErrors:m.trackErrors??f.trackErrors,enableSessionReplay:m.sessionReplay??f.enableSessionReplay,trackButtonClicks:m.trackButtonClicks??f.trackButtonClicks,trackCopy:m.trackCopy??f.trackCopy,trackFormInteractions:m.trackFormInteractions??f.trackFormInteractions,featureFlagsEnabled:m.featureFlagsEnabled===!0}}else console.warn("Failed to fetch tracking config from API, using defaults")}catch(I){console.warn("Error fetching tracking config:",I)}if(A.featureFlagsEnabled){let I=await Ye(t,n,i,s);A.featureFlagsEnabled=I.enabled,A.featureFlags=I.flags}return A}var de="rybbit-replay-sampled";function Ze(r){if(r>=100)return!0;if(r<=0)return!1;try{let e=sessionStorage.getItem(de);if(e!==null)return e==="1";let t=Math.random()*100<r;return sessionStorage.setItem(de,t?"1":"0"),t}catch{return Math.random()*100<r}}var M=class{constructor(e,t,n){this.isRecording=!1;this.eventBuffer=[];this.config=e,this.userId=t,this.sendBatch=n}async initialize(){if(!this.config.enableSessionReplay)return;let e=this.config.sessionReplaySampleRate;e!==void 0&&!Ze(e)||(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((e,t)=>{let n=document.createElement("script");n.src=`${this.config.analyticsHost}/replay.js`,n.async=!1,n.onload=()=>{e()},n.onerror=()=>t(new Error("Failed to load rrweb")),document.head.appendChild(n)})}startRecording(){if(!(this.isRecording||!window.rrweb||!this.config.enableSessionReplay))try{let e={mousemove:!1,mouseInteraction:{MouseUp:!1,MouseDown:!1,Click:!0,ContextMenu:!1,DblClick:!0,Focus:!0,Blur:!0,TouchStart:!1,TouchEnd:!1},scroll:500,input:"last",media:800},t={script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},n={emit:i=>{this.addEvent({type:i.type,data:i.data,timestamp:i.timestamp||Date.now()})},recordCanvas:!1,checkoutEveryNms:6e4,checkoutEveryNth:500,blockClass:this.config.sessionReplayBlockClass??"rr-block",blockSelector:this.config.sessionReplayBlockSelector??null,ignoreClass:this.config.sessionReplayIgnoreClass??"rr-ignore",ignoreSelector:this.config.sessionReplayIgnoreSelector??null,maskTextClass:this.config.sessionReplayMaskTextClass??"rr-mask",maskAllInputs:this.config.sessionReplayMaskAllInputs??!0,maskInputOptions:this.config.sessionReplayMaskInputOptions??{password:!0,email:!0},collectFonts:this.config.sessionReplayCollectFonts??!0,sampling:this.config.sessionReplaySampling??e,slimDOMOptions:this.config.sessionReplaySlimDOMOptions??t};this.config.sessionReplayMaskTextSelectors&&this.config.sessionReplayMaskTextSelectors.length>0&&(n.maskTextSelector=this.config.sessionReplayMaskTextSelectors.join(", ")),this.stopRecordingFn=window.rrweb.record(n),this.isRecording=!0,this.setupBatchTimer()}catch{}}stopRecording(){this.isRecording&&(this.stopRecordingFn&&this.stopRecordingFn(),this.isRecording=!1,this.clearBatchTimer(),this.eventBuffer.length>0&&this.flushEvents())}isActive(){return this.isRecording}addEvent(e){this.eventBuffer.push(e),this.eventBuffer.length>=this.config.sessionReplayBatchSize&&this.flushEvents()}setupBatchTimer(){this.clearBatchTimer(),this.batchTimer=window.setInterval(()=>{this.eventBuffer.length>0&&this.flushEvents()},this.config.sessionReplayBatchInterval)}clearBatchTimer(){this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0)}async flushEvents(){if(this.eventBuffer.length===0)return;let e=[...this.eventBuffer];this.eventBuffer=[];let t={userId:this.userId,events:e,metadata:{pageUrl:window.location.href,viewportWidth:screen.width,viewportHeight:screen.height,language:navigator.language}};try{await this.sendBatch(t)}catch{this.eventBuffer.unshift(...e)}}updateUserId(e){e!==this.userId&&(this.eventBuffer.length>0&&this.flushEvents(),this.userId=e)}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var b={automationApi:1,zeroOuterDimensions:2,missingChrome:4,swiftShader:8,emptyPlugins:16,defaultViewport800x600:32,defaultViewport1024x768:64,impossibleDimensions:128,outerDimensionsWeird:256,pluginApiAbsence:512,defaultViewport1280x1200:1024,squareScreen:2048},et=Object.keys(b),he={automationApi:3,zeroOuterDimensions:2,missingChrome:1,swiftShader:1,emptyPlugins:1,defaultViewport800x600:3,defaultViewport1024x768:3,impossibleDimensions:3,outerDimensionsWeird:2,pluginApiAbsence:0,defaultViewport1280x1200:3,squareScreen:3},ht=et.reduce((r,e)=>r|b[e],0),ft=b.automationApi|b.impossibleDimensions|b.defaultViewport800x600|b.defaultViewport1024x768|b.defaultViewport1280x1200|b.squareScreen,fe=10,pe=200,ge=8192,tt=[{width:800,height:600,signal:"defaultViewport800x600"},{width:1024,height:768,signal:"defaultViewport1024x768"},{width:1280,height:1200,signal:"defaultViewport1280x1200"}];function nt(r,e){return Number.isFinite(r)&&Number.isFinite(e)&&r>=pe&&e>=pe&&r<=ge&&e<=ge}function rt(r){return/Windows NT|Macintosh|X11|Linux x86_64/.test(r)&&!/Mobile|Android|iPhone|iPad/.test(r)}function me(r,e,t){if(!nt(r,e))return["impossibleDimensions"];let n=[];if(r===e&&n.push("squareScreen"),rt(t))for(let i of tt)r===i.width&&e===i.height&&n.push(i.signal);return n}var ye=null;function ve(){return Se().score}function ke(){return Se().mask}function we(){return document.prerendering===!0}function Se(){return we()?be():(ye??(ye=be()),ye)}function be(){let r=0,e=0;function t(n){let i=b[n];(e&i)===0&&(e|=i,r+=he[n])}try{let n=navigator.userAgent,i=/Chrome\//.test(n)&&!/\bwv\b|; wv\)/.test(n),s=Number(window.screen?.width),a=Number(window.screen?.height),c=Number(window.outerWidth),u=Number(window.outerHeight),d=Number(window.innerWidth),g=Number(window.innerHeight),T=["__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(o=>o in window||o in document);(navigator.webdriver===!0||T)&&t("automationApi"),(u===0||c===0)&&!we()&&t("zeroOuterDimensions");for(let o of me(s,a,n))t(o);Number.isFinite(c)&&Number.isFinite(u)&&Number.isFinite(d)&&Number.isFinite(g)&&c>0&&u>0&&d>0&&g>0&&(c+8<d||u+8<g)&&t("outerDimensionsWeird");let h=!1;!window.chrome&&i&&(t("missingChrome"),h=!0);try{let o=document.createElement("canvas"),l=o.getContext("webgl")||o.getContext("experimental-webgl");if(l)try{let p=[],S=l.getParameter(l.RENDERER);typeof S=="string"&&p.push(S);try{let E=l.getExtension("WEBGL_debug_renderer_info");if(E){let R=l.getParameter(E.UNMASKED_RENDERER_WEBGL);typeof R=="string"&&p.push(R)}}catch{}p.join(" ").toLowerCase().includes("swiftshader")&&t("swiftShader")}finally{it(o,l)}}catch{}(!navigator.plugins||navigator.plugins.length===0)&&i&&(t("emptyPlugins"),h=!0),h&&t("pluginApiAbsence")}catch{}return{score:Math.min(r,fe),mask:e}}function it(r,e){try{e.getExtension("WEBGL_lose_context")?.loseContext?.()}catch{}r.width=0,r.height=0}var st=2e3,x=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,n]of Object.entries(this.config.featureFlags||{}))e[t]=this.serializeFeatureFlagValue(n.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(),st);try{let n=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(!n.ok)return;let i=await n.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 M(this.config,this.customUserId||"",e=>this.sendSessionReplayBatch(e)),await this.sessionReplayRecorder.initialize()}catch(e){console.error("Failed to initialize session replay:",e)}}async sendSessionReplayBatch(e){try{await fetch(`${this.config.analyticsHost}/session-replay/record/${this.config.siteId}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e),mode:"cors",keepalive:!1})}catch(t){throw console.error("Failed to send session replay batch:",t),t}}createBasePayload(){let e=new URL(window.location.href),t=e.pathname;if(e.hash&&e.hash.startsWith("#/")&&(t=e.hash.substring(1)),V(t,this.config.skipPatterns))return null;let n=V(t,this.config.maskPatterns);n&&(t=n);let i={site_id:this.config.siteId,hostname:e.hostname,pathname:t,querystring:this.config.trackQuerystring?e.search:"",screenWidth:screen.width,screenHeight:screen.height,language:navigator.language,page_title:document.title,referrer:document.referrer,_bs:ve(),_bsm:ke()};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="",n={}){if(e==="custom_event"&&(!t||typeof t!="string")){console.error("Event name is required and must be a string for custom events");return}let i=this.createBasePayload();if(!i)return;let a={...i,type:e,event_name:t,properties:["custom_event","outbound","error","button_click","copy","form_submit","input_change"].includes(e)?JSON.stringify(n):void 0};this.sendTrackingData(a)}trackPageview(){this.track("pageview")}trackEvent(e,t={}){this.track("custom_event",e,t)}getFeatureFlag(e,t){let n=this.config.featureFlags?.[e];if(!n)return t;let i=`${e}:${n.version}:${this.serializeFeatureFlagValue(n.value)}`;return this.exposedFeatureFlags.has(i)||(this.exposedFeatureFlags.add(i),this.trackEvent("feature_flag_exposure",{key:e,value:this.serializeFeatureFlagValue(n.value),version:n.version,reason:n.reason})),n.value}getFeatureFlags(){return Object.fromEntries(Object.entries(this.config.featureFlags||{}).map(([e,t])=>[e,t.value]))}getFeatureFlagPayload(e,t){let n=this.config.featureFlags?.[e];return!n||n.payload===void 0?t:n.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="",n="_self"){this.track("outbound","",{url:e,text:t,target:n})}trackWebVitals(e){let t=this.createBasePayload();if(!t)return;let n={...t,type:"performance",event_name:"web-vitals",...e};this.sendTrackingData(n)}trackError(e,t={}){let n=e?.message||"";if(n.includes("ResizeObserver loop completed with undelivered notifications")||n.includes("ResizeObserver loop limit exceeded"))return;let i=window.location.origin,s=t.filename||"",a=e.stack||"";if(s)try{if(new URL(s).origin!==i)return}catch{}else if(a&&!a.includes(i))return;let u=[e.name||"Error",n,t.filename||"",t.lineno??"",t.colno??""].join("|"),d=Date.now(),g=6e4,y=this.errorDedupeCache.get(u);if(y&&d-y<g)return;this.errorDedupeCache.set(u,d);let T=10*6e4;if(d-this.errorDedupeLastCleanup>g){for(let[o,l]of this.errorDedupeCache.entries())d-l>T&&this.errorDedupeCache.delete(o);this.errorDedupeLastCleanup=d}let h={message:e.message?.substring(0,500)||"Unknown error",stack:a.substring(0,2e3)||""};if(s&&(h.fileName=s),t.lineno){let o=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;o&&o!==0&&(h.lineNumber=o)}if(t.colno){let o=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;o&&o!==0&&(h.columnNumber=o)}for(let o in t)!["lineno","colno"].includes(o)&&t[o]!==void 0&&(h[o]=t[o]);this.track("error",e.name||"Error",h)}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,n=!0){try{await fetch(`${this.config.analyticsHost}/identify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({site_id:this.config.siteId,user_id:e,traits:t,is_new_identify:n}),mode:"cors",keepalive:!0})}catch(i){console.error("Failed to send identify event:",i)}}clearUserId(){this.customUserId=null;try{localStorage.removeItem(`${this.config.namespace}-user-id`)}catch{}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 Le=-1,_=r=>{addEventListener("pageshow",(e=>{e.persisted&&(Le=e.timeStamp,r(e))}),!0)},v=(r,e,t,n)=>{let i,s;return a=>{e.value>=0&&(a||n)&&(s=e.value-(i??0),(s||i===void 0)&&(i=e.value,e.delta=s,e.rating=((c,u)=>c>u[1]?"poor":c>u[0]?"needs-improvement":"good")(e.value,t),r(e)))}},Q=r=>{requestAnimationFrame((()=>requestAnimationFrame((()=>r()))))},Y=()=>{let r=performance.getEntriesByType("navigation")[0];if(r&&r.responseStart>0&&r.responseStart<performance.now())return r},L=()=>Y()?.activationStart??0,k=(r,e=-1)=>{let t=Y(),n="navigate";return Le>=0?n="back-forward-cache":t&&(document.prerendering||L()>0?n="prerender":document.wasDiscarded?n="restore":t.type&&(n=t.type.replace(/_/g,"-"))),{name:r,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:n}},G=new WeakMap;function Z(r,e){return G.get(r)||G.set(r,new e),G.get(r)}var $=class{constructor(){w(this,"t");w(this,"i",0);w(this,"o",[])}h(e){if(e.hadRecentInput)return;let t=this.o[0],n=this.o.at(-1);this.i&&t&&n&&e.startTime-n.startTime<1e3&&e.startTime-t.startTime<5e3?(this.i+=e.value,this.o.push(e)):(this.i=e.value,this.o=[e]),this.t?.(e)}},F=(r,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(r)){let n=new PerformanceObserver((i=>{Promise.resolve().then((()=>{e(i.getEntries())}))}));return n.observe({type:r,buffered:!0,...t}),n}}catch{}},ee=r=>{let e=!1;return()=>{e||(r(),e=!0)}},P=-1,Fe=new Set,Ee=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,j=r=>{if(document.visibilityState==="hidden"){if(r.type==="visibilitychange")for(let e of Fe)e();isFinite(P)||(P=r.type==="visibilitychange"?r.timeStamp:0,removeEventListener("prerenderingchange",j,!0))}},N=()=>{if(P<0){let r=L();P=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter((t=>t.name==="hidden"&&t.startTime>r))[0]?.startTime)??Ee(),addEventListener("visibilitychange",j,!0),addEventListener("prerenderingchange",j,!0),_((()=>{setTimeout((()=>{P=Ee()}))}))}return{get firstHiddenTime(){return P},onHidden(r){Fe.add(r)}}},O=r=>{document.prerendering?addEventListener("prerenderingchange",(()=>r()),!0):r()},Te=[1800,3e3],te=(r,e={})=>{O((()=>{let t=N(),n,i=k("FCP"),s=F("paint",(a=>{for(let c of a)c.name==="first-contentful-paint"&&(s.disconnect(),c.startTime<t.firstHiddenTime&&(i.value=Math.max(c.startTime-L(),0),i.entries.push(c),n(!0)))}));s&&(n=v(r,i,Te,e.reportAllChanges),_((a=>{i=k("FCP"),n=v(r,i,Te,e.reportAllChanges),Q((()=>{i.value=performance.now()-a.timeStamp,n(!0)}))})))}))},Re=[.1,.25],Me=(r,e={})=>{let t=N();te(ee((()=>{let n,i=k("CLS",0),s=Z(e,$),a=u=>{for(let d of u)s.h(d);s.i>i.value&&(i.value=s.i,i.entries=s.o,n())},c=F("layout-shift",a);c&&(n=v(r,i,Re,e.reportAllChanges),t.onHidden((()=>{a(c.takeRecords()),n(!0)})),_((()=>{s.i=0,i=k("CLS",0),n=v(r,i,Re,e.reportAllChanges),Q((()=>n()))})),setTimeout(n))})))},xe=0,z=1/0,B=0,at=r=>{for(let e of r)e.interactionId&&(z=Math.min(z,e.interactionId),B=Math.max(B,e.interactionId),xe=B?(B-z)/7+1:0)},K,Ce=()=>K?xe:performance.interactionCount??0,ot=()=>{"interactionCount"in performance||K||(K=F("event",at,{type:"event",buffered:!0,durationThreshold:0}))},Ie=0,q=class{constructor(){w(this,"u",[]);w(this,"l",new Map);w(this,"m");w(this,"p")}v(){Ie=Ce(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor((Ce()-Ie)/50));return this.u[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!=="first-input")return;let t=this.u.at(-1),n=this.l.get(e.interactionId);if(n||this.u.length<10||e.duration>t.P){if(n?e.duration>n.P?(n.entries=[e],n.P=e.duration):e.duration===n.P&&e.startTime===n.entries[0].startTime&&n.entries.push(e):(n={id:e.interactionId,entries:[e],P:e.duration},this.l.set(n.id,n),this.u.push(n)),this.u.sort(((i,s)=>s.P-i.P)),this.u.length>10){let i=this.u.splice(10);for(let s of i)this.l.delete(s.id)}this.p?.(n)}}},Be=r=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?r():(r=ee(r),addEventListener("visibilitychange",r,{once:!0,capture:!0}),e((()=>{r(),removeEventListener("visibilitychange",r,{capture:!0})})))},Pe=[200,500],Ne=(r,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let t=N();O((()=>{ot();let n,i=k("INP"),s=Z(e,q),a=u=>{Be((()=>{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,n())}))},c=F("event",a,{durationThreshold:e.durationThreshold??40});n=v(r,i,Pe,e.reportAllChanges),c&&(c.observe({type:"first-input",buffered:!0}),t.onHidden((()=>{a(c.takeRecords()),n(!0)})),_((()=>{s.v(),i=k("INP"),n=v(r,i,Pe,e.reportAllChanges)})))}))},J=class{constructor(){w(this,"m")}h(e){this.m?.(e)}},_e=[2500,4e3],Oe=(r,e={})=>{O((()=>{let t=N(),n,i=k("LCP"),s=Z(e,J),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-L(),0),i.entries=[d],n())},c=F("largest-contentful-paint",a);if(c){n=v(r,i,_e,e.reportAllChanges);let u=ee((()=>{a(c.takeRecords()),c.disconnect(),n(!0)})),d=g=>{g.isTrusted&&(Be(u),removeEventListener(g.type,d,{capture:!0}))};for(let g of["keydown","click","visibilitychange"])addEventListener(g,d,{capture:!0});_((g=>{i=k("LCP"),n=v(r,i,_e,e.reportAllChanges),Q((()=>{i.value=performance.now()-g.timeStamp,n(!0)}))}))}}))},Ae=[800,1800],X=r=>{document.prerendering?O((()=>X(r))):document.readyState!=="complete"?addEventListener("load",(()=>X(r)),!0):setTimeout(r)},De=(r,e={})=>{let t=k("TTFB"),n=v(r,t,Ae,e.reportAllChanges);X((()=>{let i=Y();i&&(t.value=Math.max(i.responseStart-L(),0),t.entries=[i],n(!0),_((()=>{t=k("TTFB",0),n=v(r,t,Ae,e.reportAllChanges),n(!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{Oe(this.collectMetric.bind(this)),Me(this.collectMetric.bind(this)),Ne(this.collectMetric.bind(this)),te(this.collectMetric.bind(this)),De(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 lt=1e3,U=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,n=0;for(;t&&n<3;){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return!0;t=t.parentElement,n++}return!1}trackButtonClick(e){let t=this.findButton(e);if(!t||t.hasAttribute("data-rybbit-event"))return;let n=Date.now(),i=this.lastClickAt.get(t);if(i!==void 0&&n-i<lt)return;this.lastClickAt.set(t,n);let s={text:this.getElementText(t),...this.extractDataAttributes(t)};this.tracker.trackButtonClick(s)}extractDataAttributes(e){let t={};for(let n of e.attributes)if(n.name.startsWith("data-rybbit-prop-")){let i=n.name.replace("data-rybbit-prop-","");t[i]=n.value}return t}findButton(e){if(e.tagName==="BUTTON"||e.getAttribute("role")==="button")return e;if(e.tagName==="INPUT"){let i=e.type?.toLowerCase();if(i==="submit"||i==="button")return e}let t=e.parentElement,n=0;for(;t&&n<3;){if(t.tagName==="BUTTON"||t.getAttribute("role")==="button")return t;t=t.parentElement,n++}return null}getElementText(e){let t=e.textContent?.trim().substring(0,100);if(t)return t;let n=e.getAttribute("aria-label")?.trim().substring(0,100);if(n)return n;if(e.tagName==="INPUT"){let s=e.value?.trim().substring(0,100);if(s)return s}let i=e.getAttribute("title")?.trim().substring(0,100);if(i)return i}cleanup(){document.removeEventListener("click",this.handleClick.bind(this),!0)}};var H=class{constructor(e){this.tracker=e}initialize(){document.addEventListener("copy",this.handleCopy.bind(this))}handleCopy(){let e=window.getSelection();if(!e||e.isCollapsed)return;let t=e.toString(),n=t.length;if(n===0)return;let i=e.anchorNode,s=i instanceof HTMLElement?i:i?.parentElement;if(!s)return;let a={text:t.substring(0,500),...n>500&&{textLength:n},sourceElement:s.tagName.toLowerCase()};this.tracker.trackCopy(a)}cleanup(){document.removeEventListener("copy",this.handleCopy.bind(this))}};var W=class{constructor(e,t){this.tracker=e,this.config=t,this.boundHandleSubmit=this.handleSubmit.bind(this),this.boundHandleChange=this.handleChange.bind(this)}initialize(){document.addEventListener("submit",this.boundHandleSubmit,!0),document.addEventListener("change",this.boundHandleChange,!0)}cleanup(){document.removeEventListener("submit",this.boundHandleSubmit,!0),document.removeEventListener("change",this.boundHandleChange,!0)}handleSubmit(e){let t=e.target;if(t.tagName!=="FORM")return;let n={formId:t.id||"",formName:t.name||"",formAction:t.action||"",method:(t.method||"get").toUpperCase(),fieldCount:t.elements.length,ariaLabel:t.getAttribute("aria-label")||void 0,...this.extractDataAttributes(t)};this.tracker.trackFormSubmit(n)}handleChange(e){let t=e.target,n=t.tagName.toUpperCase();if(!["INPUT","SELECT","TEXTAREA"].includes(n)||t.disabled||t.readOnly)return;if(n==="INPUT"){let a=t.type?.toLowerCase();if(a==="hidden"||a==="password")return}let i=t.name||t.id||t.getAttribute("aria-label")||t.placeholder||"",s={element:n.toLowerCase(),inputType:n==="INPUT"?t.type?.toLowerCase():void 0,inputName:i,formId:t.form?.id||void 0,formName:t.form?.name||void 0,...this.extractDataAttributes(t)};this.tracker.trackInputChange(s)}extractDataAttributes(e){let t={};for(let n of e.attributes)if(n.name.startsWith("data-rybbit-prop-")){let i=n.name.replace("data-rybbit-prop-","");t[i]=n.value}return t}};(async function(){let r=document.currentScript;if(!r){console.error("Could not find current script tag");return}let e=r.getAttribute("data-namespace")||"rybbit",t=`disable-${e}`;if(window.__RYBBIT_OPTOUT__||localStorage.getItem(t)!==null){window[e]={pageview:()=>{},event:()=>{},error:()=>{},trackOutbound:()=>{},identify:()=>{},setTraits:()=>{},clearUserId:()=>{},getUserId:()=>null,flag:(o,l)=>l,flagPayload:(o,l)=>l,flags:()=>({}),flagPayloads:()=>({}),onReady:()=>{},startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let n=[],i=o=>(...l)=>{n.push([o,l])};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,l)=>l,flagPayload:(o,l)=>l,flags:()=>({}),flagPayloads:()=>({}),onReady:i("onReady"),startSessionReplay:i("startSessionReplay"),stopSessionReplay:i("stopSessionReplay"),isSessionReplayActive:()=>!1};let s=await ue(r);if(!s)return;let a=new x(s);s.enableWebVitals&&new D(l=>{a.trackWebVitals(l)}).initialize();let c=null,u=null,d=null;s.trackButtonClicks&&(c=new U(a,s),c.initialize()),s.trackCopy&&(u=new H(a),u.initialize()),s.trackFormInteractions&&(d=new W(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 l=o.reason instanceof Error?o.reason:new Error(String(o.reason));a.trackError(l,{type:"unhandledrejection"})}));let g=()=>a.trackPageview(),y=s.debounceDuration>0?oe(g,s.debounceDuration):g;function T(){if(document.addEventListener("click",function(o){let l=o.target;for(;l&&l!==document.documentElement;){if(l.hasAttribute("data-rybbit-event")){let p=l.getAttribute("data-rybbit-event");if(p){let S={};for(let E of l.attributes)if(E.name.startsWith("data-rybbit-prop-")){let R=E.name.replace("data-rybbit-prop-","");S[R]=E.value}a.trackEvent(p,S)}break}l=l.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,l=history.replaceState;history.pushState=function(...p){o.apply(this,p),y(),a.onPageChange()},history.replaceState=function(...p){l.apply(this,p),y(),a.onPageChange()},window.addEventListener("popstate",()=>{y(),a.onPageChange()}),window.addEventListener("hashchange",()=>{y(),a.onPageChange()})}}window[s.namespace]={pageview:()=>a.trackPageview(),event:(o,l={})=>a.trackEvent(o,l),error:(o,l={})=>a.trackError(o,l),trackOutbound:(o,l="",p="_self")=>a.trackOutbound(o,l,p),identify:(o,l)=>a.identify(o,l),setTraits:o=>a.setTraits(o),clearUserId:()=>a.clearUserId(),getUserId:()=>a.getUserId(),flag:(o,l)=>a.getFeatureFlag(o,l),flagPayload:(o,l)=>a.getFeatureFlagPayload(o,l),flags:()=>a.getFeatureFlags(),flagPayloads:()=>a.getFeatureFlagPayloads(),onReady:o=>o(window[s.namespace]),startSessionReplay:()=>a.startSessionReplay(),stopSessionReplay:()=>a.stopSessionReplay(),isSessionReplayActive:()=>a.isSessionReplayActive()};let h=window[s.namespace];for(let[o,l]of n)h[o](...l);T(),window.addEventListener("beforeunload",()=>{c?.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.ts
index 0bbd35552..3f54e021d 100644
--- a/server/src/analytics-script/botSignals.test.ts
+++ b/server/src/analytics-script/botSignals.test.ts
@@ -1,5 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { CLIENT_BOT_SIGNAL_MASKS, getBotScore, getBotSignalMask, resetBotScoreCacheForTests } from "./botSignals.js";
+import { CLIENT_BOT_SIGNAL_MASKS } from "@rybbit/shared";
+import { getBotScore, getBotSignalMask, resetBotScoreCacheForTests } from "./botSignals.js";
function setNavigatorProperty(name: string, value: unknown) {
Object.defineProperty(navigator, name, {
diff --git a/server/src/analytics-script/botSignals.ts b/server/src/analytics-script/botSignals.ts
index c8c9ae5c1..65d91b234 100644
--- a/server/src/analytics-script/botSignals.ts
+++ b/server/src/analytics-script/botSignals.ts
@@ -4,44 +4,21 @@
* Checks browser environment characteristics that distinguish real browsers
* from headless/automated ones. Returns a single weighted integer score.
* The tracker sends the score plus a compact signal bitmask for aggregate diagnostics.
+ *
+ * The bit layout, the weights and the screen-geometry rules are the wire
+ * contract with the server and live in @rybbit/shared/botSignalContract, which
+ * both sides import. Nothing about the mask is defined here.
*/
-export const CLIENT_BOT_SIGNAL_MASKS = {
- automationApi: 1 << 0,
- webdriver: 1 << 0,
- zeroOuterDimensions: 1 << 1,
- missingChrome: 1 << 2,
- swiftShader: 1 << 3,
- emptyPlugins: 1 << 4,
- defaultViewport800x600: 1 << 5,
- defaultViewport1024x768: 1 << 6,
- impossibleDimensions: 1 << 7,
- 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
- );
-}
+// Imported from the contract module rather than the package barrel: this is a
+// browser bundle, and the barrel would drag unrelated shared runtime code
+// (the scope tables) onto every tracked page.
+import {
+ CLIENT_BOT_SIGNAL_MASKS,
+ CLIENT_BOT_SIGNAL_WEIGHTS,
+ ClientBotSignalName,
+ getScreenDimensionSignals,
+ MAX_CLIENT_BOT_SCORE,
+} from "@rybbit/shared/dist/botSignalContract.js";
interface BotSignalResult {
score: number;
@@ -50,8 +27,6 @@ interface BotSignalResult {
let cachedBotSignals: BotSignalResult | null = null;
-const MAX_BOT_SCORE = 10;
-
export function getBotScore(): number {
return getBotSignals().score;
}
@@ -79,19 +54,18 @@ function calculateBotSignals(): BotSignalResult {
let score = 0;
let mask = 0;
- function addSignal(signalMask: number, weight: number) {
+ function addSignal(name: ClientBotSignalName) {
+ const signalMask = CLIENT_BOT_SIGNAL_MASKS[name];
if ((mask & signalMask) !== 0) {
return;
}
mask |= signalMask;
- score += weight;
+ score += CLIENT_BOT_SIGNAL_WEIGHTS[name];
}
try {
const userAgent = navigator.userAgent;
const isChromeLike = /Chrome\//.test(userAgent) && !/\bwv\b|; wv\)/.test(userAgent);
- const isDesktopUA =
- /Windows NT|Macintosh|X11|Linux x86_64/.test(userAgent) && !/Mobile|Android|iPhone|iPad/.test(userAgent);
const screenWidth = Number(window.screen?.width);
const screenHeight = Number(window.screen?.height);
const outerWidth = Number(window.outerWidth);
@@ -120,47 +94,24 @@ function calculateBotSignals(): BotSignalResult {
];
const hasAutomationGlobal = automationGlobalNames.some(name => name in window || name in document);
if ((navigator as any).webdriver === true || hasAutomationGlobal) {
- addSignal(CLIENT_BOT_SIGNAL_MASKS.automationApi, 3);
+ addSignal("automationApi");
}
// 2. Zero outer dimensions β€” common in headless/browserless environments.
// Skipped while prerendering: Chrome legitimately reports 0 there.
if ((outerHeight === 0 || outerWidth === 0) && !isPrerendering()) {
- addSignal(CLIENT_BOT_SIGNAL_MASKS.zeroOuterDimensions, 2);
+ addSignal("zeroOuterDimensions");
}
- // 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 in
- // one week from a single crawler, against a few hundred from everything
- // else combined).
- if (isDesktopUA && screenWidth === 800 && screenHeight === 600) {
- addSignal(CLIENT_BOT_SIGNAL_MASKS.defaultViewport800x600, 3);
- }
- if (isDesktopUA && screenWidth === 1024 && screenHeight === 768) {
- addSignal(CLIENT_BOT_SIGNAL_MASKS.defaultViewport1024x768, 3);
- }
- if (isDesktopUA && screenWidth === 1280 && screenHeight === 1200) {
- addSignal(CLIENT_BOT_SIGNAL_MASKS.defaultViewport1280x1200, 3);
+ // 3. Screen geometry β€” displays outside the range any real one reports,
+ // square screens, and default automation viewports. The rules are the
+ // contract's, so the server derives the same signals from the reported
+ // dimensions regardless of which tracker version sent them.
+ for (const signal of getScreenDimensionSignals(screenWidth, screenHeight, userAgent)) {
+ addSignal(signal);
}
- // 5. Outer dimensions smaller than inner dimensions should not happen in normal desktop browsers
+ // 4. Outer dimensions smaller than inner dimensions should not happen in normal desktop browsers
if (
Number.isFinite(outerWidth) &&
Number.isFinite(outerHeight) &&
@@ -172,18 +123,18 @@ function calculateBotSignals(): BotSignalResult {
innerHeight > 0 &&
(outerWidth + 8 < innerWidth || outerHeight + 8 < innerHeight)
) {
- addSignal(CLIENT_BOT_SIGNAL_MASKS.outerDimensionsWeird, 2);
+ addSignal("outerDimensionsWeird");
}
- // 6. Missing window.chrome on a Chrome UA β€” real Chrome usually exposes this object
+ // 5. Missing window.chrome on a Chrome UA β€” real Chrome usually exposes this object
// Only flag for non-WebView Chrome UAs; Android WebView doesn't expose window.chrome
let hasPluginOrApiAbsence = false;
if (!(window as any).chrome && isChromeLike) {
- addSignal(CLIENT_BOT_SIGNAL_MASKS.missingChrome, 1);
+ addSignal("missingChrome");
hasPluginOrApiAbsence = true;
}
- // 7. WebGL renderer check β€” headless/containerized Chrome often uses Google SwiftShader
+ // 6. WebGL renderer check β€” headless/containerized Chrome often uses Google SwiftShader
try {
const canvas = document.createElement("canvas");
const gl = (canvas.getContext("webgl") || canvas.getContext("experimental-webgl")) as WebGLRenderingContext | null;
@@ -207,7 +158,7 @@ function calculateBotSignals(): BotSignalResult {
// Firefox Privacy
}
if (rendererParts.join(" ").toLowerCase().includes("swiftshader")) {
- addSignal(CLIENT_BOT_SIGNAL_MASKS.swiftShader, 1);
+ addSignal("swiftShader");
}
} finally {
releaseWebGlContext(canvas, gl);
@@ -217,21 +168,21 @@ function calculateBotSignals(): BotSignalResult {
// WebGL not available β€” not a bot signal by itself
}
- // 8. No plugins β€” weak supporting signal for Chrome-like UAs only
+ // 7. No plugins β€” weak supporting signal for Chrome-like UAs only
if ((!navigator.plugins || navigator.plugins.length === 0) && isChromeLike) {
- addSignal(CLIENT_BOT_SIGNAL_MASKS.emptyPlugins, 1);
+ addSignal("emptyPlugins");
hasPluginOrApiAbsence = true;
}
if (hasPluginOrApiAbsence) {
- addSignal(CLIENT_BOT_SIGNAL_MASKS.pluginApiAbsence, 0);
+ addSignal("pluginApiAbsence");
}
} catch (e) {
// If any top-level access fails, return whatever we've accumulated
}
return {
- score: Math.min(score, MAX_BOT_SCORE),
+ score: Math.min(score, MAX_CLIENT_BOT_SCORE),
mask,
};
}
diff --git a/server/src/analytics-script/build.js b/server/src/analytics-script/build.js
index 7b38ccf31..4c5d354f9 100644
--- a/server/src/analytics-script/build.js
+++ b/server/src/analytics-script/build.js
@@ -1,6 +1,6 @@
import { build } from "esbuild";
import { existsSync, mkdirSync } from "fs";
-import { dirname } from "path";
+import { dirname, resolve } from "path";
import { fileURLToPath } from "url";
const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -11,6 +11,15 @@ if (!existsSync(publicDir)) {
mkdirSync(publicDir, { recursive: true });
}
+// The tracker shares the Bot Signal contract with the server through
+// @rybbit/shared, which is published as CommonJS. Resolving it normally would
+// bundle the module unshaken, so point esbuild at the TypeScript source and let
+// it tree-shake down to the handful of values the browser actually uses. The
+// alias names the contract module, not the package barrel, so nothing else in
+// @rybbit/shared can ever reach a tracked page.
+const botSignalContractSource = resolve(__dirname, "../../../shared/src/botSignalContract.ts");
+const bundleContractFromSource = { "@rybbit/shared/dist/botSignalContract.js": botSignalContractSource };
+
async function buildScript() {
try {
// Build the full version
@@ -23,6 +32,7 @@ async function buildScript() {
minify: false,
sourcemap: false,
platform: "browser",
+ alias: bundleContractFromSource,
});
console.log("βœ… Built script-full.js");
@@ -37,6 +47,7 @@ async function buildScript() {
minify: true,
sourcemap: false,
platform: "browser",
+ alias: bundleContractFromSource,
});
console.log("βœ… Built script.js (minified)");
diff --git a/server/src/services/tracker/botBlocking/anomalyScorer.test.ts b/server/src/services/tracker/botBlocking/anomalyScorer.test.ts
index 0a867263e..13f487c82 100644
--- a/server/src/services/tracker/botBlocking/anomalyScorer.test.ts
+++ b/server/src/services/tracker/botBlocking/anomalyScorer.test.ts
@@ -16,7 +16,7 @@ import {
} from "./anomalyScorer.js";
const baseInput = {
- siteId: "site_123",
+ siteId: 123,
ipAddress: "203.0.113.10",
userAgent: "Mozilla/5.0 Chrome/120 Safari/537.36",
hostname: "example.com",
diff --git a/server/src/services/tracker/botBlocking/anomalyScorer.ts b/server/src/services/tracker/botBlocking/anomalyScorer.ts
index b48c9c697..aca673e48 100644
--- a/server/src/services/tracker/botBlocking/anomalyScorer.ts
+++ b/server/src/services/tracker/botBlocking/anomalyScorer.ts
@@ -75,7 +75,13 @@ export interface AnomalyCounters {
const INTERACTION_EVENT_TYPES = new Set(["button_click", "input_change", "copy"]);
export interface AnomalyInput {
- siteId: string;
+ /**
+ * Numeric Site id. Counters are namespaced by it, so it must be the id the
+ * rest of ingestion uses β€” a Site addressed by its text id in one request and
+ * its legacy numeric id in another would otherwise occupy two namespaces and
+ * each would see half the traffic.
+ */
+ siteId: number;
ipAddress: string;
userAgent: string;
hostname?: string;
diff --git a/server/src/services/tracker/botBlocking/botDetectionStats.ts b/server/src/services/tracker/botBlocking/botDetectionStats.ts
index f64f5396a..09119f5d1 100644
--- a/server/src/services/tracker/botBlocking/botDetectionStats.ts
+++ b/server/src/services/tracker/botBlocking/botDetectionStats.ts
@@ -1,3 +1,9 @@
+import {
+ ALL_CLIENT_BOT_SIGNAL_BITS,
+ CLIENT_BOT_SIGNAL_MASKS,
+ CLIENT_BOT_SIGNAL_NAMES,
+ ClientBotSignalName,
+} from "@rybbit/shared";
import { redis } from "../../../db/redis/redis.js";
import { logger } from "../../../lib/logger/logger.js";
@@ -38,41 +44,16 @@ const clientBotScoreHistogram = {
score3Plus: 0,
};
-const CLIENT_BOT_SIGNAL_COMPONENTS = [
- ["automationApi", 1 << 0],
- ["zeroOuterDimensions", 1 << 1],
- ["missingChrome", 1 << 2],
- ["swiftShader", 1 << 3],
- ["emptyPlugins", 1 << 4],
- ["defaultViewport800x600", 1 << 5],
- ["defaultViewport1024x768", 1 << 6],
- ["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];
-type ClientBotSignalTotal = ClientBotSignalComponent | "missingMask" | "unknownMaskBits";
-
-const KNOWN_CLIENT_BOT_SIGNAL_MASK = CLIENT_BOT_SIGNAL_COMPONENTS.reduce((mask, [, bit]) => mask | bit, 0);
+// One counter per signal the Bot Signal contract defines, plus two for masks we
+// cannot label: absent, and carrying bits from a contract newer than this
+// build. Labels are derived from the contract rather than transcribed, so a new
+// signal starts being counted the moment it is added there.
+type ClientBotSignalTotal = ClientBotSignalName | "missingMask" | "unknownMaskBits";
const clientBotSignalTotals: Record<ClientBotSignalTotal, number> = {
missingMask: 0,
- automationApi: 0,
- zeroOuterDimensions: 0,
- missingChrome: 0,
- swiftShader: 0,
- emptyPlugins: 0,
- defaultViewport800x600: 0,
- defaultViewport1024x768: 0,
- impossibleDimensions: 0,
- outerDimensionsWeird: 0,
- pluginApiAbsence: 0,
- defaultViewport1280x1200: 0,
- squareScreen: 0,
unknownMaskBits: 0,
+ ...(Object.fromEntries(CLIENT_BOT_SIGNAL_NAMES.map(name => [name, 0])) as Record<ClientBotSignalName, number>),
};
// Canonical field sets, captured once, used to round-trip counters through the
@@ -108,13 +89,13 @@ export function recordBotBlockingRequest(clientBotScore: number | undefined, cli
if (typeof clientBotSignalMask !== "number" || !Number.isFinite(clientBotSignalMask)) {
clientBotSignalTotals.missingMask++;
} else {
- for (const [component, bit] of CLIENT_BOT_SIGNAL_COMPONENTS) {
- if ((clientBotSignalMask & bit) !== 0) {
- clientBotSignalTotals[component]++;
+ for (const name of CLIENT_BOT_SIGNAL_NAMES) {
+ if ((clientBotSignalMask & CLIENT_BOT_SIGNAL_MASKS[name]) !== 0) {
+ clientBotSignalTotals[name]++;
}
}
- if ((clientBotSignalMask & ~KNOWN_CLIENT_BOT_SIGNAL_MASK) !== 0) {
+ if ((clientBotSignalMask & ~ALL_CLIENT_BOT_SIGNAL_BITS) !== 0) {
clientBotSignalTotals.unknownMaskBits++;
}
}
diff --git a/server/src/services/tracker/botBlocking/botSignalContract.test.ts b/server/src/services/tracker/botBlocking/botSignalContract.test.ts
new file mode 100644
index 000000000..10cd76361
--- /dev/null
+++ b/server/src/services/tracker/botBlocking/botSignalContract.test.ts
@@ -0,0 +1,128 @@
+import {
+ ALL_CLIENT_BOT_SIGNAL_BITS,
+ CLIENT_BOT_SIGNAL_MASKS,
+ CLIENT_BOT_SIGNAL_NAMES,
+ CLIENT_BOT_SIGNAL_WEIGHTS,
+ getClientBotSignalNames,
+ getScreenDimensionSignals,
+ IMPLAUSIBLE_DESKTOP_VIEWPORTS,
+ MAX_PLAUSIBLE_SCREEN_DIMENSION,
+ MIN_PLAUSIBLE_SCREEN_DIMENSION,
+ scoreFromMask,
+ STRONG_CLIENT_BOT_SIGNAL_BITS,
+} from "@rybbit/shared";
+import { describe, expect, it } from "vitest";
+
+const DESKTOP_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0 Safari/537.36";
+const MOBILE_UA = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) Mobile/15E148 Safari/604.1";
+
+describe("the Bot Signal mask", () => {
+ it("gives every signal its own single bit", () => {
+ const bits = CLIENT_BOT_SIGNAL_NAMES.map(name => CLIENT_BOT_SIGNAL_MASKS[name]);
+
+ for (const bit of bits) {
+ expect(bit, "each signal occupies exactly one bit").toBeGreaterThan(0);
+ expect(bit & (bit - 1), `${bit} is a power of two`).toBe(0);
+ }
+ expect(new Set(bits).size, "no two signals share a bit").toBe(bits.length);
+ });
+
+ it("weights every signal it defines", () => {
+ for (const name of CLIENT_BOT_SIGNAL_NAMES) {
+ expect(CLIENT_BOT_SIGNAL_WEIGHTS[name], `${name} has a weight`).toBeTypeOf("number");
+ }
+ expect(Object.keys(CLIENT_BOT_SIGNAL_WEIGHTS).sort()).toEqual([...CLIENT_BOT_SIGNAL_NAMES].sort());
+ });
+
+ // The bound the ingest schema applies to `_bsm`. A hard-coded bound is how the
+ // 12th bit (squareScreen = 2048) came to fail validation and drop whole
+ // events, so it has to be the union of whatever the table currently declares.
+ it("bounds itself by the union of every declared bit", () => {
+ const union = CLIENT_BOT_SIGNAL_NAMES.reduce((mask, name) => mask | CLIENT_BOT_SIGNAL_MASKS[name], 0);
+
+ expect(ALL_CLIENT_BOT_SIGNAL_BITS).toBe(union);
+ expect(ALL_CLIENT_BOT_SIGNAL_BITS & CLIENT_BOT_SIGNAL_MASKS.squareScreen).toBe(
+ CLIENT_BOT_SIGNAL_MASKS.squareScreen
+ );
+ });
+
+ it("only convicts on signals it also defines", () => {
+ expect(STRONG_CLIENT_BOT_SIGNAL_BITS & ~ALL_CLIENT_BOT_SIGNAL_BITS).toBe(0);
+ expect(STRONG_CLIENT_BOT_SIGNAL_BITS).toBeGreaterThan(0);
+ });
+});
+
+describe("reading a mask", () => {
+ it("names the signals a mask carries and ignores bits it does not define", () => {
+ const mask = CLIENT_BOT_SIGNAL_MASKS.automationApi | CLIENT_BOT_SIGNAL_MASKS.squareScreen | (1 << 30);
+
+ expect(getClientBotSignalNames(mask)).toEqual(["automationApi", "squareScreen"]);
+ });
+
+ it("scores a mask as the sum of its signal weights", () => {
+ const mask = CLIENT_BOT_SIGNAL_MASKS.automationApi | CLIENT_BOT_SIGNAL_MASKS.emptyPlugins;
+
+ expect(scoreFromMask(mask)).toBe(
+ CLIENT_BOT_SIGNAL_WEIGHTS.automationApi + CLIENT_BOT_SIGNAL_WEIGHTS.emptyPlugins
+ );
+ expect(scoreFromMask(0)).toBe(0);
+ expect(scoreFromMask(1 << 30), "undefined bits carry no weight").toBe(0);
+ });
+});
+
+describe("the screen-geometry rules", () => {
+ it("leaves real displays alone", () => {
+ for (const [width, height] of [
+ [1920, 1080],
+ [MIN_PLAUSIBLE_SCREEN_DIMENSION, 320],
+ [7680, 4320],
+ [MAX_PLAUSIBLE_SCREEN_DIMENSION, 4320],
+ ]) {
+ expect(getScreenDimensionSignals(width, height, DESKTOP_UA), `${width}x${height}`).toEqual([]);
+ }
+ });
+
+ it("flags displays no real one reports, and says nothing else about them", () => {
+ for (const [width, height] of [
+ [1, 1],
+ [16384, 16384],
+ [1920, 10000],
+ [199, 800],
+ [Number.NaN, 1080],
+ ]) {
+ expect(getScreenDimensionSignals(width, height, DESKTOP_UA), `${width}x${height}`).toEqual([
+ "impossibleDimensions",
+ ]);
+ }
+ });
+
+ it("flags a square screen on any platform", () => {
+ expect(getScreenDimensionSignals(2000, 2000, DESKTOP_UA)).toEqual(["squareScreen"]);
+ expect(getScreenDimensionSignals(2000, 2000, MOBILE_UA)).toEqual(["squareScreen"]);
+ });
+
+ it("flags default automation viewports on desktop user agents only", () => {
+ for (const viewport of IMPLAUSIBLE_DESKTOP_VIEWPORTS) {
+ expect(getScreenDimensionSignals(viewport.width, viewport.height, DESKTOP_UA)).toContain(viewport.signal);
+ expect(getScreenDimensionSignals(viewport.width, viewport.height, MOBILE_UA)).toEqual([]);
+ }
+ });
+
+ // The tracker computes these from window.screen and the server re-derives them
+ // from the reported dimensions. Both call this function, so a signal that
+ // convicts must be reachable from the score the tracker would have sent.
+ it("produces signals the weights table can score", () => {
+ const signals = [
+ ...getScreenDimensionSignals(1, 1, DESKTOP_UA),
+ ...getScreenDimensionSignals(2000, 2000, DESKTOP_UA),
+ ...IMPLAUSIBLE_DESKTOP_VIEWPORTS.flatMap(viewport =>
+ getScreenDimensionSignals(viewport.width, viewport.height, DESKTOP_UA)
+ ),
+ ];
+
+ for (const signal of signals) {
+ expect(CLIENT_BOT_SIGNAL_MASKS[signal], `${signal} is in the mask table`).toBeGreaterThan(0);
+ expect(CLIENT_BOT_SIGNAL_WEIGHTS[signal], `${signal} is in the weights table`).toBeGreaterThan(0);
+ }
+ });
+});
diff --git a/server/src/services/tracker/botBlocking/index.test.ts b/server/src/services/tracker/botBlocking/index.test.ts
index 0bee1fb63..f1eaf18ec 100644
--- a/server/src/services/tracker/botBlocking/index.test.ts
+++ b/server/src/services/tracker/botBlocking/index.test.ts
@@ -1,3 +1,4 @@
+import { CLIENT_BOT_SIGNAL_MASKS as clientBotSignalMasks } from "@rybbit/shared";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { lookupAsn } from "../../../db/geolocation/asn.js";
import { resetAnomalyScorerForTests, setRedisAnomalyEnabledForTests } from "./anomalyScorer.js";
@@ -16,7 +17,7 @@ vi.mock("../../../db/redis/redis.js", () => ({
}));
const basePayload = {
- siteId: "site_123",
+ siteId: 123,
ipAddress: "203.0.113.10",
};
@@ -28,12 +29,6 @@ const browserHeaders = {
"user-agent": "Mozilla/5.0 Chrome/120 Safari/537.36",
};
-const clientBotSignalMasks = {
- automationApi: 1 << 0,
- zeroOuterDimensions: 1 << 1,
- swiftShader: 1 << 3,
-};
-
describe("checkBotBlocking", () => {
beforeEach(() => {
resetAnomalyScorerForTests();
diff --git a/server/src/services/tracker/botBlocking/index.ts b/server/src/services/tracker/botBlocking/index.ts
index f31cc1c6d..29ac235dc 100644
--- a/server/src/services/tracker/botBlocking/index.ts
+++ b/server/src/services/tracker/botBlocking/index.ts
@@ -1,3 +1,13 @@
+import {
+ CLIENT_BOT_SIGNAL_MASKS,
+ CLIENT_BOT_SIGNAL_WEIGHTS,
+ ClientBotSignalName,
+ getClientBotSignalNames,
+ getScreenDimensionSignals,
+ MAX_CLIENT_BOT_SCORE,
+ scoreFromMask,
+ STRONG_CLIENT_BOT_SIGNAL_BITS,
+} from "@rybbit/shared";
import type { IncomingHttpHeaders } from "http";
import { lookupAsn, type AsnInfo, type AsnLookup } from "../../../db/geolocation/asn.js";
import { logger } from "../../../lib/logger/logger.js";
@@ -15,7 +25,8 @@ import { classifyUA } from "./uaBots/index.js";
const LOG_BOT_DETECTIONS = false;
interface BotBlockingPayload {
- siteId: string;
+ /** Numeric Site id β€” the one ingestion uses everywhere else. */
+ siteId: number;
userAgent?: string;
clientBotScore?: number;
clientBotSignalMask?: number;
@@ -56,61 +67,6 @@ interface AnomalyReason {
windowSeconds: number;
}
-const CLIENT_SIGNAL_MASKS = {
- automationApi: 1 << 0,
- zeroOuterDimensions: 1 << 1,
- missingChrome: 1 << 2,
- swiftShader: 1 << 3,
- emptyPlugins: 1 << 4,
- defaultViewport800x600: 1 << 5,
- defaultViewport1024x768: 1 << 6,
- impossibleDimensions: 1 << 7,
- outerDimensionsWeird: 1 << 8,
- pluginApiAbsence: 1 << 9,
- defaultViewport1280x1200: 1 << 10,
- squareScreen: 1 << 11,
-} as const;
-
-type ClientSignalName = keyof typeof CLIENT_SIGNAL_MASKS;
-
-// Must mirror the weights in analytics-script/botSignals.ts β€” the client sends
-// one cached score, and the server recomputes it from the signal mask to split
-// it into convicting vs. corroborating evidence.
-const CLIENT_SIGNAL_WEIGHTS: Record<ClientSignalName, number> = {
- automationApi: 3,
- zeroOuterDimensions: 2,
- missingChrome: 1,
- swiftShader: 1,
- emptyPlugins: 1,
- defaultViewport800x600: 3,
- defaultViewport1024x768: 3,
- impossibleDimensions: 3,
- outerDimensionsWeird: 2,
- pluginApiAbsence: 0,
- defaultViewport1280x1200: 3,
- squareScreen: 3,
-};
-
-// Signals that are automation-specific enough to convict on their own. The
-// remaining (weak) signals β€” empty plugins, SwiftShader, zero outer dimensions,
-// missing window.chrome β€” all occur on real devices (Android Chrome ships empty
-// plugins; low-end GPUs fall back to SwiftShader; prerendered pages report zero
-// outer dimensions), so they corroborate other layers but never convict.
-const STRONG_CLIENT_SIGNAL_BITS =
- CLIENT_SIGNAL_MASKS.automationApi |
- CLIENT_SIGNAL_MASKS.impossibleDimensions |
- CLIENT_SIGNAL_MASKS.defaultViewport800x600 |
- CLIENT_SIGNAL_MASKS.defaultViewport1024x768 |
- CLIENT_SIGNAL_MASKS.defaultViewport1280x1200 |
- CLIENT_SIGNAL_MASKS.squareScreen;
-
-function sumClientSignalWeights(mask: number): number {
- return Object.entries(CLIENT_SIGNAL_MASKS).reduce(
- (total, [name, bit]) => ((mask & bit) !== 0 ? total + CLIENT_SIGNAL_WEIGHTS[name as ClientSignalName] : total),
- 0
- );
-}
-
export interface BotBlockingDetection {
layer: BotDetectionMethod;
botCategory?: string | null;
@@ -119,7 +75,7 @@ export interface BotBlockingDetection {
score?: number;
clientBotScore?: number;
clientBotSignalMask?: number;
- clientSignals?: ClientSignalName[];
+ clientSignals?: ClientBotSignalName[];
ip?: string;
asn?: number;
asnOrg?: string;
@@ -176,37 +132,6 @@ function buildBotEventProperties(
};
}
-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);
-}
-
-function getClientSignalNames(mask: number): ClientSignalName[] {
- return Object.entries(CLIENT_SIGNAL_MASKS).flatMap(([name, bit]) =>
- (mask & bit) !== 0 ? [name as ClientSignalName] : []
- );
-}
-
function getClientSignalResult(payload: BotBlockingPayload, userAgent: string) {
const hasClientScore = typeof payload.clientBotScore === "number" && Number.isFinite(payload.clientBotScore);
const hasClientMask = typeof payload.clientBotSignalMask === "number" && Number.isFinite(payload.clientBotSignalMask);
@@ -214,56 +139,39 @@ function getClientSignalResult(payload: BotBlockingPayload, userAgent: string) {
let mask = rawMask;
let inferredScore = 0;
- function addInferredSignal(name: ClientSignalName, weight: number) {
- const bit = CLIENT_SIGNAL_MASKS[name];
+ function addInferredSignal(name: ClientBotSignalName) {
+ const bit = CLIENT_BOT_SIGNAL_MASKS[name];
if ((mask & bit) === 0) {
mask |= bit;
}
if (!hasClientScore || (rawMask & bit) === 0) {
- inferredScore += weight;
+ inferredScore += CLIENT_BOT_SIGNAL_WEIGHTS[name];
}
}
// 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.
+ // rules apply to every hit regardless of which tracker version sent it. An
+ // event that reports no dimensions at all says nothing about its display.
const { screenWidth, screenHeight } = payload;
- const hasScreenDimensions = screenWidth !== undefined || screenHeight !== undefined;
- if (hasScreenDimensions && !isPlausibleScreenDimensions(screenWidth, screenHeight)) {
- addInferredSignal("impossibleDimensions", 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 (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);
- }
+ if (screenWidth !== undefined || screenHeight !== undefined) {
+ for (const signal of getScreenDimensionSignals(screenWidth ?? NaN, screenHeight ?? NaN, userAgent)) {
+ addInferredSignal(signal);
}
}
- const score = Math.min((hasClientScore ? payload.clientBotScore! : 0) + inferredScore, 10);
+ const score = Math.min((hasClientScore ? payload.clientBotScore! : 0) + inferredScore, MAX_CLIENT_BOT_SCORE);
// Score contributed by strong (convicting) signals only. Derived from the
// mask, not the client's opaque score β€” a score sent without a mask cannot be
// decomposed, so it can only ever corroborate.
- const strongScore = sumClientSignalWeights(mask & STRONG_CLIENT_SIGNAL_BITS);
+ const strongScore = scoreFromMask(mask & STRONG_CLIENT_BOT_SIGNAL_BITS);
return {
score,
strongScore,
mask,
- signalNames: getClientSignalNames(mask),
+ signalNames: getClientBotSignalNames(mask),
scoreForStats: hasClientScore || inferredScore > 0 ? score : undefined,
maskForStats: hasClientMask || mask !== 0 ? mask : undefined,
};
diff --git a/server/src/services/tracker/ingestEvent.test.ts b/server/src/services/tracker/ingestEvent.test.ts
index 27ba55767..c51fbacbb 100644
--- a/server/src/services/tracker/ingestEvent.test.ts
+++ b/server/src/services/tracker/ingestEvent.test.ts
@@ -222,6 +222,19 @@ describe("ingestEvent", () => {
);
});
+ // Anomaly counters are namespaced by this id. Passing the incoming identifier
+ // instead split one Site across two namespaces β€” the text id the UI emits and
+ // the legacy numeric id still accepted β€” each seeing half the traffic.
+ it("namespaces bot detection by the numeric Site id, not the incoming identifier", async () => {
+ await ingestEvent(trackingRequest());
+
+ expect(mocks.checkBotBlocking).toHaveBeenCalledWith(
+ expect.objectContaining({
+ payload: expect.objectContaining({ siteId: 42 }),
+ })
+ );
+ });
+
it("reuses the request's Site Configuration for identity instead of re-reading it", async () => {
await ingestEvent(
trackingRequest({
diff --git a/server/src/services/tracker/ingestEvent.ts b/server/src/services/tracker/ingestEvent.ts
index 6b7e145af..026c9579c 100644
--- a/server/src/services/tracker/ingestEvent.ts
+++ b/server/src/services/tracker/ingestEvent.ts
@@ -70,7 +70,7 @@ export async function ingestEvent(trackingRequest: TrackingRequest): Promise<Ing
isMobileSite: site.type === "mobile",
lookupAsn: trackingRequest.lookupAsn,
payload: {
- siteId: payload.site_id,
+ siteId: site.siteId,
userAgent: trackingRequest.userAgent,
clientBotScore: payload._bs,
clientBotSignalMask: payload._bsm,
diff --git a/server/src/services/tracker/trackingPayload.test.ts b/server/src/services/tracker/trackingPayload.test.ts
new file mode 100644
index 000000000..f9b2bd2f9
--- /dev/null
+++ b/server/src/services/tracker/trackingPayload.test.ts
@@ -0,0 +1,31 @@
+import { ALL_CLIENT_BOT_SIGNAL_BITS, CLIENT_BOT_SIGNAL_MASKS, MAX_CLIENT_BOT_SCORE } from "@rybbit/shared";
+import { describe, expect, it } from "vitest";
+import { trackingPayloadSchema } from "./trackingPayload.js";
+
+function pageview(fields: Record<string, unknown>) {
+ return trackingPayloadSchema.safeParse({ type: "pageview", site_id: "site_abc", ...fields });
+}
+
+describe("the bot signal bounds on an ingested payload", () => {
+ // The tracker's 12th signal bit (squareScreen = 2048) once exceeded a
+ // hard-coded `_bsm` bound, so every event carrying it failed validation and
+ // was dropped with a 400 β€” the whole event, not just the signal. The bound is
+ // derived from the contract now, so a new bit widens it automatically.
+ it("accepts a mask carrying every bit the contract defines", () => {
+ expect(pageview({ _bsm: ALL_CLIENT_BOT_SIGNAL_BITS, _bs: MAX_CLIENT_BOT_SCORE }).success).toBe(true);
+ expect(pageview({ _bsm: CLIENT_BOT_SIGNAL_MASKS.squareScreen }).success).toBe(true);
+ });
+
+ it("rejects a mask carrying bits the contract does not define", () => {
+ expect(pageview({ _bsm: ALL_CLIENT_BOT_SIGNAL_BITS + 1 }).success).toBe(false);
+ });
+
+ it("rejects a score above the contract's ceiling", () => {
+ expect(pageview({ _bs: MAX_CLIENT_BOT_SCORE }).success).toBe(true);
+ expect(pageview({ _bs: MAX_CLIENT_BOT_SCORE + 1 }).success).toBe(false);
+ });
+
+ it("treats both as optional β€” an older tracker sends neither", () => {
+ expect(pageview({}).success).toBe(true);
+ });
+});
diff --git a/server/src/services/tracker/trackingPayload.ts b/server/src/services/tracker/trackingPayload.ts
index 6286963dd..cde7a6f9f 100644
--- a/server/src/services/tracker/trackingPayload.ts
+++ b/server/src/services/tracker/trackingPayload.ts
@@ -1,3 +1,4 @@
+import { ALL_CLIENT_BOT_SIGNAL_BITS, MAX_CLIENT_BOT_SCORE } from "@rybbit/shared";
import { z } from "zod";
// Shared fields for all event types
@@ -17,8 +18,11 @@ const baseEventFields = {
feature_flags: z.record(z.string().max(100), z.string().max(2048)).optional(),
ip_address: z.string().ip().optional(),
user_agent: z.string().max(512).optional(),
- _bs: z.number().int().min(0).max(10).optional(),
- _bsm: z.number().int().min(0).max(2047).optional(),
+ // Bounds come from the Bot Signal contract, so appending a signal bit widens
+ // the accepted mask with it. Hard-coding the bound is how the 12th bit
+ // (squareScreen = 2048) came to fail validation and drop the whole event.
+ _bs: z.number().int().min(0).max(MAX_CLIENT_BOT_SCORE).optional(),
+ _bsm: z.number().int().min(0).max(ALL_CLIENT_BOT_SIGNAL_BITS).optional(),
};
// Default event_name and properties used by pageview and performance
diff --git a/shared/src/botSignalContract.ts b/shared/src/botSignalContract.ts
new file mode 100644
index 000000000..96c9e1da6
--- /dev/null
+++ b/shared/src/botSignalContract.ts
@@ -0,0 +1,171 @@
+/**
+ * The Bot Signal contract β€” the wire format the tracker and the server both speak.
+ *
+ * The tracker computes a weighted score and a compact signal bitmask in the
+ * browser and sends them as `_bs`/`_bsm`; the server re-derives the environment
+ * signals it can see server-side, decomposes the mask into convicting vs.
+ * corroborating evidence, and aggregates the bits for diagnostics. All three
+ * consumers must agree bit-for-bit, so the bit layout, the weights, the
+ * plausible-dimension bounds, the implausible-viewport list and the mask's valid
+ * range live here rather than being transcribed into each of them.
+ *
+ * Adding a signal: append a bit, give it a weight, and add it to
+ * STRONG_CLIENT_BOT_SIGNAL_BITS if it convicts on its own. Nothing else needs
+ * to change β€” the ingest bound, the stats labels and the score derivation are
+ * all computed from this table.
+ */
+
+export const CLIENT_BOT_SIGNAL_MASKS = {
+ automationApi: 1 << 0,
+ zeroOuterDimensions: 1 << 1,
+ missingChrome: 1 << 2,
+ swiftShader: 1 << 3,
+ emptyPlugins: 1 << 4,
+ defaultViewport800x600: 1 << 5,
+ defaultViewport1024x768: 1 << 6,
+ impossibleDimensions: 1 << 7,
+ outerDimensionsWeird: 1 << 8,
+ pluginApiAbsence: 1 << 9,
+ defaultViewport1280x1200: 1 << 10,
+ squareScreen: 1 << 11,
+} as const;
+
+export type ClientBotSignalName = keyof typeof CLIENT_BOT_SIGNAL_MASKS;
+
+export const CLIENT_BOT_SIGNAL_NAMES = Object.keys(CLIENT_BOT_SIGNAL_MASKS) as ClientBotSignalName[];
+
+/**
+ * Weight each signal contributes to the bot score. The tracker sums these as it
+ * detects signals; the server sums them back out of the mask to tell apart the
+ * signals that convict from the ones that only corroborate.
+ */
+export const CLIENT_BOT_SIGNAL_WEIGHTS: Record<ClientBotSignalName, number> = {
+ automationApi: 3,
+ zeroOuterDimensions: 2,
+ missingChrome: 1,
+ swiftShader: 1,
+ emptyPlugins: 1,
+ defaultViewport800x600: 3,
+ defaultViewport1024x768: 3,
+ impossibleDimensions: 3,
+ outerDimensionsWeird: 2,
+ pluginApiAbsence: 0,
+ defaultViewport1280x1200: 3,
+ squareScreen: 3,
+};
+
+/**
+ * Every bit this contract defines β€” and therefore the largest `_bsm` a current
+ * tracker can send. The ingest schema bounds `_bsm` by this value, so appending
+ * a bit above widens the bound with it. A hard-coded bound is how the 12th bit
+ * (squareScreen = 2048) came to fail validation and drop whole events.
+ */
+export const ALL_CLIENT_BOT_SIGNAL_BITS = CLIENT_BOT_SIGNAL_NAMES.reduce(
+ (mask, name) => mask | CLIENT_BOT_SIGNAL_MASKS[name],
+ 0
+);
+
+/**
+ * Signals automation-specific enough to convict on their own. The remaining
+ * (weak) signals β€” empty plugins, SwiftShader, zero outer dimensions, missing
+ * window.chrome β€” all occur on real devices (Android Chrome ships empty
+ * plugins; low-end GPUs fall back to SwiftShader; prerendered pages report zero
+ * outer dimensions), so they corroborate other layers but never convict.
+ */
+export const STRONG_CLIENT_BOT_SIGNAL_BITS =
+ CLIENT_BOT_SIGNAL_MASKS.automationApi |
+ CLIENT_BOT_SIGNAL_MASKS.impossibleDimensions |
+ CLIENT_BOT_SIGNAL_MASKS.defaultViewport800x600 |
+ CLIENT_BOT_SIGNAL_MASKS.defaultViewport1024x768 |
+ CLIENT_BOT_SIGNAL_MASKS.defaultViewport1280x1200 |
+ CLIENT_BOT_SIGNAL_MASKS.squareScreen;
+
+/** Upper bound on the reported bot score, on both sides of the wire. */
+export const MAX_CLIENT_BOT_SCORE = 10;
+
+/**
+ * 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.
+ */
+export const MIN_PLAUSIBLE_SCREEN_DIMENSION = 200;
+export const MAX_PLAUSIBLE_SCREEN_DIMENSION = 8192;
+
+/**
+ * Default automation/display-server geometries. 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 in one week from a
+ * single crawler, against a few hundred from everything else combined). Gated
+ * on a desktop user agent, where these sizes are implausible.
+ */
+export const IMPLAUSIBLE_DESKTOP_VIEWPORTS: readonly {
+ width: number;
+ height: number;
+ signal: ClientBotSignalName;
+}[] = [
+ { width: 800, height: 600, signal: "defaultViewport800x600" },
+ { width: 1024, height: 768, signal: "defaultViewport1024x768" },
+ { width: 1280, height: 1200, signal: "defaultViewport1280x1200" },
+];
+
+export 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
+ );
+}
+
+export function isDesktopUserAgent(userAgent: string): boolean {
+ return /Windows NT|Macintosh|X11|Linux x86_64/.test(userAgent) && !/Mobile|Android|iPhone|iPad/.test(userAgent);
+}
+
+/**
+ * The screen-geometry rules, evaluated identically in the browser (against
+ * `window.screen`) and on the server (against the reported dimensions, so the
+ * rules apply to every hit regardless of which tracker version sent it).
+ *
+ * An implausible display short-circuits: there is nothing to say about the
+ * shape of a screen that no display reports. Otherwise, no shipping display is
+ * square β€” every square value in production traffic is a renderer default
+ * (2000x2000 on Facebook/Amazon/Google infrastructure, 1024x1024 and 1280x1280
+ * on Google's, 1366x1366 and 1600x1600 on proxy fleets). Square is not gated on
+ * a desktop UA: the square fleets also claim Android and iOS.
+ */
+export function getScreenDimensionSignals(width: number, height: number, userAgent: string): ClientBotSignalName[] {
+ if (!isPlausibleScreenDimensions(width, height)) {
+ return ["impossibleDimensions"];
+ }
+
+ const signals: ClientBotSignalName[] = [];
+
+ if (width === height) {
+ signals.push("squareScreen");
+ }
+
+ if (isDesktopUserAgent(userAgent)) {
+ for (const viewport of IMPLAUSIBLE_DESKTOP_VIEWPORTS) {
+ if (width === viewport.width && height === viewport.height) {
+ signals.push(viewport.signal);
+ }
+ }
+ }
+
+ return signals;
+}
+
+/** The signals a mask carries, ignoring bits this contract does not define. */
+export function getClientBotSignalNames(mask: number): ClientBotSignalName[] {
+ return CLIENT_BOT_SIGNAL_NAMES.filter(name => (mask & CLIENT_BOT_SIGNAL_MASKS[name]) !== 0);
+}
+
+/** Uncapped sum of the weights of the signals a mask carries. */
+export function scoreFromMask(mask: number): number {
+ return getClientBotSignalNames(mask).reduce((total, name) => total + CLIENT_BOT_SIGNAL_WEIGHTS[name], 0);
+}
diff --git a/shared/src/index.ts b/shared/src/index.ts
index 4515cc3d3..51cdce44d 100644
--- a/shared/src/index.ts
+++ b/shared/src/index.ts
@@ -1,3 +1,4 @@
+export * from "./botSignalContract";
export * from "./dashboards";
export * from "./filters";
export * from "./params";