Skip to content

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

Enhance site management with domain handling

Bill Yang990861aca6b6
diff --git a/server/src/api/sites/addSite.ts b/server/src/api/sites/addSite.ts
index b4eeb1001..aa8d1f457 100644
--- a/server/src/api/sites/addSite.ts
+++ b/server/src/api/sites/addSite.ts
@@ -109,6 +109,7 @@ export async function addSite(
siteConfig.addSite(newSite[0].siteId, {
public: newSite[0].public || false,
saltUserIds: newSite[0].saltUserIds || false,
+ domain: newSite[0].domain,
});
return reply.status(201).send(newSite[0]);
diff --git a/server/src/api/sites/changeSiteDomain.ts b/server/src/api/sites/changeSiteDomain.ts
index d3538bcfe..7fe1f6e80 100644
--- a/server/src/api/sites/changeSiteDomain.ts
+++ b/server/src/api/sites/changeSiteDomain.ts
@@ -4,6 +4,7 @@ import { db } from "../../db/postgres/postgres.js";
import { sites } from "../../db/postgres/schema.js";
import { loadAllowedDomains } from "../../lib/allowedDomains.js";
import { getUserHasAdminAccessToSite } from "../../lib/auth-utils.js";
+import { siteConfig } from "../../lib/siteConfig.js";
export async function changeSiteDomain(
request: FastifyRequest<{
@@ -57,6 +58,7 @@ export async function changeSiteDomain(
// Reload allowed domains to update CORS configuration
await loadAllowedDomains();
+ siteConfig.updateSiteDomain(siteId, newDomain);
return reply.status(200).send({ message: "Domain updated successfully" });
} catch (err) {
diff --git a/server/src/lib/siteConfig.ts b/server/src/lib/siteConfig.ts
index 1b6e4d8c1..bc1191bb4 100644
--- a/server/src/lib/siteConfig.ts
+++ b/server/src/lib/siteConfig.ts
@@ -5,6 +5,7 @@ import { sites } from "../db/postgres/schema.js";
interface SiteConfigData {
public: boolean;
saltUserIds: boolean;
+ domain: string;
}
class SiteConfig {
@@ -18,6 +19,7 @@ class SiteConfig {
siteId: sites.siteId,
public: sites.public,
saltUserIds: sites.saltUserIds,
+ domain: sites.domain,
})
.from(sites);
@@ -29,6 +31,7 @@ class SiteConfig {
this.siteConfigMap.set(site.siteId, {
public: site.public || false,
saltUserIds: site.saltUserIds || false,
+ domain: site.domain || "",
});
}
@@ -60,6 +63,15 @@ class SiteConfig {
return config?.saltUserIds || false;
}
+ /**
+ * Get the domain of a site
+ */
+ getSiteDomain(siteId: string | number): string {
+ const numericSiteId = Number(siteId);
+ const config = this.siteConfigMap.get(numericSiteId);
+ return config?.domain || "";
+ }
+
/**
* Update the public status of a site in the cache
*/
@@ -67,6 +79,7 @@ class SiteConfig {
const config = this.siteConfigMap.get(siteId) || {
public: false,
saltUserIds: false,
+ domain: "",
};
config.public = isPublic;
this.siteConfigMap.set(siteId, config);
@@ -79,11 +92,25 @@ class SiteConfig {
const config = this.siteConfigMap.get(siteId) || {
public: false,
saltUserIds: false,
+ domain: "",
};
config.saltUserIds = saltUserIds;
this.siteConfigMap.set(siteId, config);
}
+ /**
+ * Update the domain of a site in the cache
+ */
+ updateSiteDomain(siteId: number, domain: string): void {
+ const config = this.siteConfigMap.get(siteId) || {
+ public: false,
+ saltUserIds: false,
+ domain: "",
+ };
+ config.domain = domain;
+ this.siteConfigMap.set(siteId, config);
+ }
+
/**
* Add a new site to the cache
*/
diff --git a/server/src/tracker/const.ts b/server/src/tracker/const.ts
index 4d55e2492..61824cc91 100644
--- a/server/src/tracker/const.ts
+++ b/server/src/tracker/const.ts
@@ -1,3 +1,9 @@
+/**
+ * Set to true to disable origin checking for tracking requests
+ * This should only be enabled in development or testing environments
+ */
+export const DISABLE_ORIGIN_CHECK = process.env.DISABLE_ORIGIN_CHECK === "true";
+
export const searchDomains = [
// Google and variants
"google.com",
diff --git a/server/src/tracker/trackEvent.ts b/server/src/tracker/trackEvent.ts
index 227f1337e..82830b5a6 100644
--- a/server/src/tracker/trackEvent.ts
+++ b/server/src/tracker/trackEvent.ts
@@ -4,6 +4,7 @@ import {
clearSelfReferrer,
createBasePayload,
getExistingSession,
+ isSiteOverLimit,
TotalTrackingPayload,
} from "./trackingUtils.js";
import { db } from "../db/postgres/postgres.js";
@@ -11,6 +12,8 @@ import { activeSessions } from "../db/postgres/schema.js";
import { eq } from "drizzle-orm";
import { getDeviceType } from "../utils.js";
import { pageviewQueue } from "./pageviewQueue.js";
+import { siteConfig } from "../lib/siteConfig.js";
+import { DISABLE_ORIGIN_CHECK } from "./const.js";
// Define Zod schema for validation
export const trackingPayloadSchema = z.discriminatedUnion("type", [
@@ -131,6 +134,81 @@ export async function processTrackingEvent(
await updateSession(payload, existingSession, isPageview);
}
+/**
+ * Validates if the request's origin matches the registered domain for the site
+ * @param siteId The site ID from the tracking payload
+ * @param requestOrigin The origin header from the request
+ * @returns An object with success status and optional error message
+ */
+async function validateOrigin(siteId: string, requestOrigin?: string) {
+ try {
+ // If origin checking is disabled, return success
+ if (DISABLE_ORIGIN_CHECK) {
+ console.info(
+ `[Tracking] Origin check disabled. Allowing request for site ${siteId} from origin: ${
+ requestOrigin || "none"
+ }`
+ );
+ return { success: true };
+ }
+
+ // Ensure site config is initialized
+ await siteConfig.ensureInitialized();
+
+ // Convert siteId to number
+ const numericSiteId =
+ typeof siteId === "string" ? parseInt(siteId, 10) : siteId;
+
+ // Get the domain associated with this site
+ const siteDomain = siteConfig.getSiteDomain(numericSiteId);
+
+ if (!siteDomain) {
+ return {
+ success: false,
+ error: "Site not found or has no registered domain",
+ };
+ }
+
+ // If no origin header, reject the request
+ if (!requestOrigin) {
+ return {
+ success: false,
+ error: "Origin header required",
+ };
+ }
+
+ try {
+ // Parse the origin into URL components
+ const originUrl = new URL(requestOrigin);
+
+ // Normalize domains by removing 'www.' prefix if present
+ const normalizedOriginHost = originUrl.hostname.replace(/^www\./, "");
+ const normalizedSiteDomain = siteDomain.replace(/^www\./, "");
+
+ // Check if the normalized domains match
+ if (normalizedOriginHost !== normalizedSiteDomain) {
+ return {
+ success: false,
+ error: `Origin mismatch. Expected: ${siteDomain}, Received: ${requestOrigin}`,
+ };
+ }
+
+ return { success: true };
+ } catch (error) {
+ return {
+ success: false,
+ error: `Invalid origin format: ${requestOrigin}`,
+ };
+ }
+ } catch (error) {
+ console.error("Error validating origin:", error);
+ return {
+ success: false,
+ error: "Internal error validating origin",
+ };
+ }
+}
+
// Unified handler for all events (pageviews and custom events)
export async function trackEvent(request: FastifyRequest, reply: FastifyReply) {
try {
@@ -148,23 +226,36 @@ export async function trackEvent(request: FastifyRequest, reply: FastifyReply) {
// Use validated data
const validatedPayload = validationResult.data;
- // Access validated data using validatedPayload.propertyName
- const eventType = validatedPayload.type;
+ // Validate that the request is coming from the expected origin
+ const originValidation = await validateOrigin(
+ validatedPayload.site_id,
+ request.headers.origin as string
+ );
+
+ if (!originValidation.success) {
+ console.warn(
+ `[Tracking] Request rejected for site ${validatedPayload.site_id}: ${originValidation.error}`
+ );
+ return reply.status(403).send({
+ success: false,
+ error: originValidation.error,
+ });
+ }
// Check if the site has exceeded its monthly limit
- // if (isSiteOverLimit(validatedPayload.site_id)) {
- // console.log(
- // `[Tracking] Skipping event for site ${validatedPayload.site_id} - over monthly limit`
- // );
- // return reply
- // .status(200)
- // .send("Site over monthly limit, event not tracked");
- // }
+ if (isSiteOverLimit(validatedPayload.site_id)) {
+ console.log(
+ `[Tracking] Skipping event for site ${validatedPayload.site_id} - over monthly limit`
+ );
+ return reply
+ .status(200)
+ .send("Site over monthly limit, event not tracked");
+ }
// Create base payload for the event using validated data
const payload = createBasePayload(
request, // Pass request for IP/UA
- eventType,
+ validatedPayload.type,
validatedPayload // Add validated payload back
);
@@ -178,7 +269,7 @@ export async function trackEvent(request: FastifyRequest, reply: FastifyReply) {
await processTrackingEvent(
payload,
existingSession,
- eventType === "pageview"
+ validatedPayload.type === "pageview"
);
return reply.status(200).send({