🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
replace monotomic siteId with random id (#588)
Bill Yang8a6321df88da
diff --git a/client/src/api/admin/sites.ts b/client/src/api/admin/sites.tsindex 98cf3eeae..45bbde678 100644--- a/client/src/api/admin/sites.ts+++ b/client/src/api/admin/sites.ts@@ -5,6 +5,7 @@ import { usePathname } from "next/navigation";import { authClient } from "../../lib/auth";export type SiteResponse = {+ id: string | null;siteId: number;name: string;domain: string;@@ -18,22 +19,6 @@ export type SiteResponse = {isOwner: boolean;};-export type GetSitesResponse = {- siteId: number;- name: string;- domain: string;- createdAt: string;- updatedAt: string;- createdBy: string;- public: boolean;- saltUserIds: boolean;- blockBots: boolean;- overMonthlyLimit?: boolean;- monthlyEventCount?: number;- eventLimit?: number;- isOwner?: boolean;-}[];-export type GetSitesFromOrgResponse = {organization: {id: string;@@ -47,6 +32,7 @@ export type GetSitesFromOrgResponse = {overMonthlyLimit: boolean | null;} | null;sites: Array<{+ id: string | null;siteId: number;name: string;domain: string;diff --git a/client/src/app/[site]/components/Header/NoData.tsx b/client/src/app/[site]/components/Header/NoData.tsxindex 412fd162c..ca1e72360 100644--- a/client/src/app/[site]/components/Header/NoData.tsx+++ b/client/src/app/[site]/components/Header/NoData.tsx@@ -73,7 +73,7 @@ export function NoData() {<div className="text-xs text-muted-foreground">Place this snippet in the <head> of your website:</div><CodeSnippetlanguage="HTML"- code={`<script\n src="${globalThis.location.origin}/api/script.js"\n data-site-id="${siteMetadata?.siteId}"\n defer\n></script>`}+ code={`<script\n src="${globalThis.location.origin}/api/script.js"\n data-site-id="${siteMetadata?.id ?? siteMetadata?.siteId}"\n defer\n></script>`}className="text-xs"/><span className="text-xs text-muted-foreground">diff --git a/client/src/components/SiteSettings/ScriptBuilder.tsx b/client/src/components/SiteSettings/ScriptBuilder.tsxindex 35540fa0d..01be9602f 100644--- a/client/src/components/SiteSettings/ScriptBuilder.tsx+++ b/client/src/components/SiteSettings/ScriptBuilder.tsx@@ -9,7 +9,7 @@ import { useState } from "react";import { IS_CLOUD } from "../../lib/const";interface ScriptBuilderProps {- siteId: number;+ siteId: string;}export function ScriptBuilder({ siteId }: ScriptBuilderProps) {@@ -204,26 +204,19 @@ export function ScriptBuilder({ siteId }: ScriptBuilderProps) {</div>{/* Track Outbound Links Option */}- {/* <div className="space-y-2">+ <div className="space-y-2"><div className="flex items-center justify-between"><div>- <Label- htmlFor="trackOutbound"- className="text-sm font-medium text-foreground block"- >+ <Label htmlFor="trackOutbound" className="text-sm font-medium text-foreground block">Track outbound link clicks</Label><p className="text-xs text-muted-foreground mt-1">Automatically track when users click links to external sites</p></div>- <Switch- id="trackOutbound"- checked={trackOutbound}- onCheckedChange={setTrackOutbound}- />+ <Switch id="trackOutbound" checked={trackOutbound} onCheckedChange={setTrackOutbound} /></div>- </div> */}+ </div>{/* Web Vitals Option */}{IS_CLOUD && (diff --git a/client/src/components/SiteSettings/SiteSettings.tsx b/client/src/components/SiteSettings/SiteSettings.tsxindex 59f6a062d..23731e55b 100644--- a/client/src/components/SiteSettings/SiteSettings.tsx+++ b/client/src/components/SiteSettings/SiteSettings.tsx@@ -65,7 +65,7 @@ function SiteSettingsInner({ siteMetadata, trigger }: { siteMetadata: SiteRespon</TabsList><TabsContent value="script" className="pt-4 space-y-4 max-h-[70vh] overflow-y-auto">- <ScriptBuilder siteId={siteMetadata.siteId} />+ <ScriptBuilder siteId={siteMetadata.id ?? String(siteMetadata.siteId)} /></TabsContent><TabsContent value="apikey" className="pt-4 space-y-4 max-h-[70vh] overflow-y-auto">diff --git a/docs-v2/src/app/layout.tsx b/docs-v2/src/app/layout.tsxindex 5c4e9bd7e..46a0d5e29 100644--- a/docs-v2/src/app/layout.tsx+++ b/docs-v2/src/app/layout.tsx@@ -78,7 +78,7 @@ export default function Layout({ children }: { children: ReactNode }) {<html lang="en" suppressHydrationWarning className="dark"><scriptsrc="https://demo.rybbit.io/api/script.js"- data-site-id="21"+ data-site-id="3c8487f0427d"deferdata-session-replay="true"data-web-vitals="true"diff --git a/server/drizzle.config.ts b/server/drizzle.config.tsindex b58314e70..07af307f0 100644--- a/server/drizzle.config.ts+++ b/server/drizzle.config.ts@@ -9,7 +9,7 @@ export default defineConfig({dialect: "postgresql",dbCredentials: {host: process.env.POSTGRES_HOST || "postgres",- port: process.env.POSTGRES_PORT || 5432,+ port: parseInt(process.env.POSTGRES_PORT || "5432"),database: process.env.POSTGRES_DB || "analytics",user: process.env.POSTGRES_USER || "frog",password: process.env.POSTGRES_PASSWORD || "frog",diff --git a/server/public/script-full.js b/server/public/script-full.jsindex ba4ddeeca..75154e47a 100644--- a/server/public/script-full.js+++ b/server/public/script-full.js@@ -72,30 +72,15 @@}const siteId = scriptTag.getAttribute("data-site-id") || scriptTag.getAttribute("site-id");if (!siteId || isNaN(Number(siteId))) {- console.error(- "Please provide a valid site ID using the data-site-id attribute"- );+ console.error("Please provide a valid site ID using the data-site-id attribute");return null;}const debounceDuration = scriptTag.getAttribute("data-debounce") ? Math.max(0, parseInt(scriptTag.getAttribute("data-debounce"))) : 500;- const skipPatterns = parseJsonSafely(- scriptTag.getAttribute("data-skip-patterns"),- []- );- const maskPatterns = parseJsonSafely(- scriptTag.getAttribute("data-mask-patterns"),- []- );+ const skipPatterns = parseJsonSafely(scriptTag.getAttribute("data-skip-patterns"), []);+ const maskPatterns = parseJsonSafely(scriptTag.getAttribute("data-mask-patterns"), []);const apiKey = scriptTag.getAttribute("data-api-key") || void 0;- const sessionReplayBatchSize = scriptTag.getAttribute(- "data-replay-batch-size"- ) ? Math.max(1, parseInt(scriptTag.getAttribute("data-replay-batch-size"))) : 250;- const sessionReplayBatchInterval = scriptTag.getAttribute(- "data-replay-batch-interval"- ) ? Math.max(- 1e3,- parseInt(scriptTag.getAttribute("data-replay-batch-interval"))- ) : 5e3;+ const sessionReplayBatchSize = scriptTag.getAttribute("data-replay-batch-size") ? Math.max(1, parseInt(scriptTag.getAttribute("data-replay-batch-size"))) : 250;+ const sessionReplayBatchInterval = scriptTag.getAttribute("data-replay-batch-interval") ? Math.max(1e3, parseInt(scriptTag.getAttribute("data-replay-batch-interval"))) : 5e3;return {analyticsHost,siteId,@@ -312,19 +297,16 @@if (this.config.apiKey) {batch.apiKey = this.config.apiKey;}- await fetch(- `${this.config.analyticsHost}/session-replay/record/${this.config.siteId}`,- {- method: "POST",- headers: {- "Content-Type": "application/json"- },- body: JSON.stringify(batch),- mode: "cors",- keepalive: false- // Disable keepalive for large session replay requests- }- );+ await fetch(`${this.config.analyticsHost}/session-replay/record/${this.config.siteId}`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json"+ },+ body: JSON.stringify(batch),+ mode: "cors",+ keepalive: false+ // Disable keepalive for large session replay requests+ });} catch (error) {console.error("Failed to send session replay batch:", error);throw error;@@ -379,9 +361,7 @@}track(eventType, eventName = "", properties = {}) {if (eventType === "custom_event" && (!eventName || typeof eventName !== "string")) {- console.error(- "Event name is required and must be a string for custom events"- );+ console.error("Event name is required and must be a string for custom events");return;}const basePayload = this.createBasePayload();@@ -526,26 +506,26 @@}, true);};var n = (e2, t2, n2, i2) => {- let s2, o2;+ let o2, s2;return (r2) => {- t2.value >= 0 && (r2 || i2) && (o2 = t2.value - (s2 ?? 0), (o2 || void 0 === s2) && (s2 = t2.value, t2.delta = o2, t2.rating = ((e3, t3) => e3 > t3[1] ? "poor" : e3 > t3[0] ? "needs-improvement" : "good")(t2.value, n2), e2(t2)));+ t2.value >= 0 && (r2 || i2) && (s2 = t2.value - (o2 ?? 0), (s2 || void 0 === o2) && (o2 = t2.value, t2.delta = s2, t2.rating = ((e3, t3) => e3 > t3[1] ? "poor" : e3 > t3[0] ? "needs-improvement" : "good")(t2.value, n2), e2(t2)));};};var i = (e2) => {requestAnimationFrame(() => requestAnimationFrame(() => e2()));};- var s = () => {+ var o = () => {const e2 = performance.getEntriesByType("navigation")[0];if (e2 && e2.responseStart > 0 && e2.responseStart < performance.now()) return e2;};- var o = () => {- const e2 = s();+ var s = () => {+ const e2 = o();return e2?.activationStart ?? 0;};var r = (t2, n2 = -1) => {- const i2 = s();+ const i2 = o();let r2 = "navigate";- e >= 0 ? r2 = "back-forward-cache" : i2 && (document.prerendering || o() > 0 ? r2 = "prerender" : document.wasDiscarded ? r2 = "restore" : i2.type && (r2 = i2.type.replace(/_/g, "-")));+ e >= 0 ? r2 = "back-forward-cache" : i2 && (document.prerendering || s() > 0 ? r2 = "prerender" : document.wasDiscarded ? r2 = "restore" : i2.type && (r2 = i2.type.replace(/_/g, "-")));return { name: t2, value: n2, rating: "good", delta: 0, entries: [], id: `v5-${Date.now()}-${Math.floor(8999999999999 * Math.random()) + 1e12}`, navigationType: r2 };};var c = /* @__PURE__ */ new WeakMap();@@ -584,130 +564,127 @@};};var u = -1;- var l = /* @__PURE__ */ new Set();- var m = () => "hidden" !== document.visibilityState || document.prerendering ? 1 / 0 : 0;- var p = (e2) => {- if ("hidden" === document.visibilityState) {- if ("visibilitychange" === e2.type) for (const e3 of l) e3();- isFinite(u) || (u = "visibilitychange" === e2.type ? e2.timeStamp : 0, removeEventListener("prerenderingchange", p, true));- }+ var l = () => "hidden" !== document.visibilityState || document.prerendering ? 1 / 0 : 0;+ var m = (e2) => {+ "hidden" === document.visibilityState && u > -1 && (u = "visibilitychange" === e2.type ? e2.timeStamp : 0, v());+ };+ var g = () => {+ addEventListener("visibilitychange", m, true), addEventListener("prerenderingchange", m, true);};var v = () => {+ removeEventListener("visibilitychange", m, true), removeEventListener("prerenderingchange", m, true);+ };+ var p = () => {if (u < 0) {- const e2 = o(), n2 = document.prerendering ? void 0 : globalThis.performance.getEntriesByType("visibility-state").filter((t2) => "hidden" === t2.name && t2.startTime > e2)[0]?.startTime;- u = n2 ?? m(), addEventListener("visibilitychange", p, true), addEventListener("prerenderingchange", p, true), t(() => {+ const e2 = s(), n2 = document.prerendering ? void 0 : globalThis.performance.getEntriesByType("visibility-state").filter((t2) => "hidden" === t2.name && t2.startTime > e2)[0]?.startTime;+ u = n2 ?? l(), g(), t(() => {setTimeout(() => {- u = m();+ u = l(), g();});});}return { get firstHiddenTime() {return u;- }, onHidden(e2) {- l.add(e2);} };};- var g = (e2) => {+ var y = (e2) => {document.prerendering ? addEventListener("prerenderingchange", () => e2(), true) : e2();};- var y = [1800, 3e3];- var E = (e2, s2 = {}) => {- g(() => {- const c2 = v();+ var b = [1800, 3e3];+ var P = (e2, o2 = {}) => {+ y(() => {+ const c2 = p();let a2, d2 = r("FCP");const f2 = h("paint", (e3) => {- for (const t2 of e3) "first-contentful-paint" === t2.name && (f2.disconnect(), t2.startTime < c2.firstHiddenTime && (d2.value = Math.max(t2.startTime - o(), 0), d2.entries.push(t2), a2(true)));+ for (const t2 of e3) "first-contentful-paint" === t2.name && (f2.disconnect(), t2.startTime < c2.firstHiddenTime && (d2.value = Math.max(t2.startTime - s(), 0), d2.entries.push(t2), a2(true)));});- f2 && (a2 = n(e2, d2, y, s2.reportAllChanges), t((t2) => {- d2 = r("FCP"), a2 = n(e2, d2, y, s2.reportAllChanges), i(() => {+ f2 && (a2 = n(e2, d2, b, o2.reportAllChanges), t((t2) => {+ d2 = r("FCP"), a2 = n(e2, d2, b, o2.reportAllChanges), i(() => {d2.value = performance.now() - t2.timeStamp, a2(true);});}));});};- var b = [0.1, 0.25];- var L = (e2, s2 = {}) => {- const o2 = v();- E(f(() => {- let c2, f2 = r("CLS", 0);- const u2 = a(s2, d), l2 = (e3) => {- for (const t2 of e3) u2.h(t2);- u2.i > f2.value && (f2.value = u2.i, f2.entries = u2.o, c2());- }, m2 = h("layout-shift", l2);- m2 && (c2 = n(e2, f2, b, s2.reportAllChanges), o2.onHidden(() => {- l2(m2.takeRecords()), c2(true);+ var T = [0.1, 0.25];+ var E = (e2, o2 = {}) => {+ P(f(() => {+ let s2, c2 = r("CLS", 0);+ const f2 = a(o2, d), u2 = (e3) => {+ for (const t2 of e3) f2.h(t2);+ f2.i > c2.value && (c2.value = f2.i, c2.entries = f2.o, s2());+ }, l2 = h("layout-shift", u2);+ l2 && (s2 = n(e2, c2, T, o2.reportAllChanges), document.addEventListener("visibilitychange", () => {+ "hidden" === document.visibilityState && (u2(l2.takeRecords()), s2(true));}), t(() => {- u2.i = 0, f2 = r("CLS", 0), c2 = n(e2, f2, b, s2.reportAllChanges), i(() => c2());- }), setTimeout(c2));+ f2.i = 0, c2 = r("CLS", 0), s2 = n(e2, c2, T, o2.reportAllChanges), i(() => s2());+ }), setTimeout(s2));}));};- var P = 0;- var T = 1 / 0;var _ = 0;- var M = (e2) => {- for (const t2 of e2) t2.interactionId && (T = Math.min(T, t2.interactionId), _ = Math.max(_, t2.interactionId), P = _ ? (_ - T) / 7 + 1 : 0);+ var L = 1 / 0;+ var M = 0;+ var C = (e2) => {+ for (const t2 of e2) t2.interactionId && (L = Math.min(L, t2.interactionId), M = Math.max(M, t2.interactionId), _ = M ? (M - L) / 7 + 1 : 0);};- var w;- var C = () => w ? P : performance.interactionCount ?? 0;- var I = () => {- "interactionCount" in performance || w || (w = h("event", M, { type: "event", buffered: true, durationThreshold: 0 }));+ var I;+ var w = () => I ? _ : performance.interactionCount ?? 0;+ var F = () => {+ "interactionCount" in performance || I || (I = h("event", C, { type: "event", buffered: true, durationThreshold: 0 }));};- var F = 0;- var k = class {+ var k = 0;+ var A = class {constructor() {__publicField(this, "u", []);__publicField(this, "l", /* @__PURE__ */ new Map());__publicField(this, "m");- __publicField(this, "p");+ __publicField(this, "v");}- v() {- F = C(), this.u.length = 0, this.l.clear();+ p() {+ k = w(), this.u.length = 0, this.l.clear();}- L() {- const e2 = Math.min(this.u.length - 1, Math.floor((C() - F) / 50));+ P() {+ const e2 = Math.min(this.u.length - 1, Math.floor((w() - k) / 50));return this.u[e2];}h(e2) {if (this.m?.(e2), !e2.interactionId && "first-input" !== e2.entryType) return;const t2 = this.u.at(-1);let n2 = this.l.get(e2.interactionId);- if (n2 || this.u.length < 10 || e2.duration > t2.P) {- if (n2 ? e2.duration > n2.P ? (n2.entries = [e2], n2.P = e2.duration) : e2.duration === n2.P && e2.startTime === n2.entries[0].startTime && n2.entries.push(e2) : (n2 = { id: e2.interactionId, entries: [e2], P: e2.duration }, this.l.set(n2.id, n2), this.u.push(n2)), this.u.sort((e3, t3) => t3.P - e3.P), this.u.length > 10) {+ if (n2 || this.u.length < 10 || e2.duration > t2.T) {+ if (n2 ? e2.duration > n2.T ? (n2.entries = [e2], n2.T = e2.duration) : e2.duration === n2.T && e2.startTime === n2.entries[0].startTime && n2.entries.push(e2) : (n2 = { id: e2.interactionId, entries: [e2], T: e2.duration }, this.l.set(n2.id, n2), this.u.push(n2)), this.u.sort((e3, t3) => t3.T - e3.T), this.u.length > 10) {const e3 = this.u.splice(10);for (const t3 of e3) this.l.delete(t3.id);}- this.p?.(n2);+ this.v?.(n2);}}};- var A = (e2) => {+ var B = (e2) => {const t2 = globalThis.requestIdleCallback || setTimeout;- "hidden" === document.visibilityState ? e2() : (e2 = f(e2), addEventListener("visibilitychange", e2, { once: true, capture: true }), t2(() => {- e2(), removeEventListener("visibilitychange", e2, { capture: true });+ "hidden" === document.visibilityState ? e2() : (e2 = f(e2), document.addEventListener("visibilitychange", e2, { once: true }), t2(() => {+ e2(), document.removeEventListener("visibilitychange", e2);}));};- var B = [200, 500];+ var N = [200, 500];var S = (e2, i2 = {}) => {- if (!globalThis.PerformanceEventTiming || !("interactionId" in PerformanceEventTiming.prototype)) return;- const s2 = v();- g(() => {- I();- let o2, c2 = r("INP");- const d2 = a(i2, k), f2 = (e3) => {- A(() => {- for (const t3 of e3) d2.h(t3);- const t2 = d2.L();- t2 && t2.P !== c2.value && (c2.value = t2.P, c2.entries = t2.entries, o2());+ globalThis.PerformanceEventTiming && "interactionId" in PerformanceEventTiming.prototype && y(() => {+ F();+ let o2, s2 = r("INP");+ const c2 = a(i2, A), d2 = (e3) => {+ B(() => {+ for (const t3 of e3) c2.h(t3);+ const t2 = c2.P();+ t2 && t2.T !== s2.value && (s2.value = t2.T, s2.entries = t2.entries, o2());});- }, u2 = h("event", f2, { durationThreshold: i2.durationThreshold ?? 40 });- o2 = n(e2, c2, B, i2.reportAllChanges), u2 && (u2.observe({ type: "first-input", buffered: true }), s2.onHidden(() => {- f2(u2.takeRecords()), o2(true);+ }, f2 = h("event", d2, { durationThreshold: i2.durationThreshold ?? 40 });+ o2 = n(e2, s2, N, i2.reportAllChanges), f2 && (f2.observe({ type: "first-input", buffered: true }), document.addEventListener("visibilitychange", () => {+ "hidden" === document.visibilityState && (d2(f2.takeRecords()), o2(true));}), t(() => {- d2.v(), c2 = r("INP"), o2 = n(e2, c2, B, i2.reportAllChanges);+ c2.p(), s2 = r("INP"), o2 = n(e2, s2, N, i2.reportAllChanges);}));});};- var N = class {+ var q = class {constructor() {__publicField(this, "m");}@@ -715,41 +692,39 @@this.m?.(e2);}};- var q = [2500, 4e3];- var x = (e2, s2 = {}) => {- g(() => {- const c2 = v();+ var x = [2500, 4e3];+ var O = (e2, o2 = {}) => {+ y(() => {+ const c2 = p();let d2, u2 = r("LCP");- const l2 = a(s2, N), m2 = (e3) => {- s2.reportAllChanges || (e3 = e3.slice(-1));- for (const t2 of e3) l2.h(t2), t2.startTime < c2.firstHiddenTime && (u2.value = Math.max(t2.startTime - o(), 0), u2.entries = [t2], d2());- }, p2 = h("largest-contentful-paint", m2);- if (p2) {- d2 = n(e2, u2, q, s2.reportAllChanges);- const o2 = f(() => {- m2(p2.takeRecords()), p2.disconnect(), d2(true);- }), c3 = (e3) => {- e3.isTrusted && (A(o2), removeEventListener(e3.type, c3, { capture: true }));- };- for (const e3 of ["keydown", "click", "visibilitychange"]) addEventListener(e3, c3, { capture: true });+ const l2 = a(o2, q), m2 = (e3) => {+ o2.reportAllChanges || (e3 = e3.slice(-1));+ for (const t2 of e3) l2.h(t2), t2.startTime < c2.firstHiddenTime && (u2.value = Math.max(t2.startTime - s(), 0), u2.entries = [t2], d2());+ }, g2 = h("largest-contentful-paint", m2);+ if (g2) {+ d2 = n(e2, u2, x, o2.reportAllChanges);+ const s2 = f(() => {+ m2(g2.takeRecords()), g2.disconnect(), d2(true);+ });+ for (const e3 of ["keydown", "click", "visibilitychange"]) addEventListener(e3, () => B(s2), { capture: true, once: true });t((t2) => {- u2 = r("LCP"), d2 = n(e2, u2, q, s2.reportAllChanges), i(() => {+ u2 = r("LCP"), d2 = n(e2, u2, x, o2.reportAllChanges), i(() => {u2.value = performance.now() - t2.timeStamp, d2(true);});});}});};- var H = [800, 1800];- var O = (e2) => {- document.prerendering ? g(() => O(e2)) : "complete" !== document.readyState ? addEventListener("load", () => O(e2), true) : setTimeout(e2);+ var $ = [800, 1800];+ var D = (e2) => {+ document.prerendering ? y(() => D(e2)) : "complete" !== document.readyState ? addEventListener("load", () => D(e2), true) : setTimeout(e2);};- var $ = (e2, i2 = {}) => {- let c2 = r("TTFB"), a2 = n(e2, c2, H, i2.reportAllChanges);- O(() => {- const d2 = s();- d2 && (c2.value = Math.max(d2.responseStart - o(), 0), c2.entries = [d2], a2(true), t(() => {- c2 = r("TTFB", 0), a2 = n(e2, c2, H, i2.reportAllChanges), a2(true);+ var H = (e2, i2 = {}) => {+ let c2 = r("TTFB"), a2 = n(e2, c2, $, i2.reportAllChanges);+ D(() => {+ const d2 = o();+ d2 && (c2.value = Math.max(d2.responseStart - s(), 0), c2.entries = [d2], a2(true), t(() => {+ c2 = r("TTFB", 0), a2 = n(e2, c2, $, i2.reportAllChanges), a2(true);}));});};@@ -771,11 +746,11 @@}initialize() {try {- x(this.collectMetric.bind(this));- L(this.collectMetric.bind(this));- S(this.collectMetric.bind(this));+ O(this.collectMetric.bind(this));E(this.collectMetric.bind(this));- $(this.collectMetric.bind(this));+ S(this.collectMetric.bind(this));+ P(this.collectMetric.bind(this));+ H(this.collectMetric.bind(this));this.timeout = setTimeout(() => {if (!this.sent) {this.sendData();@@ -794,9 +769,7 @@if (this.sent) return;const metricName = metric.name.toLowerCase();this.data[metricName] = metric.value;- const allCollected = Object.values(this.data).every(- (value) => value !== null- );+ const allCollected = Object.values(this.data).every((value) => value !== null);if (allCollected) {this.sendData();}@@ -830,6 +803,8 @@},event: () => {},+ error: () => {+ },trackOutbound: () => {},identify: () => {@@ -851,11 +826,9 @@}const tracker = new Tracker(config);if (config.enableWebVitals) {- const webVitalsCollector = new WebVitalsCollector(- (vitals) => {- tracker.trackWebVitals(vitals);- }- );+ const webVitalsCollector = new WebVitalsCollector((vitals) => {+ tracker.trackWebVitals(vitals);+ });webVitalsCollector.initialize();}if (config.trackErrors) {@@ -896,15 +869,9 @@target = target.parentElement;}if (config.trackOutbound) {- const link = e2.target.closest(- "a"- );+ const link = e2.target.closest("a");if (link?.href && isOutboundLink(link.href)) {- tracker.trackOutbound(- link.href,- link.innerText || link.textContent || "",- link.target || "_self"- );+ tracker.trackOutbound(link.href, link.innerText || link.textContent || "", link.target || "_self");}}});diff --git a/server/public/script.js b/server/public/script.jsindex 4d64eda90..5eef7b9e7 100644--- a/server/public/script.js+++ b/server/public/script.js@@ -1 +1 @@-"use strict";(()=>{var se=Object.defineProperty;var ae=(r,e,t)=>e in r?se(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var p=(r,e,t)=>ae(r,typeof e!="symbol"?e+"":e,t);function oe(r){let e="__DOUBLE_ASTERISK_TOKEN__",t="__SINGLE_ASTERISK_TOKEN__",n=r.replace(/\*\*/g,e).replace(/\*/g,t).replace(/[.+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(`/${e}/`,"g"),"/(?:.+/)?"),n=n.replace(new RegExp(e,"g"),".*"),n=n.replace(/\//g,"\\/");let o=n.replace(new RegExp(t,"g"),"[^/]+");return new RegExp("^"+o+"$")}function P(r,e){for(let t of e)try{if(oe(t).test(r))return t}catch(i){console.error(`Invalid pattern: ${t}`,i)}return null}function F(r,e){let t=null;return(...i)=>{t&&clearTimeout(t),t=setTimeout(()=>r(...i),e)}}function W(r){try{let e=window.location.hostname,t=new URL(r).hostname;return t!==e&&t!==""}catch{return!1}}function T(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}}function H(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 i=r.getAttribute("data-site-id")||r.getAttribute("site-id");if(!i||isNaN(Number(i)))return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let n=r.getAttribute("data-debounce")?Math.max(0,parseInt(r.getAttribute("data-debounce"))):500,o=T(r.getAttribute("data-skip-patterns"),[]),a=T(r.getAttribute("data-mask-patterns"),[]),s=r.getAttribute("data-api-key")||void 0,c=r.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(r.getAttribute("data-replay-batch-size"))):250,l=r.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(r.getAttribute("data-replay-batch-interval"))):5e3;return{analyticsHost:t,siteId:i,debounceDuration:n,autoTrackPageview:r.getAttribute("data-auto-track-pageview")!=="false",autoTrackSpa:r.getAttribute("data-track-spa")!=="false",trackQuerystring:r.getAttribute("data-track-query")!=="false",trackOutbound:r.getAttribute("data-track-outbound")!=="false",enableWebVitals:r.getAttribute("data-web-vitals")==="true",trackErrors:r.getAttribute("data-track-errors")==="true",enableSessionReplay:r.getAttribute("data-session-replay")==="true",sessionReplayBatchSize:c,sessionReplayBatchInterval:l,skipPatterns:o,maskPatterns:a,apiKey:s}}var v=class{constructor(e,t,i){this.isRecording=!1;this.eventBuffer=[];this.config=e,this.userId=t,this.sendBatch=i}async initialize(){this.config.enableSessionReplay&&(window.rrweb||await this.loadRrweb(),window.rrweb&&this.startRecording())}async loadRrweb(){return new Promise((e,t)=>{let i=document.createElement("script");i.src=`${this.config.analyticsHost}/replay.js`,i.async=!1,i.onload=()=>{e()},i.onerror=()=>t(new Error("Failed to load rrweb")),document.head.appendChild(i)})}startRecording(){if(!(this.isRecording||!window.rrweb||!this.config.enableSessionReplay))try{this.stopRecordingFn=window.rrweb.record({emit:e=>{this.addEvent({type:e.type,data:e.data,timestamp:e.timestamp||Date.now()})},recordCanvas:!0,collectFonts:!0,checkoutEveryNms:3e4,checkoutEveryNth:200,maskAllInputs:!0,maskInputOptions:{password:!0,email:!0},slimDOMOptions:{script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},sampling:{mousemove:!1,mouseInteraction:!0,scroll:150,input:"last"}}),this.isRecording=!0,this.setupBatchTimer()}catch{}}stopRecording(){this.isRecording&&(this.stopRecordingFn&&this.stopRecordingFn(),this.isRecording=!1,this.clearBatchTimer(),this.eventBuffer.length>0&&this.flushEvents())}isActive(){return this.isRecording}addEvent(e){this.eventBuffer.push(e),this.eventBuffer.length>=this.config.sessionReplayBatchSize&&this.flushEvents()}setupBatchTimer(){this.clearBatchTimer(),this.batchTimer=window.setInterval(()=>{this.eventBuffer.length>0&&this.flushEvents()},this.config.sessionReplayBatchInterval)}clearBatchTimer(){this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0)}async flushEvents(){if(this.eventBuffer.length===0)return;let e=[...this.eventBuffer];this.eventBuffer=[];let t={userId:this.userId,events:e,metadata:{pageUrl:window.location.href,viewportWidth:screen.width,viewportHeight:screen.height,language:navigator.language}};try{await this.sendBatch(t)}catch{this.eventBuffer.unshift(...e)}}updateUserId(e){this.userId=e}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var b=class{constructor(e){this.customUserId=null;this.config=e,this.loadUserId(),e.enableSessionReplay&&this.initializeSessionReplay()}loadUserId(){try{let e=localStorage.getItem("rybbit-user-id");e&&(this.customUserId=e)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new v(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{this.config.apiKey&&(e.apiKey=this.config.apiKey),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)),P(t,this.config.skipPatterns))return null;let i=P(t,this.config.maskPatterns);i&&(t=i);let n={site_id:this.config.siteId,hostname:e.hostname,pathname:t,querystring:this.config.trackQuerystring?e.search:"",screenWidth:screen.width,screenHeight:screen.height,language:navigator.language,page_title:document.title,referrer:document.referrer};return this.customUserId&&(n.user_id=this.customUserId),this.config.apiKey&&(n.api_key=this.config.apiKey),n}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="",i={}){if(e==="custom_event"&&(!t||typeof t!="string")){console.error("Event name is required and must be a string for custom events");return}let n=this.createBasePayload();if(!n)return;let o={...n,type:e,event_name:t,properties:e==="custom_event"||e==="outbound"||e==="error"?JSON.stringify(i):void 0};this.sendTrackingData(o)}trackPageview(){this.track("pageview")}trackEvent(e,t={}){this.track("custom_event",e,t)}trackOutbound(e,t="",i="_self"){this.track("outbound","",{url:e,text:t,target:i})}trackWebVitals(e){let t=this.createBasePayload();if(!t)return;let i={...t,type:"performance",event_name:"web-vitals",...e};this.sendTrackingData(i)}trackError(e,t={}){let i=window.location.origin,n=t.filename||"",o=e.stack||"";if(n)try{if(new URL(n).origin!==i)return}catch{}else if(o&&!o.includes(i))return;let a={message:e.message?.substring(0,500)||"Unknown error",stack:o.substring(0,2e3)||""};if(n&&(a.fileName=n),t.lineno){let s=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;s&&s!==0&&(a.lineNumber=s)}if(t.colno){let s=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;s&&s!==0&&(a.columnNumber=s)}for(let s in t)!["lineno","colno"].includes(s)&&t[s]!==void 0&&(a[s]=t[s]);this.track("error",e.name||"Error",a)}identify(e){if(typeof e!="string"||e.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=e.trim();try{localStorage.setItem("rybbit-user-id",this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(this.customUserId)}clearUserId(){this.customUserId=null;try{localStorage.removeItem("rybbit-user-id")}catch{}}getUserId(){return this.customUserId}startSessionReplay(){this.sessionReplayRecorder?this.sessionReplayRecorder.startRecording():console.warn("Session replay not initialized")}stopSessionReplay(){this.sessionReplayRecorder&&this.sessionReplayRecorder.stopRecording()}isSessionReplayActive(){return this.sessionReplayRecorder?.isActive()??!1}onPageChange(){this.sessionReplayRecorder&&this.sessionReplayRecorder.onPageChange()}cleanup(){this.sessionReplayRecorder&&this.sessionReplayRecorder.cleanup()}};var Q=-1,f=r=>{addEventListener("pageshow",e=>{e.persisted&&(Q=e.timeStamp,r(e))},!0)},u=(r,e,t,i)=>{let n,o;return a=>{e.value>=0&&(a||i)&&(o=e.value-(n??0),(o||n===void 0)&&(n=e.value,e.delta=o,e.rating=((s,c)=>s>c[1]?"poor":s>c[0]?"needs-improvement":"good")(e.value,t),r(e)))}},O=r=>{requestAnimationFrame(()=>requestAnimationFrame(()=>r()))},D=()=>{let r=performance.getEntriesByType("navigation")[0];if(r&&r.responseStart>0&&r.responseStart<performance.now())return r},m=()=>D()?.activationStart??0,h=(r,e=-1)=>{let t=D(),i="navigate";return Q>=0?i="back-forward-cache":t&&(document.prerendering||m()>0?i="prerender":document.wasDiscarded?i="restore":t.type&&(i=t.type.replace(/_/g,"-"))),{name:r,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:i}},E=new WeakMap;function U(r,e){return E.get(r)||E.set(r,new e),E.get(r)}var I=class{constructor(){p(this,"t");p(this,"i",0);p(this,"o",[])}h(e){if(e.hadRecentInput)return;let t=this.o[0],i=this.o.at(-1);this.i&&t&&i&&e.startTime-i.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)}},y=(r,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(r)){let i=new PerformanceObserver(n=>{Promise.resolve().then(()=>{e(n.getEntries())})});return i.observe({type:r,buffered:!0,...t}),i}}catch{}},x=r=>{let e=!1;return()=>{e||(r(),e=!0)}},g=-1,Y=new Set,V=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,A=r=>{if(document.visibilityState==="hidden"){if(r.type==="visibilitychange")for(let e of Y)e();isFinite(g)||(g=r.type==="visibilitychange"?r.timeStamp:0,removeEventListener("prerenderingchange",A,!0))}},w=()=>{if(g<0){let r=m();g=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter(t=>t.name==="hidden"&&t.startTime>r)[0]?.startTime)??V(),addEventListener("visibilitychange",A,!0),addEventListener("prerenderingchange",A,!0),f(()=>{setTimeout(()=>{g=V()})})}return{get firstHiddenTime(){return g},onHidden(r){Y.add(r)}}},S=r=>{document.prerendering?addEventListener("prerenderingchange",()=>r(),!0):r()},z=[1800,3e3],N=(r,e={})=>{S(()=>{let t=w(),i,n=h("FCP"),o=y("paint",a=>{for(let s of a)s.name==="first-contentful-paint"&&(o.disconnect(),s.startTime<t.firstHiddenTime&&(n.value=Math.max(s.startTime-m(),0),n.entries.push(s),i(!0)))});o&&(i=u(r,n,z,e.reportAllChanges),f(a=>{n=h("FCP"),i=u(r,n,z,e.reportAllChanges),O(()=>{n.value=performance.now()-a.timeStamp,i(!0)})}))})},K=[.1,.25],X=(r,e={})=>{let t=w();N(x(()=>{let i,n=h("CLS",0),o=U(e,I),a=c=>{for(let l of c)o.h(l);o.i>n.value&&(n.value=o.i,n.entries=o.o,i())},s=y("layout-shift",a);s&&(i=u(r,n,K,e.reportAllChanges),t.onHidden(()=>{a(s.takeRecords()),i(!0)}),f(()=>{o.i=0,n=h("CLS",0),i=u(r,n,K,e.reportAllChanges),O(()=>i())}),setTimeout(i))}))},Z=0,C=1/0,R=0,ce=r=>{for(let e of r)e.interactionId&&(C=Math.min(C,e.interactionId),R=Math.max(R,e.interactionId),Z=R?(R-C)/7+1:0)},B,$=()=>B?Z:performance.interactionCount??0,le=()=>{"interactionCount"in performance||B||(B=y("event",ce,{type:"event",buffered:!0,durationThreshold:0}))},J=0,L=class{constructor(){p(this,"u",[]);p(this,"l",new Map);p(this,"m");p(this,"p")}v(){J=$(),this.u.length=0,this.l.clear()}L(){let e=Math.min(this.u.length-1,Math.floor(($()-J)/50));return this.u[e]}h(e){if(this.m?.(e),!e.interactionId&&e.entryType!=="first-input")return;let t=this.u.at(-1),i=this.l.get(e.interactionId);if(i||this.u.length<10||e.duration>t.P){if(i?e.duration>i.P?(i.entries=[e],i.P=e.duration):e.duration===i.P&&e.startTime===i.entries[0].startTime&&i.entries.push(e):(i={id:e.interactionId,entries:[e],P:e.duration},this.l.set(i.id,i),this.u.push(i)),this.u.sort((n,o)=>o.P-n.P),this.u.length>10){let n=this.u.splice(10);for(let o of n)this.l.delete(o.id)}this.p?.(i)}}},ee=r=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?r():(r=x(r),addEventListener("visibilitychange",r,{once:!0,capture:!0}),e(()=>{r(),removeEventListener("visibilitychange",r,{capture:!0})}))},q=[200,500],te=(r,e={})=>{if(!globalThis.PerformanceEventTiming||!("interactionId"in PerformanceEventTiming.prototype))return;let t=w();S(()=>{le();let i,n=h("INP"),o=U(e,L),a=c=>{ee(()=>{for(let d of c)o.h(d);let l=o.L();l&&l.P!==n.value&&(n.value=l.P,n.entries=l.entries,i())})},s=y("event",a,{durationThreshold:e.durationThreshold??40});i=u(r,n,q,e.reportAllChanges),s&&(s.observe({type:"first-input",buffered:!0}),t.onHidden(()=>{a(s.takeRecords()),i(!0)}),f(()=>{o.v(),n=h("INP"),i=u(r,n,q,e.reportAllChanges)}))})},M=class{constructor(){p(this,"m")}h(e){this.m?.(e)}},j=[2500,4e3],re=(r,e={})=>{S(()=>{let t=w(),i,n=h("LCP"),o=U(e,M),a=c=>{e.reportAllChanges||(c=c.slice(-1));for(let l of c)o.h(l),l.startTime<t.firstHiddenTime&&(n.value=Math.max(l.startTime-m(),0),n.entries=[l],i())},s=y("largest-contentful-paint",a);if(s){i=u(r,n,j,e.reportAllChanges);let c=x(()=>{a(s.takeRecords()),s.disconnect(),i(!0)}),l=d=>{d.isTrusted&&(ee(c),removeEventListener(d.type,l,{capture:!0}))};for(let d of["keydown","click","visibilitychange"])addEventListener(d,l,{capture:!0});f(d=>{n=h("LCP"),i=u(r,n,j,e.reportAllChanges),O(()=>{n.value=performance.now()-d.timeStamp,i(!0)})})}})},G=[800,1800],_=r=>{document.prerendering?S(()=>_(r)):document.readyState!=="complete"?addEventListener("load",()=>_(r),!0):setTimeout(r)},ie=(r,e={})=>{let t=h("TTFB"),i=u(r,t,G,e.reportAllChanges);_(()=>{let n=D();n&&(t.value=Math.max(n.responseStart-m(),0),t.entries=[n],i(!0),f(()=>{t=h("TTFB",0),i=u(r,t,G,e.reportAllChanges),i(!0)}))})};var k=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{re(this.collectMetric.bind(this)),X(this.collectMetric.bind(this)),te(this.collectMetric.bind(this)),N(this.collectMetric.bind(this)),ie(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(n=>n!==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}}};(function(){let r=document.currentScript;if(!r){console.error("Could not find current script tag");return}if(window.__RYBBIT_OPTOUT__||localStorage.getItem("disable-rybbit")!==null){window.rybbit={pageview:()=>{},event:()=>{},trackOutbound:()=>{},identify:()=>{},clearUserId:()=>{},getUserId:()=>null,startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let e=H(r);if(!e)return;let t=new b(e);e.enableWebVitals&&new k(s=>{t.trackWebVitals(s)}).initialize(),e.trackErrors&&(window.addEventListener("error",a=>{t.trackError(a.error||new Error(a.message),{filename:a.filename,lineno:a.lineno,colno:a.colno})}),window.addEventListener("unhandledrejection",a=>{let s=a.reason instanceof Error?a.reason:new Error(String(a.reason));t.trackError(s,{type:"unhandledrejection"})}));let i=()=>t.trackPageview(),n=e.debounceDuration>0?F(i,e.debounceDuration):i;function o(){if(document.addEventListener("click",function(a){let s=a.target;for(;s&&s!==document.documentElement;){if(s.hasAttribute("data-rybbit-event")){let c=s.getAttribute("data-rybbit-event");if(c){let l={};for(let d of s.attributes)if(d.name.startsWith("data-rybbit-prop-")){let ne=d.name.replace("data-rybbit-prop-","");l[ne]=d.value}t.trackEvent(c,l)}break}s=s.parentElement}if(e.trackOutbound){let c=a.target.closest("a");c?.href&&W(c.href)&&t.trackOutbound(c.href,c.innerText||c.textContent||"",c.target||"_self")}}),e.autoTrackSpa){let a=history.pushState,s=history.replaceState;history.pushState=function(...c){a.apply(this,c),n(),t.onPageChange()},history.replaceState=function(...c){s.apply(this,c),n(),t.onPageChange()},window.addEventListener("popstate",()=>{n(),t.onPageChange()}),window.addEventListener("hashchange",()=>{n(),t.onPageChange()})}}window.rybbit={pageview:()=>t.trackPageview(),event:(a,s={})=>t.trackEvent(a,s),error:(a,s={})=>t.trackError(a,s),trackOutbound:(a,s="",c="_self")=>t.trackOutbound(a,s,c),identify:a=>t.identify(a),clearUserId:()=>t.clearUserId(),getUserId:()=>t.getUserId(),startSessionReplay:()=>t.startSessionReplay(),stopSessionReplay:()=>t.stopSessionReplay(),isSessionReplayActive:()=>t.isSessionReplayActive()},o(),window.addEventListener("beforeunload",()=>{t.cleanup()}),e.autoTrackPageview&&t.trackPageview()})();})();+"use strict";(()=>{var se=Object.defineProperty;var ae=(i,e,t)=>e in i?se(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var h=(i,e,t)=>ae(i,typeof e!="symbol"?e+"":e,t);function oe(i){let e="__DOUBLE_ASTERISK_TOKEN__",t="__SINGLE_ASTERISK_TOKEN__",n=i.replace(/\*\*/g,e).replace(/\*/g,t).replace(/[.+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(`/${e}/`,"g"),"/(?:.+/)?"),n=n.replace(new RegExp(e,"g"),".*"),n=n.replace(/\//g,"\\/");let c=n.replace(new RegExp(t,"g"),"[^/]+");return new RegExp("^"+c+"$")}function k(i,e){for(let t of e)try{if(oe(t).test(i))return t}catch(r){console.error(`Invalid pattern: ${t}`,r)}return null}function x(i,e){let t=null;return(...r)=>{t&&clearTimeout(t),t=setTimeout(()=>i(...r),e)}}function F(i){try{let e=window.location.hostname,t=new URL(i).hostname;return t!==e&&t!==""}catch{return!1}}function E(i,e){if(!i)return e;try{let t=JSON.parse(i);return Array.isArray(e)&&!Array.isArray(t)?e:t}catch(t){return console.error("Error parsing JSON:",t),e}}function W(i){let e=i.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=i.getAttribute("data-site-id")||i.getAttribute("site-id");if(!r||isNaN(Number(r)))return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let n=i.getAttribute("data-debounce")?Math.max(0,parseInt(i.getAttribute("data-debounce"))):500,c=E(i.getAttribute("data-skip-patterns"),[]),a=E(i.getAttribute("data-mask-patterns"),[]),s=i.getAttribute("data-api-key")||void 0,o=i.getAttribute("data-replay-batch-size")?Math.max(1,parseInt(i.getAttribute("data-replay-batch-size"))):250,l=i.getAttribute("data-replay-batch-interval")?Math.max(1e3,parseInt(i.getAttribute("data-replay-batch-interval"))):5e3;return{analyticsHost:t,siteId:r,debounceDuration:n,autoTrackPageview:i.getAttribute("data-auto-track-pageview")!=="false",autoTrackSpa:i.getAttribute("data-track-spa")!=="false",trackQuerystring:i.getAttribute("data-track-query")!=="false",trackOutbound:i.getAttribute("data-track-outbound")!=="false",enableWebVitals:i.getAttribute("data-web-vitals")==="true",trackErrors:i.getAttribute("data-track-errors")==="true",enableSessionReplay:i.getAttribute("data-session-replay")==="true",sessionReplayBatchSize:o,sessionReplayBatchInterval:l,skipPatterns:c,maskPatterns:a,apiKey:s}}var y=class{constructor(e,t,r){this.isRecording=!1;this.eventBuffer=[];this.config=e,this.userId=t,this.sendBatch=r}async initialize(){this.config.enableSessionReplay&&(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{this.stopRecordingFn=window.rrweb.record({emit:e=>{this.addEvent({type:e.type,data:e.data,timestamp:e.timestamp||Date.now()})},recordCanvas:!0,collectFonts:!0,checkoutEveryNms:3e4,checkoutEveryNth:200,maskAllInputs:!0,maskInputOptions:{password:!0,email:!0},slimDOMOptions:{script:!1,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0},sampling:{mousemove:!1,mouseInteraction:!0,scroll:150,input:"last"}}),this.isRecording=!0,this.setupBatchTimer()}catch{}}stopRecording(){this.isRecording&&(this.stopRecordingFn&&this.stopRecordingFn(),this.isRecording=!1,this.clearBatchTimer(),this.eventBuffer.length>0&&this.flushEvents())}isActive(){return this.isRecording}addEvent(e){this.eventBuffer.push(e),this.eventBuffer.length>=this.config.sessionReplayBatchSize&&this.flushEvents()}setupBatchTimer(){this.clearBatchTimer(),this.batchTimer=window.setInterval(()=>{this.eventBuffer.length>0&&this.flushEvents()},this.config.sessionReplayBatchInterval)}clearBatchTimer(){this.batchTimer&&(clearInterval(this.batchTimer),this.batchTimer=void 0)}async flushEvents(){if(this.eventBuffer.length===0)return;let e=[...this.eventBuffer];this.eventBuffer=[];let t={userId:this.userId,events:e,metadata:{pageUrl:window.location.href,viewportWidth:screen.width,viewportHeight:screen.height,language:navigator.language}};try{await this.sendBatch(t)}catch{this.eventBuffer.unshift(...e)}}updateUserId(e){this.userId=e}onPageChange(){this.isRecording&&this.flushEvents()}cleanup(){this.stopRecording()}};var v=class{constructor(e){this.customUserId=null;this.config=e,this.loadUserId(),e.enableSessionReplay&&this.initializeSessionReplay()}loadUserId(){try{let e=localStorage.getItem("rybbit-user-id");e&&(this.customUserId=e)}catch{}}async initializeSessionReplay(){try{this.sessionReplayRecorder=new y(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{this.config.apiKey&&(e.apiKey=this.config.apiKey),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)),k(t,this.config.skipPatterns))return null;let r=k(t,this.config.maskPatterns);r&&(t=r);let n={site_id:this.config.siteId,hostname:e.hostname,pathname:t,querystring:this.config.trackQuerystring?e.search:"",screenWidth:screen.width,screenHeight:screen.height,language:navigator.language,page_title:document.title,referrer:document.referrer};return this.customUserId&&(n.user_id=this.customUserId),this.config.apiKey&&(n.api_key=this.config.apiKey),n}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 n=this.createBasePayload();if(!n)return;let c={...n,type:e,event_name:t,properties:e==="custom_event"||e==="outbound"||e==="error"?JSON.stringify(r):void 0};this.sendTrackingData(c)}trackPageview(){this.track("pageview")}trackEvent(e,t={}){this.track("custom_event",e,t)}trackOutbound(e,t="",r="_self"){this.track("outbound","",{url:e,text:t,target:r})}trackWebVitals(e){let t=this.createBasePayload();if(!t)return;let r={...t,type:"performance",event_name:"web-vitals",...e};this.sendTrackingData(r)}trackError(e,t={}){let r=window.location.origin,n=t.filename||"",c=e.stack||"";if(n)try{if(new URL(n).origin!==r)return}catch{}else if(c&&!c.includes(r))return;let a={message:e.message?.substring(0,500)||"Unknown error",stack:c.substring(0,2e3)||""};if(n&&(a.fileName=n),t.lineno){let s=typeof t.lineno=="string"?parseInt(t.lineno,10):t.lineno;s&&s!==0&&(a.lineNumber=s)}if(t.colno){let s=typeof t.colno=="string"?parseInt(t.colno,10):t.colno;s&&s!==0&&(a.columnNumber=s)}for(let s in t)!["lineno","colno"].includes(s)&&t[s]!==void 0&&(a[s]=t[s]);this.track("error",e.name||"Error",a)}identify(e){if(typeof e!="string"||e.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=e.trim();try{localStorage.setItem("rybbit-user-id",this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}this.sessionReplayRecorder&&this.sessionReplayRecorder.updateUserId(this.customUserId)}clearUserId(){this.customUserId=null;try{localStorage.removeItem("rybbit-user-id")}catch{}}getUserId(){return this.customUserId}startSessionReplay(){this.sessionReplayRecorder?this.sessionReplayRecorder.startRecording():console.warn("Session replay not initialized")}stopSessionReplay(){this.sessionReplayRecorder&&this.sessionReplayRecorder.stopRecording()}isSessionReplayActive(){return this.sessionReplayRecorder?.isActive()??!1}onPageChange(){this.sessionReplayRecorder&&this.sessionReplayRecorder.onPageChange()}cleanup(){this.sessionReplayRecorder&&this.sessionReplayRecorder.cleanup()}};var Q=-1,g=i=>{addEventListener("pageshow",e=>{e.persisted&&(Q=e.timeStamp,i(e))},!0)},d=(i,e,t,r)=>{let n,c;return a=>{e.value>=0&&(a||r)&&(c=e.value-(n??0),(c||n===void 0)&&(n=e.value,e.delta=c,e.rating=((s,o)=>s>o[1]?"poor":s>o[0]?"needs-improvement":"good")(e.value,t),i(e)))}},_=i=>{requestAnimationFrame(()=>requestAnimationFrame(()=>i()))},D=()=>{let i=performance.getEntriesByType("navigation")[0];if(i&&i.responseStart>0&&i.responseStart<performance.now())return i},f=()=>D()?.activationStart??0,u=(i,e=-1)=>{let t=D(),r="navigate";return Q>=0?r="back-forward-cache":t&&(document.prerendering||f()>0?r="prerender":document.wasDiscarded?r="restore":t.type&&(r=t.type.replace(/_/g,"-"))),{name:i,value:e,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:r}},P=new WeakMap;function O(i,e){return P.get(i)||P.set(i,new e),P.get(i)}var I=class{constructor(){h(this,"t");h(this,"i",0);h(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=(i,e,t={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(i)){let r=new PerformanceObserver(n=>{Promise.resolve().then(()=>{e(n.getEntries())})});return r.observe({type:i,buffered:!0,...t}),r}}catch{}},U=i=>{let e=!1;return()=>{e||(i(),e=!0)}},p=-1,H=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,R=i=>{document.visibilityState==="hidden"&&p>-1&&(p=i.type==="visibilitychange"?i.timeStamp:0,ce())},V=()=>{addEventListener("visibilitychange",R,!0),addEventListener("prerenderingchange",R,!0)},ce=()=>{removeEventListener("visibilitychange",R,!0),removeEventListener("prerenderingchange",R,!0)},Y=()=>{if(p<0){let i=f();p=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter(t=>t.name==="hidden"&&t.startTime>i)[0]?.startTime)??H(),V(),g(()=>{setTimeout(()=>{p=H(),V()})})}return{get firstHiddenTime(){return p}}},w=i=>{document.prerendering?addEventListener("prerenderingchange",()=>i(),!0):i()},z=[1800,3e3],N=(i,e={})=>{w(()=>{let t=Y(),r,n=u("FCP"),c=m("paint",a=>{for(let s of a)s.name==="first-contentful-paint"&&(c.disconnect(),s.startTime<t.firstHiddenTime&&(n.value=Math.max(s.startTime-f(),0),n.entries.push(s),r(!0)))});c&&(r=d(i,n,z,e.reportAllChanges),g(a=>{n=u("FCP"),r=d(i,n,z,e.reportAllChanges),_(()=>{n.value=performance.now()-a.timeStamp,r(!0)})}))})},K=[.1,.25],X=(i,e={})=>{N(U(()=>{let t,r=u("CLS",0),n=O(e,I),c=s=>{for(let o of s)n.h(o);n.i>r.value&&(r.value=n.i,r.entries=n.o,t())},a=m("layout-shift",c);a&&(t=d(i,r,K,e.reportAllChanges),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(a.takeRecords()),t(!0))}),g(()=>{n.i=0,r=u("CLS",0),t=d(i,r,K,e.reportAllChanges),_(()=>t())}),setTimeout(t))}))},Z=0,C=1/0,b=0,le=i=>{for(let e of i)e.interactionId&&(C=Math.min(C,e.interactionId),b=Math.max(b,e.interactionId),Z=b?(b-C)/7+1:0)},A,$=()=>A?Z:performance.interactionCount??0,de=()=>{"interactionCount"in performance||A||(A=m("event",le,{type:"event",buffered:!0,durationThreshold:0}))},J=0,B=class{constructor(){h(this,"u",[]);h(this,"l",new Map);h(this,"m");h(this,"v")}p(){J=$(),this.u.length=0,this.l.clear()}P(){let e=Math.min(this.u.length-1,Math.floor(($()-J)/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.T){if(r?e.duration>r.T?(r.entries=[e],r.T=e.duration):e.duration===r.T&&e.startTime===r.entries[0].startTime&&r.entries.push(e):(r={id:e.interactionId,entries:[e],T:e.duration},this.l.set(r.id,r),this.u.push(r)),this.u.sort((n,c)=>c.T-n.T),this.u.length>10){let n=this.u.splice(10);for(let c of n)this.l.delete(c.id)}this.v?.(r)}}},ee=i=>{let e=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?i():(i=U(i),document.addEventListener("visibilitychange",i,{once:!0}),e(()=>{i(),document.removeEventListener("visibilitychange",i)}))},j=[200,500],te=(i,e={})=>{globalThis.PerformanceEventTiming&&"interactionId"in PerformanceEventTiming.prototype&&w(()=>{de();let t,r=u("INP"),n=O(e,B),c=s=>{ee(()=>{for(let l of s)n.h(l);let o=n.P();o&&o.T!==r.value&&(r.value=o.T,r.entries=o.entries,t())})},a=m("event",c,{durationThreshold:e.durationThreshold??40});t=d(i,r,j,e.reportAllChanges),a&&(a.observe({type:"first-input",buffered:!0}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(a.takeRecords()),t(!0))}),g(()=>{n.p(),r=u("INP"),t=d(i,r,j,e.reportAllChanges)}))})},L=class{constructor(){h(this,"m")}h(e){this.m?.(e)}},q=[2500,4e3],ie=(i,e={})=>{w(()=>{let t=Y(),r,n=u("LCP"),c=O(e,L),a=o=>{e.reportAllChanges||(o=o.slice(-1));for(let l of o)c.h(l),l.startTime<t.firstHiddenTime&&(n.value=Math.max(l.startTime-f(),0),n.entries=[l],r())},s=m("largest-contentful-paint",a);if(s){r=d(i,n,q,e.reportAllChanges);let o=U(()=>{a(s.takeRecords()),s.disconnect(),r(!0)});for(let l of["keydown","click","visibilitychange"])addEventListener(l,()=>ee(o),{capture:!0,once:!0});g(l=>{n=u("LCP"),r=d(i,n,q,e.reportAllChanges),_(()=>{n.value=performance.now()-l.timeStamp,r(!0)})})}})},G=[800,1800],M=i=>{document.prerendering?w(()=>M(i)):document.readyState!=="complete"?addEventListener("load",()=>M(i),!0):setTimeout(i)},re=(i,e={})=>{let t=u("TTFB"),r=d(i,t,G,e.reportAllChanges);M(()=>{let n=D();n&&(t.value=Math.max(n.responseStart-f(),0),t.entries=[n],r(!0),g(()=>{t=u("TTFB",0),r=d(i,t,G,e.reportAllChanges),r(!0)}))})};var S=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{ie(this.collectMetric.bind(this)),X(this.collectMetric.bind(this)),te(this.collectMetric.bind(this)),N(this.collectMetric.bind(this)),re(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(n=>n!==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}}};(function(){let i=document.currentScript;if(!i){console.error("Could not find current script tag");return}if(window.__RYBBIT_OPTOUT__||localStorage.getItem("disable-rybbit")!==null){window.rybbit={pageview:()=>{},event:()=>{},error:()=>{},trackOutbound:()=>{},identify:()=>{},clearUserId:()=>{},getUserId:()=>null,startSessionReplay:()=>{},stopSessionReplay:()=>{},isSessionReplayActive:()=>!1};return}let e=W(i);if(!e)return;let t=new v(e);e.enableWebVitals&&new S(s=>{t.trackWebVitals(s)}).initialize(),e.trackErrors&&(window.addEventListener("error",a=>{t.trackError(a.error||new Error(a.message),{filename:a.filename,lineno:a.lineno,colno:a.colno})}),window.addEventListener("unhandledrejection",a=>{let s=a.reason instanceof Error?a.reason:new Error(String(a.reason));t.trackError(s,{type:"unhandledrejection"})}));let r=()=>t.trackPageview(),n=e.debounceDuration>0?x(r,e.debounceDuration):r;function c(){if(document.addEventListener("click",function(a){let s=a.target;for(;s&&s!==document.documentElement;){if(s.hasAttribute("data-rybbit-event")){let o=s.getAttribute("data-rybbit-event");if(o){let l={};for(let T of s.attributes)if(T.name.startsWith("data-rybbit-prop-")){let ne=T.name.replace("data-rybbit-prop-","");l[ne]=T.value}t.trackEvent(o,l)}break}s=s.parentElement}if(e.trackOutbound){let o=a.target.closest("a");o?.href&&F(o.href)&&t.trackOutbound(o.href,o.innerText||o.textContent||"",o.target||"_self")}}),e.autoTrackSpa){let a=history.pushState,s=history.replaceState;history.pushState=function(...o){a.apply(this,o),n(),t.onPageChange()},history.replaceState=function(...o){s.apply(this,o),n(),t.onPageChange()},window.addEventListener("popstate",()=>{n(),t.onPageChange()}),window.addEventListener("hashchange",()=>{n(),t.onPageChange()})}}window.rybbit={pageview:()=>t.trackPageview(),event:(a,s={})=>t.trackEvent(a,s),error:(a,s={})=>t.trackError(a,s),trackOutbound:(a,s="",o="_self")=>t.trackOutbound(a,s,o),identify:a=>t.identify(a),clearUserId:()=>t.clearUserId(),getUserId:()=>t.getUserId(),startSessionReplay:()=>t.startSessionReplay(),stopSessionReplay:()=>t.stopSessionReplay(),isSessionReplayActive:()=>t.isSessionReplayActive()},c(),window.addEventListener("beforeunload",()=>{t.cleanup()}),e.autoTrackPageview&&t.trackPageview()})();})();diff --git a/server/src/api/sessionReplay/recordSessionReplay.ts b/server/src/api/sessionReplay/recordSessionReplay.tsindex 2ce2a0be0..a094de97a 100644--- a/server/src/api/sessionReplay/recordSessionReplay.ts+++ b/server/src/api/sessionReplay/recordSessionReplay.ts@@ -2,7 +2,7 @@ import { FastifyReply, FastifyRequest } from "fastify";import { z } from "zod";import { siteConfig } from "../../lib/siteConfig.js";import { SessionReplayIngestService } from "../../services/replay/sessionReplayIngestService.js";-import { validateApiKey, validateOrigin } from "../../services/shared/requestValidation.js";+import { validateApiKey } from "../../services/shared/requestValidation.js";import { usageService } from "../../services/usageService.js";import { RecordSessionReplayRequest } from "../../types/sessionReplay.js";import { getIpAddress } from "../../utils.js";@@ -73,26 +73,23 @@ export async function recordSessionReplay(// }// }- // If no valid API key, validate origin- if (!apiKeyValidation.success) {- const originValidation = await validateOrigin(siteId, request.headers.origin as string);+ // If no valid API key, validate origin - disabled for now+ // if (!apiKeyValidation.success) {+ // const originValidation = await validateOrigin(siteId, request.headers.origin as string);- if (!originValidation.success) {- logger.warn(`[SessionReplay] Request rejected for site ${siteId}: ${originValidation.error}`);- return reply.status(403).send({- success: false,- error: originValidation.error,- });- }- }-- // Make sure the site config is loaded- await siteConfig.ensureInitialized();+ // if (!originValidation.success) {+ // logger.warn(`[SessionReplay] Request rejected for site ${siteId}: ${originValidation.error}`);+ // return reply.status(403).send({+ // success: false,+ // error: originValidation.error,+ // });+ // }+ // }// Check if the IP should be excluded from trackingconst requestIP = getIpAddress(request);- if (siteConfig.isIPExcluded(requestIP, siteId)) {+ if (await siteConfig.isIPExcluded(requestIP, siteId)) {logger.info(`[SessionReplay] IP ${requestIP} excluded from tracking for site ${siteId}`);return reply.status(200).send({success: true,diff --git a/server/src/api/sites/addSite.ts b/server/src/api/sites/addSite.tsindex de2d1cd8b..5681f58cc 100644--- a/server/src/api/sites/addSite.ts+++ b/server/src/api/sites/addSite.ts@@ -1,4 +1,5 @@import { FastifyReply, FastifyRequest } from "fastify";+import { randomBytes } from "crypto";import { db } from "../../db/postgres/postgres.js";import { sites } from "../../db/postgres/schema.js";import { loadAllowedDomains } from "../../lib/allowedDomains.js";@@ -65,10 +66,14 @@ export async function addSite(});}+ // Generate a random 12-character hex ID+ const id = randomBytes(6).toString('hex');+// Create the new siteconst newSite = await db.insert(sites).values({+ id,domain,name,createdBy: session.user.id,@@ -82,15 +87,7 @@ export async function addSite(// Update allowed domainsawait loadAllowedDomains();- // Update siteConfig cache with the new site- siteConfig.addSite(newSite[0].siteId, {- public: newSite[0].public || false,- saltUserIds: newSite[0].saltUserIds || false,- domain: newSite[0].domain,- blockBots: newSite[0].blockBots === undefined ? true : newSite[0].blockBots,- excludedIPs: Array.isArray(newSite[0].excludedIPs) ? newSite[0].excludedIPs : [],- apiKey: newSite[0].apiKey,- });+ // No need to update cache as we're querying directly nowreturn reply.status(201).send(newSite[0]);} catch (error) {diff --git a/server/src/api/sites/getSite.ts b/server/src/api/sites/getSite.tsindex e82e58a39..7e4deb6be 100644--- a/server/src/api/sites/getSite.ts+++ b/server/src/api/sites/getSite.ts@@ -34,6 +34,7 @@ export async function getSite(request: FastifyRequest<GetSiteParams>, reply: Fas}return reply.status(200).send({+ id: site.id,siteId: site.siteId,name: site.name,domain: site.domain,diff --git a/server/src/api/sites/getSiteIsPublic.ts b/server/src/api/sites/getSiteIsPublic.tsindex a93617c9e..8a283b16b 100644--- a/server/src/api/sites/getSiteIsPublic.ts+++ b/server/src/api/sites/getSiteIsPublic.ts@@ -3,6 +3,6 @@ import { siteConfig } from "../../lib/siteConfig.js";export async function getSiteIsPublic(request: FastifyRequest<{ Params: { site: string } }>, reply: FastifyReply) {const { site } = request.params;- const isPublic = siteConfig.isSitePublic(site);+ const isPublic = await siteConfig.isSitePublic(site);return reply.status(200).send({ isPublic });}diff --git a/server/src/api/uptime/createMonitor.ts b/server/src/api/uptime/createMonitor.tsindex 30417d704..0293721bf 100644--- a/server/src/api/uptime/createMonitor.ts+++ b/server/src/api/uptime/createMonitor.ts@@ -1,8 +1,7 @@import { and, eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { db } from "../../db/postgres/postgres.js";-import { member } from "../../db/postgres/schema.js";-import { uptimeMonitors, uptimeMonitorStatus } from "../../db/postgres/uptimeSchema.js";+import { uptimeMonitors, uptimeMonitorStatus, member } from "../../db/postgres/schema.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { uptimeService } from "../../services/uptime/uptimeService.js";import { createMonitorSchema, type CreateMonitorInput } from "./schemas.js";diff --git a/server/src/api/uptime/deleteMonitor.ts b/server/src/api/uptime/deleteMonitor.tsindex 106e35f26..fad19b84c 100644--- a/server/src/api/uptime/deleteMonitor.ts+++ b/server/src/api/uptime/deleteMonitor.ts@@ -1,8 +1,7 @@import { and, eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { db } from "../../db/postgres/postgres.js";-import { member } from "../../db/postgres/schema.js";-import { uptimeMonitors, uptimeMonitorStatus } from "../../db/postgres/uptimeSchema.js";+import { uptimeMonitors, uptimeMonitorStatus, member } from "../../db/postgres/schema.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { uptimeService } from "../../services/uptime/uptimeService.js";diff --git a/server/src/api/uptime/getMonitor.ts b/server/src/api/uptime/getMonitor.tsindex afcc8db5c..6ca696b8a 100644--- a/server/src/api/uptime/getMonitor.ts+++ b/server/src/api/uptime/getMonitor.ts@@ -1,8 +1,7 @@import { and, eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { db } from "../../db/postgres/postgres.js";-import { member } from "../../db/postgres/schema.js";-import { uptimeMonitors, uptimeMonitorStatus } from "../../db/postgres/uptimeSchema.js";+import { uptimeMonitors, uptimeMonitorStatus, member } from "../../db/postgres/schema.js";import { getSessionFromReq } from "../../lib/auth-utils.js";interface GetMonitorParams {diff --git a/server/src/api/uptime/getMonitorEvents.ts b/server/src/api/uptime/getMonitorEvents.tsindex 53ec59a55..136c72366 100644--- a/server/src/api/uptime/getMonitorEvents.ts+++ b/server/src/api/uptime/getMonitorEvents.ts@@ -1,8 +1,7 @@import { and, eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { db } from "../../db/postgres/postgres.js";-import { member } from "../../db/postgres/schema.js";-import { uptimeMonitors } from "../../db/postgres/uptimeSchema.js";+import { uptimeMonitors, member } from "../../db/postgres/schema.js";import { clickhouse } from "../../db/clickhouse/clickhouse.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { processResults } from "../analytics/utils.js";diff --git a/server/src/api/uptime/getMonitorStats.ts b/server/src/api/uptime/getMonitorStats.tsindex a0668620a..ad9dff6a5 100644--- a/server/src/api/uptime/getMonitorStats.ts+++ b/server/src/api/uptime/getMonitorStats.ts@@ -2,8 +2,7 @@ import { and, eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { clickhouse } from "../../db/clickhouse/clickhouse.js";import { db } from "../../db/postgres/postgres.js";-import { member } from "../../db/postgres/schema.js";-import { uptimeMonitors } from "../../db/postgres/uptimeSchema.js";+import { member, uptimeMonitors } from "../../db/postgres/schema.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { processResults, TimeBucketToFn } from "../analytics/utils.js";import { getMonitorStatsQuerySchema, type GetMonitorStatsQuery } from "./schemas.js";diff --git a/server/src/api/uptime/getMonitorStatus.ts b/server/src/api/uptime/getMonitorStatus.tsindex 428997790..1e2eefe02 100644--- a/server/src/api/uptime/getMonitorStatus.ts+++ b/server/src/api/uptime/getMonitorStatus.ts@@ -1,8 +1,7 @@import { and, eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { db } from "../../db/postgres/postgres.js";-import { member } from "../../db/postgres/schema.js";-import { uptimeMonitors, uptimeMonitorStatus } from "../../db/postgres/uptimeSchema.js";+import { uptimeMonitors, uptimeMonitorStatus, member } from "../../db/postgres/schema.js";import { clickhouse } from "../../db/clickhouse/clickhouse.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { processResults } from "../analytics/utils.js";diff --git a/server/src/api/uptime/getMonitorUptime.ts b/server/src/api/uptime/getMonitorUptime.tsindex 318131ef2..5d71898c7 100644--- a/server/src/api/uptime/getMonitorUptime.ts+++ b/server/src/api/uptime/getMonitorUptime.ts@@ -1,8 +1,7 @@import { and, eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { db } from "../../db/postgres/postgres.js";-import { member } from "../../db/postgres/schema.js";-import { uptimeMonitors } from "../../db/postgres/uptimeSchema.js";+import { uptimeMonitors, member } from "../../db/postgres/schema.js";import { clickhouse } from "../../db/clickhouse/clickhouse.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { processResults } from "../analytics/utils.js";diff --git a/server/src/api/uptime/getMonitorUptimeBuckets.ts b/server/src/api/uptime/getMonitorUptimeBuckets.tsindex bf23decfd..8cf898f20 100644--- a/server/src/api/uptime/getMonitorUptimeBuckets.ts+++ b/server/src/api/uptime/getMonitorUptimeBuckets.ts@@ -3,8 +3,7 @@ import { FastifyReply, FastifyRequest } from "fastify";import { z } from "zod";import { clickhouse } from "../../db/clickhouse/clickhouse.js";import { db } from "../../db/postgres/postgres.js";-import { member } from "../../db/postgres/schema.js";-import { uptimeMonitors } from "../../db/postgres/uptimeSchema.js";+import { member, uptimeMonitors } from "../../db/postgres/schema.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { processResults } from "../analytics/utils.js";diff --git a/server/src/api/uptime/getMonitors.ts b/server/src/api/uptime/getMonitors.tsindex 1c437b723..0a30d0ca9 100644--- a/server/src/api/uptime/getMonitors.ts+++ b/server/src/api/uptime/getMonitors.ts@@ -2,8 +2,7 @@ import { and, eq, inArray, desc } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { DateTime } from "luxon";import { db } from "../../db/postgres/postgres.js";-import { member } from "../../db/postgres/schema.js";-import { uptimeMonitors, uptimeMonitorStatus } from "../../db/postgres/uptimeSchema.js";+import { uptimeMonitors, uptimeMonitorStatus, member } from "../../db/postgres/schema.js";import { clickhouse } from "../../db/clickhouse/clickhouse.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { processResults } from "../analytics/utils.js";diff --git a/server/src/api/uptime/getRegions.ts b/server/src/api/uptime/getRegions.tsindex c95a95528..6cb249ebc 100644--- a/server/src/api/uptime/getRegions.ts+++ b/server/src/api/uptime/getRegions.ts@@ -1,7 +1,7 @@import { eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { db } from "../../db/postgres/postgres.js";-import { agentRegions } from "../../db/postgres/uptimeSchema.js";+import { agentRegions } from "../../db/postgres/schema.js";import { getSessionFromReq } from "../../lib/auth-utils.js";export async function getRegions(request: FastifyRequest, reply: FastifyReply) {diff --git a/server/src/api/uptime/incidents.ts b/server/src/api/uptime/incidents.tsindex d79416a4f..9d0a01400 100644--- a/server/src/api/uptime/incidents.ts+++ b/server/src/api/uptime/incidents.ts@@ -2,7 +2,7 @@ import { and, desc, eq, inArray, sql } from "drizzle-orm";import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";import { z } from "zod";import { db } from "../../db/postgres/postgres.js";-import { uptimeIncidents, uptimeMonitors } from "../../db/postgres/uptimeSchema.js";+import { uptimeIncidents, uptimeMonitors } from "../../db/postgres/schema.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { getUserOrganizations } from "./utils.js";diff --git a/server/src/api/uptime/notifications.ts b/server/src/api/uptime/notifications.tsindex 3e1116401..bff870465 100644--- a/server/src/api/uptime/notifications.ts+++ b/server/src/api/uptime/notifications.ts@@ -3,7 +3,7 @@ import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";import { DateTime } from "luxon";import { z } from "zod";import { db } from "../../db/postgres/postgres.js";-import { notificationChannels } from "../../db/postgres/uptimeSchema.js";+import { notificationChannels } from "../../db/postgres/schema.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { NotificationService } from "../../services/uptime/notificationService.js";import { getUserOrganizations } from "./utils.js";diff --git a/server/src/api/uptime/updateMonitor.ts b/server/src/api/uptime/updateMonitor.tsindex e84de1d23..8b6495b13 100644--- a/server/src/api/uptime/updateMonitor.ts+++ b/server/src/api/uptime/updateMonitor.ts@@ -1,8 +1,7 @@import { and, eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { db } from "../../db/postgres/postgres.js";-import { member } from "../../db/postgres/schema.js";-import { uptimeMonitors } from "../../db/postgres/uptimeSchema.js";+import { uptimeMonitors, member } from "../../db/postgres/schema.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { uptimeService } from "../../services/uptime/uptimeService.js";import { updateMonitorSchema, type UpdateMonitorInput } from "./schemas.js";diff --git a/server/src/db/postgres/postgres.ts b/server/src/db/postgres/postgres.tsindex a813d2940..72a8f76e8 100644--- a/server/src/db/postgres/postgres.ts+++ b/server/src/db/postgres/postgres.ts@@ -2,7 +2,6 @@ import dotenv from "dotenv";import { drizzle } from "drizzle-orm/postgres-js";import postgres from "postgres";import * as schema from "./schema.js";-import * as uptimeSchema from "./uptimeSchema.js";dotenv.config();@@ -18,7 +17,7 @@ const client = postgres({});// Create drizzle ORM instance-export const db = drizzle(client, { schema: { ...schema, ...uptimeSchema } });+export const db = drizzle(client, { schema });// For compatibility with raw SQL if neededexport const sql = client;diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.tsindex 4cdfcae93..d2008bd44 100644--- a/server/src/db/postgres/schema.ts+++ b/server/src/db/postgres/schema.ts@@ -1,18 +1,18 @@+import { sql } from "drizzle-orm";import {boolean,+ check,+ foreignKey,+ index,integer,jsonb,pgTable,+ real,serial,text,timestamp,- foreignKey,unique,- real,- check,- index,} from "drizzle-orm/pg-core";-import { sql } from "drizzle-orm";// User tableexport const user = pgTable(@@ -51,6 +51,8 @@ export const verification = pgTable("verification", {export const sites = pgTable("sites",{+ id: text("id").$defaultFn(() => sql`encode(gen_random_bytes(6), 'hex')`),+ // deprecated - keeping as primary key for backwards compatibilitysiteId: serial("site_id").primaryKey().notNull(),name: text("name").notNull(),domain: text("domain").notNull(),@@ -264,3 +266,321 @@ export const telemetry = pgTable("telemetry", {tableCounts: jsonb("table_counts").notNull().$type<Record<string, number>>(),clickhouseSizeGb: real("clickhouse_size_gb").notNull(),});++// Uptime monitor definitions+export const uptimeMonitors = pgTable(+ "uptime_monitors",+ {+ id: serial("id").primaryKey().notNull(),+ organizationId: text("organization_id")+ .notNull()+ .references(() => organization.id),+ name: text("name"),+ monitorType: text("monitor_type").notNull(), // 'http', 'tcp'++ // Common settings+ intervalSeconds: integer("interval_seconds").notNull(),+ enabled: boolean("enabled").default(true),++ // HTTP/HTTPS specific configuration+ httpConfig: jsonb("http_config").$type<{+ url: string;+ method: "GET" | "POST" | "PUT" | "DELETE" | "HEAD" | "OPTIONS" | "PATCH";+ headers?: Record<string, string>;+ body?: string;+ auth?: {+ type: "none" | "basic" | "bearer" | "api_key" | "custom_header";+ credentials?: {+ username?: string;+ password?: string;+ token?: string;+ headerName?: string;+ headerValue?: string;+ };+ };+ followRedirects?: boolean;+ timeoutMs?: number;+ ipVersion?: "any" | "ipv4" | "ipv6";+ userAgent?: string;+ }>(),++ // TCP specific configuration+ tcpConfig: jsonb("tcp_config").$type<{+ host: string;+ port: number;+ timeoutMs?: number;+ }>(),++ // Validation rules+ validationRules: jsonb("validation_rules").notNull().default([]).$type<+ Array<+ | {+ type: "status_code";+ operator: "equals" | "not_equals" | "in" | "not_in";+ value: number | number[];+ }+ | {+ type: "response_time";+ operator: "less_than" | "greater_than";+ value: number;+ }+ | {+ type: "response_body_contains" | "response_body_not_contains";+ value: string;+ caseSensitive?: boolean;+ }+ | {+ type: "header_exists";+ header: string;+ }+ | {+ type: "header_value";+ header: string;+ operator: "equals" | "contains";+ value: string;+ }+ | {+ type: "response_size";+ operator: "less_than" | "greater_than";+ value: number;+ }+ >+ >(),++ // Multi-region configuration+ monitoringType: text("monitoring_type").default("local"), // 'local' or 'global'+ selectedRegions: jsonb("selected_regions").default(["local"]).$type<string[]>(),++ // Metadata+ createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),+ updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),+ createdBy: text("created_by")+ .notNull()+ .references(() => user.id),+ },+ table => [+ foreignKey({+ columns: [table.organizationId],+ foreignColumns: [organization.id],+ name: "uptime_monitors_organization_id_organization_id_fk",+ }),+ foreignKey({+ columns: [table.createdBy],+ foreignColumns: [user.id],+ name: "uptime_monitors_created_by_user_id_fk",+ }),+ ]+);++// Monitor status tracking+export const uptimeMonitorStatus = pgTable(+ "uptime_monitor_status",+ {+ monitorId: integer("monitor_id")+ .primaryKey()+ .notNull()+ .references(() => uptimeMonitors.id, { onDelete: "cascade" }),+ lastCheckedAt: timestamp("last_checked_at", { mode: "string" }),+ nextCheckAt: timestamp("next_check_at", { mode: "string" }),+ currentStatus: text("current_status").default("unknown"), // 'up', 'down', 'unknown'+ consecutiveFailures: integer("consecutive_failures").default(0),+ consecutiveSuccesses: integer("consecutive_successes").default(0),+ uptimePercentage24h: real("uptime_percentage_24h"),+ uptimePercentage7d: real("uptime_percentage_7d"),+ uptimePercentage30d: real("uptime_percentage_30d"),+ averageResponseTime24h: real("average_response_time_24h"),+ updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),+ },+ table => [+ foreignKey({+ columns: [table.monitorId],+ foreignColumns: [uptimeMonitors.id],+ name: "uptime_monitor_status_monitor_id_uptime_monitors_id_fk",+ }),+ check("uptime_monitor_status_current_status_check", sql`current_status IN ('up', 'down', 'unknown')`),+ check("uptime_monitor_status_uptime_24h_check", sql`uptime_percentage_24h >= 0 AND uptime_percentage_24h <= 100`),+ check("uptime_monitor_status_uptime_7d_check", sql`uptime_percentage_7d >= 0 AND uptime_percentage_7d <= 100`),+ check("uptime_monitor_status_uptime_30d_check", sql`uptime_percentage_30d >= 0 AND uptime_percentage_30d <= 100`),+ index("uptime_monitor_status_updated_at_idx").on(table.updatedAt),+ ]+);++// Alert configuration (scaffolding)+export const uptimeAlerts = pgTable(+ "uptime_alerts",+ {+ id: serial("id").primaryKey().notNull(),+ monitorId: integer("monitor_id")+ .notNull()+ .references(() => uptimeMonitors.id, { onDelete: "cascade" }),+ alertType: text("alert_type").notNull(), // 'email', 'webhook', 'slack', etc.+ alertConfig: jsonb("alert_config").notNull(), // Type-specific configuration+ conditions: jsonb("conditions").notNull().$type<{+ consecutiveFailures?: number;+ responseTimeThresholdMs?: number;+ uptimePercentageThreshold?: number;+ }>(),+ enabled: boolean("enabled").default(true),+ createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),+ },+ table => [+ foreignKey({+ columns: [table.monitorId],+ foreignColumns: [uptimeMonitors.id],+ name: "uptime_alerts_monitor_id_uptime_monitors_id_fk",+ }),+ ]+);++// Alert history (scaffolding)+export const uptimeAlertHistory = pgTable(+ "uptime_alert_history",+ {+ id: serial("id").primaryKey().notNull(),+ alertId: integer("alert_id")+ .notNull()+ .references(() => uptimeAlerts.id, { onDelete: "cascade" }),+ monitorId: integer("monitor_id")+ .notNull()+ .references(() => uptimeMonitors.id, { onDelete: "cascade" }),+ triggeredAt: timestamp("triggered_at", { mode: "string" }).defaultNow(),+ resolvedAt: timestamp("resolved_at", { mode: "string" }),+ alertData: jsonb("alert_data"), // Context about what triggered the alert+ },+ table => [+ foreignKey({+ columns: [table.alertId],+ foreignColumns: [uptimeAlerts.id],+ name: "uptime_alert_history_alert_id_uptime_alerts_id_fk",+ }),+ foreignKey({+ columns: [table.monitorId],+ foreignColumns: [uptimeMonitors.id],+ name: "uptime_alert_history_monitor_id_uptime_monitors_id_fk",+ }),+ ]+);++// Agent regions for VPS-based monitoring+export const agentRegions = pgTable("agent_regions", {+ code: text("code").primaryKey().notNull(), // Region code (e.g., 'us-east', 'europe')+ name: text("name").notNull(), // Region display name+ endpointUrl: text("endpoint_url").notNull(), // Agent endpoint URL+ enabled: boolean("enabled").default(true),+ lastHealthCheck: timestamp("last_health_check", { mode: "string" }),+ isHealthy: boolean("is_healthy").default(true),+});++// Uptime incidents table+export const uptimeIncidents = pgTable(+ "uptime_incidents",+ {+ id: serial("id").primaryKey().notNull(),+ organizationId: text("organization_id")+ .notNull()+ .references(() => organization.id),+ monitorId: integer("monitor_id")+ .notNull()+ .references(() => uptimeMonitors.id, { onDelete: "cascade" }),+ region: text("region"), // Region where incident occurred++ // Incident timing+ startTime: timestamp("start_time", { mode: "string" }).notNull(),+ endTime: timestamp("end_time", { mode: "string" }), // null if ongoing++ // Status+ status: text("status").notNull().default("active"), // 'active', 'acknowledged', 'resolved'++ // Acknowledgement details+ acknowledgedBy: text("acknowledged_by").references(() => user.id),+ acknowledgedAt: timestamp("acknowledged_at", { mode: "string" }),++ // Resolution details+ resolvedBy: text("resolved_by").references(() => user.id),+ resolvedAt: timestamp("resolved_at", { mode: "string" }),++ // Error details+ lastError: text("last_error"),+ lastErrorType: text("last_error_type"),+ failureCount: integer("failure_count").default(1),+ createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),+ updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),+ },+ table => [+ foreignKey({+ columns: [table.organizationId],+ foreignColumns: [organization.id],+ name: "uptime_incidents_organization_id_organization_id_fk",+ }),+ foreignKey({+ columns: [table.monitorId],+ foreignColumns: [uptimeMonitors.id],+ name: "uptime_incidents_monitor_id_uptime_monitors_id_fk",+ }),+ foreignKey({+ columns: [table.acknowledgedBy],+ foreignColumns: [user.id],+ name: "uptime_incidents_acknowledged_by_user_id_fk",+ }),+ foreignKey({+ columns: [table.resolvedBy],+ foreignColumns: [user.id],+ name: "uptime_incidents_resolved_by_user_id_fk",+ }),+ ]+);++// Notification channels table+export const notificationChannels = pgTable(+ "notification_channels",+ {+ id: serial("id").primaryKey().notNull(),+ organizationId: text("organization_id")+ .notNull()+ .references(() => organization.id),+ type: text("type").notNull(), // 'email', 'discord', 'slack', 'sms'+ name: text("name").notNull(),+ enabled: boolean("enabled").default(true),++ // Channel-specific configuration+ config: jsonb("config").notNull().$type<{+ // Email config+ email?: string;++ // Discord config+ webhookUrl?: string;++ // Slack config+ slackWebhookUrl?: string;+ slackChannel?: string;++ // SMS config (placeholder)+ phoneNumber?: string;+ provider?: string;+ }>(),++ // Monitor selection and notification settings+ monitorIds: jsonb("monitor_ids").$type<number[] | null>(), // null = all monitors+ triggerEvents: jsonb("trigger_events").notNull().default(["down", "recovery"]).$type<string[]>(), // 'down', 'recovery', 'degraded'+ cooldownMinutes: integer("cooldown_minutes").default(5), // Minimum time between notifications+ lastNotifiedAt: timestamp("last_notified_at", { mode: "string" }),++ createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),+ updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),+ createdBy: text("created_by")+ .notNull()+ .references(() => user.id),+ },+ table => [+ foreignKey({+ columns: [table.organizationId],+ foreignColumns: [organization.id],+ name: "notification_channels_organization_id_organization_id_fk",+ }),+ foreignKey({+ columns: [table.createdBy],+ foreignColumns: [user.id],+ name: "notification_channels_created_by_user_id_fk",+ }),+ ]+);diff --git a/server/src/db/postgres/uptimeSchema.ts b/server/src/db/postgres/uptimeSchema.tsdeleted file mode 100644index 71b884e88..000000000--- a/server/src/db/postgres/uptimeSchema.ts+++ /dev/null@@ -1,333 +0,0 @@-import {- boolean,- integer,- jsonb,- pgTable,- serial,- text,- timestamp,- foreignKey,- real,- check,- index,-} from "drizzle-orm/pg-core";-import { sql } from "drizzle-orm";-import { organization, user } from "./schema.js";--// Uptime monitor definitions-export const uptimeMonitors = pgTable(- "uptime_monitors",- {- id: serial("id").primaryKey().notNull(),- organizationId: text("organization_id")- .notNull()- .references(() => organization.id),- name: text("name"),- monitorType: text("monitor_type").notNull(), // 'http', 'tcp'-- // Common settings- intervalSeconds: integer("interval_seconds").notNull(),- enabled: boolean("enabled").default(true),-- // HTTP/HTTPS specific configuration- httpConfig: jsonb("http_config").$type<{- url: string;- method: "GET" | "POST" | "PUT" | "DELETE" | "HEAD" | "OPTIONS" | "PATCH";- headers?: Record<string, string>;- body?: string;- auth?: {- type: "none" | "basic" | "bearer" | "api_key" | "custom_header";- credentials?: {- username?: string;- password?: string;- token?: string;- headerName?: string;- headerValue?: string;- };- };- followRedirects?: boolean;- timeoutMs?: number;- ipVersion?: "any" | "ipv4" | "ipv6";- userAgent?: string;- }>(),-- // TCP specific configuration- tcpConfig: jsonb("tcp_config").$type<{- host: string;- port: number;- timeoutMs?: number;- }>(),-- // Validation rules- validationRules: jsonb("validation_rules").notNull().default([]).$type<- Array<- | {- type: "status_code";- operator: "equals" | "not_equals" | "in" | "not_in";- value: number | number[];- }- | {- type: "response_time";- operator: "less_than" | "greater_than";- value: number;- }- | {- type: "response_body_contains" | "response_body_not_contains";- value: string;- caseSensitive?: boolean;- }- | {- type: "header_exists";- header: string;- }- | {- type: "header_value";- header: string;- operator: "equals" | "contains";- value: string;- }- | {- type: "response_size";- operator: "less_than" | "greater_than";- value: number;- }- >- >(),-- // Multi-region configuration- monitoringType: text("monitoring_type").default("local"), // 'local' or 'global'- selectedRegions: jsonb("selected_regions").default(["local"]).$type<string[]>(),-- // Metadata- createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),- updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),- createdBy: text("created_by")- .notNull()- .references(() => user.id),- },- table => [- foreignKey({- columns: [table.organizationId],- foreignColumns: [organization.id],- name: "uptime_monitors_organization_id_organization_id_fk",- }),- foreignKey({- columns: [table.createdBy],- foreignColumns: [user.id],- name: "uptime_monitors_created_by_user_id_fk",- }),- ]-);--// Monitor status tracking-export const uptimeMonitorStatus = pgTable(- "uptime_monitor_status",- {- monitorId: integer("monitor_id")- .primaryKey()- .notNull()- .references(() => uptimeMonitors.id, { onDelete: "cascade" }),- lastCheckedAt: timestamp("last_checked_at", { mode: "string" }),- nextCheckAt: timestamp("next_check_at", { mode: "string" }),- currentStatus: text("current_status").default("unknown"), // 'up', 'down', 'unknown'- consecutiveFailures: integer("consecutive_failures").default(0),- consecutiveSuccesses: integer("consecutive_successes").default(0),- uptimePercentage24h: real("uptime_percentage_24h"),- uptimePercentage7d: real("uptime_percentage_7d"),- uptimePercentage30d: real("uptime_percentage_30d"),- averageResponseTime24h: real("average_response_time_24h"),- updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),- },- table => [- foreignKey({- columns: [table.monitorId],- foreignColumns: [uptimeMonitors.id],- name: "uptime_monitor_status_monitor_id_uptime_monitors_id_fk",- }),- check("uptime_monitor_status_current_status_check", sql`current_status IN ('up', 'down', 'unknown')`),- check("uptime_monitor_status_uptime_24h_check", sql`uptime_percentage_24h >= 0 AND uptime_percentage_24h <= 100`),- check("uptime_monitor_status_uptime_7d_check", sql`uptime_percentage_7d >= 0 AND uptime_percentage_7d <= 100`),- check("uptime_monitor_status_uptime_30d_check", sql`uptime_percentage_30d >= 0 AND uptime_percentage_30d <= 100`),- index("uptime_monitor_status_updated_at_idx").on(table.updatedAt),- ]-);--// Alert configuration (scaffolding)-export const uptimeAlerts = pgTable(- "uptime_alerts",- {- id: serial("id").primaryKey().notNull(),- monitorId: integer("monitor_id")- .notNull()- .references(() => uptimeMonitors.id, { onDelete: "cascade" }),- alertType: text("alert_type").notNull(), // 'email', 'webhook', 'slack', etc.- alertConfig: jsonb("alert_config").notNull(), // Type-specific configuration- conditions: jsonb("conditions").notNull().$type<{- consecutiveFailures?: number;- responseTimeThresholdMs?: number;- uptimePercentageThreshold?: number;- }>(),- enabled: boolean("enabled").default(true),- createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),- },- table => [- foreignKey({- columns: [table.monitorId],- foreignColumns: [uptimeMonitors.id],- name: "uptime_alerts_monitor_id_uptime_monitors_id_fk",- }),- ]-);--// Alert history (scaffolding)-export const uptimeAlertHistory = pgTable(- "uptime_alert_history",- {- id: serial("id").primaryKey().notNull(),- alertId: integer("alert_id")- .notNull()- .references(() => uptimeAlerts.id, { onDelete: "cascade" }),- monitorId: integer("monitor_id")- .notNull()- .references(() => uptimeMonitors.id, { onDelete: "cascade" }),- triggeredAt: timestamp("triggered_at", { mode: "string" }).defaultNow(),- resolvedAt: timestamp("resolved_at", { mode: "string" }),- alertData: jsonb("alert_data"), // Context about what triggered the alert- },- table => [- foreignKey({- columns: [table.alertId],- foreignColumns: [uptimeAlerts.id],- name: "uptime_alert_history_alert_id_uptime_alerts_id_fk",- }),- foreignKey({- columns: [table.monitorId],- foreignColumns: [uptimeMonitors.id],- name: "uptime_alert_history_monitor_id_uptime_monitors_id_fk",- }),- ]-);--// Agent regions for VPS-based monitoring-export const agentRegions = pgTable("agent_regions", {- code: text("code").primaryKey().notNull(), // Region code (e.g., 'us-east', 'europe')- name: text("name").notNull(), // Region display name- endpointUrl: text("endpoint_url").notNull(), // Agent endpoint URL- enabled: boolean("enabled").default(true),- lastHealthCheck: timestamp("last_health_check", { mode: "string" }),- isHealthy: boolean("is_healthy").default(true),-});--// Uptime incidents table-export const uptimeIncidents = pgTable(- "uptime_incidents",- {- id: serial("id").primaryKey().notNull(),- organizationId: text("organization_id")- .notNull()- .references(() => organization.id),- monitorId: integer("monitor_id")- .notNull()- .references(() => uptimeMonitors.id, { onDelete: "cascade" }),- region: text("region"), // Region where incident occurred-- // Incident timing- startTime: timestamp("start_time", { mode: "string" }).notNull(),- endTime: timestamp("end_time", { mode: "string" }), // null if ongoing-- // Status- status: text("status").notNull().default("active"), // 'active', 'acknowledged', 'resolved'-- // Acknowledgement details- acknowledgedBy: text("acknowledged_by").references(() => user.id),- acknowledgedAt: timestamp("acknowledged_at", { mode: "string" }),-- // Resolution details- resolvedBy: text("resolved_by").references(() => user.id),- resolvedAt: timestamp("resolved_at", { mode: "string" }),-- // Error details- lastError: text("last_error"),- lastErrorType: text("last_error_type"),- failureCount: integer("failure_count").default(1),- createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),- updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),- },- table => [- foreignKey({- columns: [table.organizationId],- foreignColumns: [organization.id],- name: "uptime_incidents_organization_id_organization_id_fk",- }),- foreignKey({- columns: [table.monitorId],- foreignColumns: [uptimeMonitors.id],- name: "uptime_incidents_monitor_id_uptime_monitors_id_fk",- }),- foreignKey({- columns: [table.acknowledgedBy],- foreignColumns: [user.id],- name: "uptime_incidents_acknowledged_by_user_id_fk",- }),- foreignKey({- columns: [table.resolvedBy],- foreignColumns: [user.id],- name: "uptime_incidents_resolved_by_user_id_fk",- }),- ]-);--// Notification channels table-export const notificationChannels = pgTable(- "notification_channels",- {- id: serial("id").primaryKey().notNull(),- organizationId: text("organization_id")- .notNull()- .references(() => organization.id),- type: text("type").notNull(), // 'email', 'discord', 'slack', 'sms'- name: text("name").notNull(),- enabled: boolean("enabled").default(true),-- // Channel-specific configuration- config: jsonb("config").notNull().$type<{- // Email config- email?: string;-- // Discord config- webhookUrl?: string;-- // Slack config- slackWebhookUrl?: string;- slackChannel?: string;-- // SMS config (placeholder)- phoneNumber?: string;- provider?: string;- }>(),-- // Monitor selection and notification settings- monitorIds: jsonb("monitor_ids").$type<number[] | null>(), // null = all monitors- triggerEvents: jsonb("trigger_events").notNull().default(["down", "recovery"]).$type<string[]>(), // 'down', 'recovery', 'degraded'- cooldownMinutes: integer("cooldown_minutes").default(5), // Minimum time between notifications- lastNotifiedAt: timestamp("last_notified_at", { mode: "string" }),-- createdAt: timestamp("created_at", { mode: "string" }).defaultNow(),- updatedAt: timestamp("updated_at", { mode: "string" }).defaultNow(),- createdBy: text("created_by")- .notNull()- .references(() => user.id),- },- table => [- foreignKey({- columns: [table.organizationId],- foreignColumns: [organization.id],- name: "notification_channels_organization_id_organization_id_fk",- }),- foreignKey({- columns: [table.createdBy],- foreignColumns: [user.id],- name: "notification_channels_created_by_user_id_fk",- }),- ]-);diff --git a/server/src/index.ts b/server/src/index.tsindex 92ea01069..8b028777b 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -412,7 +412,7 @@ server.get("/api/health", { logLevel: "silent" }, (_, reply) => reply.send("OK")const start = async () => {try {console.info("Starting server...");- await Promise.all([initializeClickhouse(), loadAllowedDomains(), siteConfig.loadSiteConfigs(), initPostgres()]);+ await Promise.all([initializeClickhouse(), loadAllowedDomains(), initPostgres()]);telemetryService.startTelemetryCron();diff --git a/server/src/lib/siteConfig.ts b/server/src/lib/siteConfig.tsindex 3e3c48313..d876e5857 100644--- a/server/src/lib/siteConfig.ts+++ b/server/src/lib/siteConfig.ts@@ -1,3 +1,4 @@+import { eq, or } from "drizzle-orm";import { db } from "../db/postgres/postgres.js";import { sites } from "../db/postgres/schema.js";import { logger } from "./logger/logger.js";@@ -5,6 +6,8 @@ import { matchesCIDR, matchesRange } from "./ipUtils.js";// Site configuration interfaceinterface SiteConfigData {+ id: string | null;+ siteId: number;public: boolean;saltUserIds: boolean;domain: string;@@ -14,13 +17,23 @@ interface SiteConfigData {}class SiteConfig {- private siteConfigMap: Map<number, SiteConfigData> = new Map();- private initialized: boolean = false;+ /**+ * Helper to determine if the input is a numeric siteId or string id+ */+ private isNumericId(id: string | number): boolean {+ return typeof id === "number" || /^\d+$/.test(id);+ }- async loadSiteConfigs() {+ /**+ * Get site by either siteId or id+ */+ private async getSiteByAnyId(siteIdOrId: string | number): Promise<SiteConfigData | undefined> {try {- const allSites = await db+ const isNumeric = this.isNumericId(siteIdOrId);++ const site = await db.select({+ id: sites.id,siteId: sites.siteId,public: sites.public,saltUserIds: sites.saltUserIds,@@ -29,54 +42,54 @@ class SiteConfig {excludedIPs: sites.excludedIPs,apiKey: sites.apiKey,})- .from(sites);-- // Reset the map- this.siteConfigMap.clear();-- // Populate the map with site IDs and their configuration- for (const site of allSites) {- this.siteConfigMap.set(site.siteId, {- public: site.public || false,- saltUserIds: site.saltUserIds || false,- domain: site.domain || "",- blockBots: site.blockBots === undefined ? true : site.blockBots,- excludedIPs: Array.isArray(site.excludedIPs) ? site.excludedIPs : [],- apiKey: site.apiKey,- });+ .from(sites)+ .where(isNumeric ? eq(sites.siteId, Number(siteIdOrId)) : eq(sites.id, String(siteIdOrId)))+ .limit(1);++ if (!site[0]) {+ return undefined;}- this.initialized = true;+ return {+ id: site[0].id,+ siteId: site[0].siteId,+ public: site[0].public || false,+ saltUserIds: site[0].saltUserIds || false,+ domain: site[0].domain || "",+ blockBots: site[0].blockBots === undefined ? true : site[0].blockBots,+ excludedIPs: Array.isArray(site[0].excludedIPs) ? site[0].excludedIPs : [],+ apiKey: site[0].apiKey,+ };} catch (error) {- console.error("Error loading site configurations:", error);- this.initialized = false;+ logger.error(error as Error, `Error fetching site configuration for ${siteIdOrId}`);+ return undefined;}}/**- * Check if a site is public without hitting the database+ * Check if a site is public*/- isSitePublic(siteId: string | number): boolean {- const numericSiteId = Number(siteId);- const config = this.siteConfigMap.get(numericSiteId);+ async isSitePublic(siteIdOrId?: string | number): Promise<boolean> {+ if (!siteIdOrId) return false;+ const config = await this.getSiteByAnyId(siteIdOrId);return config?.public || false;}/*** Check if a site has user ID salting enabled*/- shouldSaltUserIds(siteId: string | number): boolean {- const numericSiteId = Number(siteId);- const config = this.siteConfigMap.get(numericSiteId);+ async shouldSaltUserIds(siteIdOrId?: string | number): Promise<boolean> {+ if (!siteIdOrId) return false;+ const config = await this.getSiteByAnyId(siteIdOrId);return config?.saltUserIds || false;}/*** Check if a site has bot blocking enabled*/- shouldBlockBots(siteId: string | number): boolean {- const numericSiteId = Number(siteId);- const config = this.siteConfigMap.get(numericSiteId);+ async shouldBlockBots(siteIdOrId?: string | number): Promise<boolean> {+ if (!siteIdOrId) return true; // Default to blocking bots if no site specified+ const config = await this.getSiteByAnyId(siteIdOrId);// Default to true if configuration is not found (safeguard)return config?.blockBots !== false;}@@ -84,127 +97,165 @@ class SiteConfig {/*** Get the domain of a site*/- getSiteDomain(siteId: string | number): string {- const numericSiteId = Number(siteId);- const config = this.siteConfigMap.get(numericSiteId);+ async getSiteDomain(siteIdOrId?: string | number): Promise<string> {+ if (!siteIdOrId) return "";+ const config = await this.getSiteByAnyId(siteIdOrId);return config?.domain || "";}/*** Get the full site configuration*/- getSiteConfig(siteId: string | number): SiteConfigData | undefined {- const numericSiteId = Number(siteId);- return this.siteConfigMap.get(numericSiteId);+ async getSiteConfig(siteIdOrId?: string | number): Promise<SiteConfigData | undefined> {+ if (!siteIdOrId) return undefined;+ return this.getSiteByAnyId(siteIdOrId);}/**- * Update the public status of a site in the cache+ * Update the public status of a site*/- updateSitePublicStatus(siteId: number, isPublic: boolean): void {- const config = this.siteConfigMap.get(siteId);- if (!config) {- return;+ async updateSitePublicStatus(siteIdOrId: number | string, isPublic: boolean): Promise<void> {+ try {+ const isNumeric = this.isNumericId(siteIdOrId);++ await db+ .update(sites)+ .set({ public: isPublic })+ .where(isNumeric ? eq(sites.siteId, Number(siteIdOrId)) : eq(sites.id, String(siteIdOrId)));+ } catch (error) {+ logger.error(error as Error, `Error updating public status for site ${siteIdOrId}`);}- config.public = isPublic;- this.siteConfigMap.set(siteId, config);}/**- * Update the salt user IDs setting of a site in the cache+ * Update the salt user IDs setting of a site*/- updateSiteSaltSetting(siteId: number, saltUserIds: boolean): void {- const config = this.siteConfigMap.get(siteId);- if (!config) {- return;+ async updateSiteSaltSetting(siteIdOrId: number | string, saltUserIds: boolean): Promise<void> {+ try {+ const isNumeric = this.isNumericId(siteIdOrId);++ await db+ .update(sites)+ .set({ saltUserIds })+ .where(isNumeric ? eq(sites.siteId, Number(siteIdOrId)) : eq(sites.id, String(siteIdOrId)));+ } catch (error) {+ logger.error(error as Error, `Error updating salt setting for site ${siteIdOrId}`);}- config.saltUserIds = saltUserIds;- this.siteConfigMap.set(siteId, config);}/**- * Update the bot blocking setting of a site in the cache+ * Update the bot blocking setting of a site*/- updateSiteBlockBotsSetting(siteId: number, blockBots: boolean): void {- const config = this.siteConfigMap.get(siteId);- if (!config) {- return;+ async updateSiteBlockBotsSetting(siteIdOrId: number | string, blockBots: boolean): Promise<void> {+ try {+ const isNumeric = this.isNumericId(siteIdOrId);++ await db+ .update(sites)+ .set({ blockBots })+ .where(isNumeric ? eq(sites.siteId, Number(siteIdOrId)) : eq(sites.id, String(siteIdOrId)));+ } catch (error) {+ logger.error(error as Error, `Error updating block bots setting for site ${siteIdOrId}`);}- config.blockBots = blockBots;- this.siteConfigMap.set(siteId, config);}/**- * Update the domain of a site in the cache+ * Update the domain of a site*/- updateSiteDomain(siteId: number, domain: string): void {- const config = this.siteConfigMap.get(siteId);- if (!config) {- return;+ async updateSiteDomain(siteIdOrId: number | string, domain: string): Promise<void> {+ try {+ const isNumeric = this.isNumericId(siteIdOrId);++ await db+ .update(sites)+ .set({ domain })+ .where(isNumeric ? eq(sites.siteId, Number(siteIdOrId)) : eq(sites.id, String(siteIdOrId)));+ } catch (error) {+ logger.error(error as Error, `Error updating domain for site ${siteIdOrId}`);}- config.domain = domain;- this.siteConfigMap.set(siteId, config);}/**- * Update the API key of a site in the cache+ * Update the API key of a site*/- updateSiteApiKey(siteId: number, apiKey: string | null): void {- const config = this.siteConfigMap.get(siteId);- if (config) {- config.apiKey = apiKey;- this.siteConfigMap.set(siteId, config);+ async updateSiteApiKey(siteIdOrId: number | string, apiKey: string | null): Promise<void> {+ try {+ const isNumeric = this.isNumericId(siteIdOrId);++ await db+ .update(sites)+ .set({ apiKey })+ .where(isNumeric ? eq(sites.siteId, Number(siteIdOrId)) : eq(sites.id, String(siteIdOrId)));+ } catch (error) {+ logger.error(error as Error, `Error updating API key for site ${siteIdOrId}`);}}/*** Get excluded IPs for a site*/- getExcludedIPs(siteId: string | number): string[] {- const numericSiteId = Number(siteId);- const config = this.siteConfigMap.get(numericSiteId);+ async getExcludedIPs(siteIdOrId?: string | number): Promise<string[]> {+ if (!siteIdOrId) return [];+ const config = await this.getSiteByAnyId(siteIdOrId);return config?.excludedIPs || [];}/**- * Update the excluded IPs of a site in the cache+ * Update the excluded IPs of a site*/- updateSiteExcludedIPs(siteId: number, excludedIPs: string[]): void {- const config = this.siteConfigMap.get(siteId);- if (config) {- config.excludedIPs = excludedIPs;- this.siteConfigMap.set(siteId, config);+ async updateSiteExcludedIPs(siteIdOrId: number | string, excludedIPs: string[]): Promise<void> {+ try {+ const isNumeric = this.isNumericId(siteIdOrId);++ await db+ .update(sites)+ .set({ excludedIPs })+ .where(isNumeric ? eq(sites.siteId, Number(siteIdOrId)) : eq(sites.id, String(siteIdOrId)));+ } catch (error) {+ logger.error(error as Error, `Error updating excluded IPs for site ${siteIdOrId}`);}}/**- * Add a new site to the cache+ * Add a new site*/- addSite(siteId: number, config: SiteConfigData): void {- this.siteConfigMap.set(siteId, config);+ async addSite(config: Omit<SiteConfigData, "siteId">): Promise<void> {+ try {+ await db.insert(sites).values({+ id: config.id,+ name: "", // This would need to be provided+ domain: config.domain,+ public: config.public,+ saltUserIds: config.saltUserIds,+ blockBots: config.blockBots,+ excludedIPs: config.excludedIPs,+ apiKey: config.apiKey,+ createdBy: "", // This would need to be provided+ });+ } catch (error) {+ logger.error(error as Error, `Error adding site`);+ }}/**- * Remove a site from the cache+ * Remove a site*/- removeSite(siteId: number): void {- this.siteConfigMap.delete(siteId);- }+ async removeSite(siteIdOrId: number | string): Promise<void> {+ try {+ const isNumeric = this.isNumericId(siteIdOrId);- /**- * Ensure the cache is initialized- */- async ensureInitialized() {- if (!this.initialized) {- await this.loadSiteConfigs();+ await db.delete(sites).where(isNumeric ? eq(sites.siteId, Number(siteIdOrId)) : eq(sites.id, String(siteIdOrId)));+ } catch (error) {+ logger.error(error as Error, `Error removing site ${siteIdOrId}`);}}/*** Check if an IP address matches any of the excluded IPs/ranges*/- isIPExcluded(ipAddress: string, siteId: string | number): boolean {- const excludedIPs = this.getExcludedIPs(siteId);+ async isIPExcluded(ipAddress: string, siteIdOrId?: string | number): Promise<boolean> {+ if (!siteIdOrId) return false; // If no site specified, don't exclude any IPs+ const excludedIPs = await this.getExcludedIPs(siteIdOrId);if (!excludedIPs || excludedIPs.length === 0) {return false;}diff --git a/server/src/services/replay/sessionReplayIngestService.ts b/server/src/services/replay/sessionReplayIngestService.tsindex d1a18df0f..352efa94d 100644--- a/server/src/services/replay/sessionReplayIngestService.ts+++ b/server/src/services/replay/sessionReplayIngestService.ts@@ -30,7 +30,7 @@ export class SessionReplayIngestService {const userId =clientUserId && clientUserId.trim()? clientUserId.trim()- : userIdService.generateUserId(requestMeta?.ipAddress || "", requestMeta?.userAgent || "", siteId);+ : await userIdService.generateUserId(requestMeta?.ipAddress || "", requestMeta?.userAgent || "", siteId);// Get or create a session ID from the sessions serviceconst { sessionId } = await sessionsService.updateSession({diff --git a/server/src/services/shared/requestValidation.test.ts b/server/src/services/shared/requestValidation.test.tsindex 250225d82..497047b32 100644--- a/server/src/services/shared/requestValidation.test.ts+++ b/server/src/services/shared/requestValidation.test.ts@@ -2,9 +2,10 @@ import { describe, it, expect, vi, beforeEach } from "vitest";// Define the expected site config type to match SiteConfigDatainterface SiteConfigData {- id: number;+ id: string;+ siteId: number;domain: string;- apiKey?: string;+ apiKey?: string | null;public: boolean;saltUserIds: boolean;blockBots: boolean;@@ -20,7 +21,7 @@ vi.mock("../../lib/rateLimiter.js", () => ({vi.mock("../../lib/siteConfig.js", () => ({siteConfig: {- ensureInitialized: vi.fn(),+getSiteConfig: vi.fn(),},}));@@ -52,19 +53,20 @@ describe("validateApiKey", () => {});it("should return success false when site is not found", async () => {- vi.mocked(siteConfig.ensureInitialized).mockResolvedValue(undefined);+vi.mocked(siteConfig.getSiteConfig).mockResolvedValue(undefined);const result = await validateApiKey(1, "test-api-key");- expect(siteConfig.ensureInitialized).toHaveBeenCalled();+expect(siteConfig.getSiteConfig).toHaveBeenCalledWith(1);expect(result).toEqual({ success: false, error: "Site not found" });});it("should return success true when API key matches", async () => {const mockSite: SiteConfigData = {- id: 1,+ id: "test-id",+ siteId: 1,apiKey: "valid-api-key",domain: "example.com",public: true,@@ -72,7 +74,7 @@ describe("validateApiKey", () => {blockBots: true,excludedIPs: [],};- vi.mocked(siteConfig.ensureInitialized).mockResolvedValue(undefined);+vi.mocked(siteConfig.getSiteConfig).mockResolvedValue(mockSite);// Mock console.info to avoid output during tests@@ -88,7 +90,8 @@ describe("validateApiKey", () => {it("should return success false when API key does not match", async () => {const mockSite: SiteConfigData = {- id: 1,+ id: "test-id",+ siteId: 1,apiKey: "valid-api-key",domain: "example.com",public: true,@@ -96,7 +99,7 @@ describe("validateApiKey", () => {blockBots: true,excludedIPs: [],};- vi.mocked(siteConfig.ensureInitialized).mockResolvedValue(undefined);+vi.mocked(siteConfig.getSiteConfig).mockResolvedValue(mockSite);const result = await validateApiKey(1, "invalid-api-key");@@ -106,7 +109,8 @@ describe("validateApiKey", () => {it("should handle string siteId by converting to number", async () => {const mockSite: SiteConfigData = {- id: 123,+ id: "test-id",+ siteId: 123,apiKey: "test-key",domain: "example.com",public: true,@@ -114,7 +118,7 @@ describe("validateApiKey", () => {blockBots: true,excludedIPs: [],};- vi.mocked(siteConfig.ensureInitialized).mockResolvedValue(undefined);+vi.mocked(siteConfig.getSiteConfig).mockResolvedValue(mockSite);await validateApiKey("123", "test-key");@@ -124,15 +128,16 @@ describe("validateApiKey", () => {it("should handle site with no API key configured", async () => {const mockSite: Partial<SiteConfigData> &- Pick<SiteConfigData, "id" | "domain" | "public" | "saltUserIds" | "blockBots"> = {- id: 1,+ Pick<SiteConfigData, "id" | "siteId" | "domain" | "public" | "saltUserIds" | "blockBots" | "excludedIPs"> = {+ id: "test-id",+ siteId: 1,domain: "example.com",public: true,saltUserIds: false,blockBots: true,excludedIPs: [],}; // No apiKey property- vi.mocked(siteConfig.ensureInitialized).mockResolvedValue(undefined);+vi.mocked(siteConfig.getSiteConfig).mockResolvedValue(mockSite as SiteConfigData);const result = await validateApiKey(1, "any-key");@@ -141,7 +146,7 @@ describe("validateApiKey", () => {});it("should handle errors during validation", async () => {- vi.mocked(siteConfig.ensureInitialized).mockRejectedValue(new Error("Database error"));+ vi.mocked(siteConfig.getSiteConfig).mockRejectedValue(new Error("Database error"));const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});@@ -170,7 +175,7 @@ describe("validateOrigin", () => {// Re-establish the mocks after resetvi.doMock("../../lib/siteConfig.js", () => ({siteConfig: {- ensureInitialized: vi.fn(),+getSiteConfig: vi.fn(),},}));@@ -195,7 +200,7 @@ describe("validateOrigin", () => {});it("should return success false when site is not found", async () => {- vi.mocked(siteConfig.ensureInitialized).mockResolvedValue(undefined);+vi.mocked(siteConfig.getSiteConfig).mockResolvedValue(undefined);const result = await validateOrigin(1, "https://example.com");@@ -205,7 +210,8 @@ describe("validateOrigin", () => {it("should return success false when no origin header is provided", async () => {const mockSite: SiteConfigData = {- id: 1,+ id: "test-id",+ siteId: 1,domain: "example.com",apiKey: "test-key",public: true,@@ -213,7 +219,7 @@ describe("validateOrigin", () => {blockBots: true,excludedIPs: [],};- vi.mocked(siteConfig.ensureInitialized).mockResolvedValue(undefined);+vi.mocked(siteConfig.getSiteConfig).mockResolvedValue(mockSite);const result = await validateOrigin(1);@@ -223,7 +229,8 @@ describe("validateOrigin", () => {it("should return success true for exact domain match", async () => {const mockSite: SiteConfigData = {- id: 1,+ id: "test-id",+ siteId: 1,domain: "example.com",apiKey: "test-key",public: true,@@ -231,7 +238,7 @@ describe("validateOrigin", () => {blockBots: true,excludedIPs: [],};- vi.mocked(siteConfig.ensureInitialized).mockResolvedValue(undefined);+vi.mocked(siteConfig.getSiteConfig).mockResolvedValue(mockSite);vi.mocked(normalizeOrigin).mockReturnValueOnce("example.com") // for request origin@@ -246,7 +253,8 @@ describe("validateOrigin", () => {it("should return success true for subdomain (always allowed)", async () => {const mockSite: SiteConfigData = {- id: 1,+ id: "test-id",+ siteId: 1,domain: "example.com",apiKey: "test-key",public: true,@@ -254,7 +262,7 @@ describe("validateOrigin", () => {blockBots: true,excludedIPs: [],};- vi.mocked(siteConfig.ensureInitialized).mockResolvedValue(undefined);+vi.mocked(siteConfig.getSiteConfig).mockResolvedValue(mockSite);vi.mocked(normalizeOrigin).mockReturnValueOnce("sub.example.com") // for request origin@@ -267,7 +275,8 @@ describe("validateOrigin", () => {it("should return success true for nested subdomain", async () => {const mockSite: SiteConfigData = {- id: 1,+ id: "test-id",+ siteId: 1,domain: "example.com",apiKey: "test-key",public: true,@@ -275,7 +284,7 @@ describe("validateOrigin", () => {blockBots: true,excludedIPs: [],};- vi.mocked(siteConfig.ensureInitialized).mockResolvedValue(undefined);+vi.mocked(siteConfig.getSiteConfig).mockResolvedValue(mockSite);vi.mocked(normalizeOrigin).mockReturnValueOnce("deep.nested.sub.example.com") // for request origin@@ -288,7 +297,8 @@ describe("validateOrigin", () => {it("should return success false for different domain", async () => {const mockSite: SiteConfigData = {- id: 1,+ id: "test-id",+ siteId: 1,domain: "example.com",apiKey: "test-key",public: true,@@ -296,7 +306,7 @@ describe("validateOrigin", () => {blockBots: true,excludedIPs: [],};- vi.mocked(siteConfig.ensureInitialized).mockResolvedValue(undefined);+vi.mocked(siteConfig.getSiteConfig).mockResolvedValue(mockSite);vi.mocked(normalizeOrigin).mockReturnValueOnce("different.com") // for request origin@@ -312,7 +322,8 @@ describe("validateOrigin", () => {it("should return success false for domain that contains site domain but is not a subdomain", async () => {const mockSite: SiteConfigData = {- id: 1,+ id: "test-id",+ siteId: 1,domain: "example.com",apiKey: "test-key",public: true,@@ -320,7 +331,7 @@ describe("validateOrigin", () => {blockBots: true,excludedIPs: [],};- vi.mocked(siteConfig.ensureInitialized).mockResolvedValue(undefined);+vi.mocked(siteConfig.getSiteConfig).mockResolvedValue(mockSite);vi.mocked(normalizeOrigin).mockReturnValueOnce("notexample.com") // for request origin@@ -336,7 +347,8 @@ describe("validateOrigin", () => {it("should handle string siteId by converting to number", async () => {const mockSite: SiteConfigData = {- id: 123,+ id: "test-id",+ siteId: 123,domain: "example.com",apiKey: "test-key",public: true,@@ -344,7 +356,7 @@ describe("validateOrigin", () => {blockBots: true,excludedIPs: [],};- vi.mocked(siteConfig.ensureInitialized).mockResolvedValue(undefined);+vi.mocked(siteConfig.getSiteConfig).mockResolvedValue(mockSite);await validateOrigin("123", "https://example.com");@@ -354,7 +366,8 @@ describe("validateOrigin", () => {it("should handle invalid origin format", async () => {const mockSite: SiteConfigData = {- id: 1,+ id: "test-id",+ siteId: 1,domain: "example.com",apiKey: "test-key",public: true,@@ -362,7 +375,7 @@ describe("validateOrigin", () => {blockBots: true,excludedIPs: [],};- vi.mocked(siteConfig.ensureInitialized).mockResolvedValue(undefined);+vi.mocked(siteConfig.getSiteConfig).mockResolvedValue(mockSite);vi.mocked(normalizeOrigin).mockImplementation(() => {throw new Error("Invalid URL");@@ -377,7 +390,7 @@ describe("validateOrigin", () => {});it("should handle errors during validation", async () => {- vi.mocked(siteConfig.ensureInitialized).mockRejectedValue(new Error("Database error"));+ vi.mocked(siteConfig.getSiteConfig).mockRejectedValue(new Error("Database error"));const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});diff --git a/server/src/services/shared/requestValidation.ts b/server/src/services/shared/requestValidation.tsindex fa5cde232..c8980c546 100644--- a/server/src/services/shared/requestValidation.ts+++ b/server/src/services/shared/requestValidation.ts@@ -34,7 +34,6 @@ export async function validateApiKey(siteId: string | number, apiKey?: string):}try {- await siteConfig.ensureInitialized();const numericSiteId = typeof siteId === "string" ? parseInt(siteId, 10) : siteId;const site = await siteConfig.getSiteConfig(numericSiteId);@@ -68,9 +67,6 @@ export async function validateOrigin(siteId: string | number, requestOrigin?: streturn { success: true };}- // Ensure site config is initialized- await siteConfig.ensureInitialized();-// Convert siteId to numberconst numericSiteId = typeof siteId === "string" ? parseInt(siteId, 10) : siteId;diff --git a/server/src/services/tracker/trackEvent.ts b/server/src/services/tracker/trackEvent.tsindex 08256459d..e804d142e 100644--- a/server/src/services/tracker/trackEvent.ts+++ b/server/src/services/tracker/trackEvent.ts@@ -243,28 +243,25 @@ export async function trackEvent(request: FastifyRequest, reply: FastifyReply) {}}- // If no valid API key, validate origin- if (!apiKeyValidation.success) {- const originValidation = await validateOrigin(validatedPayload.site_id, request.headers.origin as string);+ // If no valid API key, validate origin - disabled for now+ // if (!apiKeyValidation.success) {+ // const originValidation = await validateOrigin(validatedPayload.site_id, request.headers.origin as string);- if (!originValidation.success) {- logger.warn(- { siteId: validatedPayload.site_id, error: originValidation.error },- "Request rejected - origin validation failed"- );- return reply.status(403).send({- success: false,- error: originValidation.error,- });- }- }-- // Make sure the site config is loaded- await siteConfig.ensureInitialized();+ // if (!originValidation.success) {+ // logger.warn(+ // { siteId: validatedPayload.site_id, error: originValidation.error },+ // "Request rejected - origin validation failed"+ // );+ // return reply.status(403).send({+ // success: false,+ // error: originValidation.error,+ // });+ // }+ // }// Check if bot blocking is enabled for this site and if the request is from a bot// Skip bot check for API key authenticated requests- if (!validatedPayload.api_key && siteConfig.shouldBlockBots(validatedPayload.site_id)) {+ if (!validatedPayload.api_key && (await siteConfig.shouldBlockBots(validatedPayload.site_id))) {// Use custom user agent if provided, otherwise fall back to headerconst userAgent = validatedPayload.user_agent || (request.headers["user-agent"] as string);if (userAgent && isbot(userAgent)) {@@ -286,7 +283,7 @@ export async function trackEvent(request: FastifyRequest, reply: FastifyReply) {// Use custom IP if provided in payload, otherwise get from requestconst requestIP = validatedPayload.ip_address || request.ip || "";- if (siteConfig.isIPExcluded(requestIP, validatedPayload.site_id)) {+ if (await siteConfig.isIPExcluded(requestIP, validatedPayload.site_id)) {logger.info({ siteId: validatedPayload.site_id, ip: requestIP }, "IP excluded from tracking");return reply.status(200).send({success: true,@@ -295,7 +292,7 @@ export async function trackEvent(request: FastifyRequest, reply: FastifyReply) {}// Create base payload for the event using validated data- const payload = createBasePayload(+ const payload = await createBasePayload(request, // Pass request for IP/UAvalidatedPayload.type,validatedPayload // Add validated payload backdiff --git a/server/src/services/tracker/utils.ts b/server/src/services/tracker/utils.tsindex 7fde74c92..5d910e00b 100644--- a/server/src/services/tracker/utils.ts+++ b/server/src/services/tracker/utils.ts@@ -82,11 +82,11 @@ export function clearSelfReferrer(referrer: string, hostname: string): string {}// Create base tracking payload from request-export function createBasePayload(+export async function createBasePayload(request: FastifyRequest,eventType: "pageview" | "custom_event" | "performance" | "error" | "outbound" = "pageview",validatedBody: ValidatedTrackingPayload-): TotalTrackingPayload {+): Promise<TotalTrackingPayload> {// Use custom user agent if provided, otherwise fall back to headerconst userAgent = validatedBody.user_agent || request.headers["user-agent"] || "";// Override IP if provided in payload@@ -96,7 +96,7 @@ export function createBasePayload(// Use custom user ID if provided, otherwise generate oneconst userId = validatedBody.user_id? validatedBody.user_id.trim()- : userIdService.generateUserId(ipAddress, userAgent, siteId);+ : await userIdService.generateUserId(ipAddress, userAgent, siteId);return {...validatedBody,diff --git a/server/src/services/uptime/monitorExecutor.ts b/server/src/services/uptime/monitorExecutor.tsindex 0710d33aa..5e1c8c562 100644--- a/server/src/services/uptime/monitorExecutor.ts+++ b/server/src/services/uptime/monitorExecutor.ts@@ -2,7 +2,7 @@ import { Worker, Job } from "bullmq";import { eq, and, inArray } from "drizzle-orm";import { DateTime } from "luxon";import { db } from "../../db/postgres/postgres.js";-import { uptimeMonitors, uptimeMonitorStatus, agentRegions, uptimeIncidents } from "../../db/postgres/uptimeSchema.js";+import { uptimeMonitors, uptimeMonitorStatus, agentRegions, uptimeIncidents } from "../../db/postgres/schema.js";import { clickhouse } from "../../db/clickhouse/clickhouse.js";import { MonitorCheckJob, HttpCheckResult, TcpCheckResult, MonitorEvent } from "./types.js";import { performHttpCheck } from "./checks/httpCheck.js";diff --git a/server/src/services/uptime/monitorScheduler.ts b/server/src/services/uptime/monitorScheduler.tsindex a2cc8a3c3..4a3c40b8a 100644--- a/server/src/services/uptime/monitorScheduler.ts+++ b/server/src/services/uptime/monitorScheduler.ts@@ -1,7 +1,7 @@import { Queue, QueueEvents } from "bullmq";import { eq } from "drizzle-orm";import { db } from "../../db/postgres/postgres.js";-import { uptimeMonitors } from "../../db/postgres/uptimeSchema.js";+import { uptimeMonitors } from "../../db/postgres/schema.js";import { createServiceLogger } from "../../lib/logger/logger.js";import { MonitorCheckJob } from "./types.js";diff --git a/server/src/services/uptime/notificationService.ts b/server/src/services/uptime/notificationService.tsindex 078d2801b..f02bbe174 100644--- a/server/src/services/uptime/notificationService.ts+++ b/server/src/services/uptime/notificationService.ts@@ -1,7 +1,7 @@import { DateTime } from "luxon";import { and, eq, InferSelectModel } from "drizzle-orm";import { db } from "../../db/postgres/postgres.js";-import { notificationChannels } from "../../db/postgres/uptimeSchema.js";+import { notificationChannels } from "../../db/postgres/schema.js";import { createServiceLogger } from "../../lib/logger/logger.js";import { sendEmail } from "../../lib/resend.js";import { sendSMS } from "../../lib/twilio.js";diff --git a/server/src/services/uptime/regionHealthChecker.ts b/server/src/services/uptime/regionHealthChecker.tsindex d64200de6..84e73afad 100644--- a/server/src/services/uptime/regionHealthChecker.ts+++ b/server/src/services/uptime/regionHealthChecker.ts@@ -1,6 +1,6 @@import { eq } from "drizzle-orm";import { db } from "../../db/postgres/postgres.js";-import { agentRegions } from "../../db/postgres/uptimeSchema.js";+import { agentRegions } from "../../db/postgres/schema.js";import { createServiceLogger } from "../../lib/logger/logger.js";export class RegionHealthChecker {diff --git a/server/src/services/userId/userIdService.ts b/server/src/services/userId/userIdService.tsindex c8417a6fe..f4630d082 100644--- a/server/src/services/userId/userIdService.ts+++ b/server/src/services/userId/userIdService.ts@@ -47,9 +47,9 @@ class UserIdService {* @param siteId The site ID to check for salting configuration* @returns A sha256 hash to identify the user*/- generateUserId(ip: string, userAgent: string, siteId?: string | number): string {+ async generateUserId(ip: string, userAgent: string, siteId?: string | number): Promise<string> {// Only apply salt if the site has salting enabled- if (siteId && siteConfig.shouldSaltUserIds(siteId)) {+ if (await siteConfig.shouldSaltUserIds(siteId)) {const dailySalt = this.getDailySalt(); // Get the salt for the current dayreturn crypto.createHash("sha256")diff --git a/server/src/utils.ts b/server/src/utils.tsindex 146941ccf..c566b48bb 100644--- a/server/src/utils.ts+++ b/server/src/utils.ts@@ -124,11 +124,8 @@ export function getDeviceType(screenWidth: number, screenHeight: number, ua: UAP// Check if a site is publicexport const isSitePublic = async (siteId: string | number) => {try {- // Ensure the siteConfig cache is initialized- await siteConfig.ensureInitialized();-// Use the cached value- return siteConfig.isSitePublic(siteId);+ return await siteConfig.isSitePublic(siteId);} catch (err) {console.error("Error checking if site is public:", err);return false;