Skip to content

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

Enhance CORS configuration and security measures (#1015)

Goldflag6f1039bdd332
diff --git a/server/src/index.ts b/server/src/index.ts
index 55a38fe1f..4d39098c1 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -149,6 +149,7 @@ import {
} from "./lib/auth-middleware.js";
import { mapHeaders } from "./lib/auth-utils.js";
import { auth } from "./lib/auth.js";
+import { createCorsOptionsDelegate, createRejectUntrustedOriginHook } from "./lib/cors.js";
import { IS_CLOUD } from "./lib/const.js";
import { reengagementService } from "./services/reengagement/reengagementService.js";
import { sessionsService } from "./services/sessions/sessionsService.js";
@@ -209,13 +210,9 @@ const server = Fastify({
});
server.register(cors, {
- origin: (_origin, callback) => {
- callback(null, true);
- },
- methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"],
- allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With", "x-captcha-response", "x-private-key"],
- credentials: true,
+ delegator: createCorsOptionsDelegate(),
});
+server.addHook("onRequest", createRejectUntrustedOriginHook());
// Serve static files
server.register(fastifyStatic, {
diff --git a/server/src/lib/auth.ts b/server/src/lib/auth.ts
index e689d627b..1263ecbb0 100644
--- a/server/src/lib/auth.ts
+++ b/server/src/lib/auth.ts
@@ -21,6 +21,7 @@ import {
sendWelcomeEmail,
} from "./email/email.js";
import { onboardingTipsService } from "../services/onboardingTips/onboardingTipsService.js";
+import { getTrustedCorsOrigins } from "./cors.js";
dotenv.config();
@@ -249,7 +250,7 @@ export const auth = betterAuth({
},
},
plugins: pluginList,
- trustedOrigins: ["http://localhost:3002"],
+ trustedOrigins: getTrustedCorsOrigins(),
advanced: {
useSecureCookies: process.env.NODE_ENV === "production", // don't mark Secure in dev
defaultCookieAttributes: {
diff --git a/server/src/lib/cors.test.ts b/server/src/lib/cors.test.ts
new file mode 100644
index 000000000..75a6186f0
--- /dev/null
+++ b/server/src/lib/cors.test.ts
@@ -0,0 +1,192 @@
+import cors from "@fastify/cors";
+import Fastify from "fastify";
+import { describe, expect, it } from "vitest";
+import {
+ createCorsOptionsDelegate,
+ createRejectUntrustedOriginHook,
+ getTrustedCorsOrigins,
+ normalizeCorsOrigin,
+} from "./cors.js";
+
+async function buildCorsTestApp(env: NodeJS.ProcessEnv) {
+ const app = Fastify();
+ await app.register(cors, {
+ delegator: createCorsOptionsDelegate(env),
+ });
+ app.addHook("onRequest", createRejectUntrustedOriginHook(env));
+
+ app.delete("/api/sites/:siteId", async () => ({ success: true }));
+ app.get("/api/sites/:siteId/sessions", async () => ({ data: [] }));
+ app.post("/api/track", async () => ({ success: true }));
+ app.get("/api/version", async () => ({ version: "0.0.0" }));
+
+ await app.ready();
+ return app;
+}
+
+describe("CORS policy", () => {
+ it("allows credentialed management requests only from BASE_URL origin", async () => {
+ const app = await buildCorsTestApp({
+ NODE_ENV: "production",
+ BASE_URL: "https://rybbit.example.com/dashboard",
+ });
+
+ try {
+ const res = await app.inject({
+ method: "OPTIONS",
+ url: "/api/sites/1",
+ headers: {
+ origin: "https://rybbit.example.com",
+ "access-control-request-method": "DELETE",
+ },
+ });
+
+ expect(res.statusCode).toBe(204);
+ expect(res.headers["access-control-allow-origin"]).toBe("https://rybbit.example.com");
+ expect(res.headers["access-control-allow-credentials"]).toBe("true");
+ } finally {
+ await app.close();
+ }
+ });
+
+ it("does not emit CORS headers for disallowed management origins", async () => {
+ const app = await buildCorsTestApp({
+ NODE_ENV: "production",
+ BASE_URL: "https://rybbit.example.com",
+ });
+
+ try {
+ const preflight = await app.inject({
+ method: "OPTIONS",
+ url: "/api/sites/1",
+ headers: {
+ origin: "https://attacker.example",
+ "access-control-request-method": "DELETE",
+ },
+ });
+
+ expect(preflight.statusCode).toBe(404);
+ expect(preflight.headers["access-control-allow-origin"]).toBeUndefined();
+ expect(preflight.headers["access-control-allow-credentials"]).toBeUndefined();
+
+ const actual = await app.inject({
+ method: "DELETE",
+ url: "/api/sites/1",
+ headers: {
+ origin: "https://attacker.example",
+ },
+ });
+
+ expect(actual.statusCode).toBe(403);
+ expect(actual.headers["access-control-allow-origin"]).toBeUndefined();
+ expect(actual.headers["access-control-allow-credentials"]).toBeUndefined();
+ } finally {
+ await app.close();
+ }
+ });
+
+ it("keeps tracking endpoints permissive without allowing credentials", async () => {
+ const app = await buildCorsTestApp({
+ NODE_ENV: "production",
+ BASE_URL: "https://rybbit.example.com",
+ });
+
+ try {
+ const preflight = await app.inject({
+ method: "OPTIONS",
+ url: "/api/track",
+ headers: {
+ origin: "https://customer-site.example",
+ "access-control-request-method": "POST",
+ },
+ });
+
+ expect(preflight.statusCode).toBe(204);
+ expect(preflight.headers["access-control-allow-origin"]).toBe("https://customer-site.example");
+ expect(preflight.headers["access-control-allow-credentials"]).toBeUndefined();
+
+ const actual = await app.inject({
+ method: "POST",
+ url: "/api/track",
+ headers: {
+ origin: "https://customer-site.example",
+ },
+ });
+
+ expect(actual.statusCode).toBe(200);
+ expect(actual.headers["access-control-allow-origin"]).toBe("https://customer-site.example");
+ expect(actual.headers["access-control-allow-credentials"]).toBeUndefined();
+ } finally {
+ await app.close();
+ }
+ });
+
+ it("allows public version checks without credentials", async () => {
+ const app = await buildCorsTestApp({
+ NODE_ENV: "production",
+ BASE_URL: "https://rybbit.example.com",
+ });
+
+ try {
+ const res = await app.inject({
+ method: "GET",
+ url: "/api/version",
+ headers: {
+ origin: "https://self-hosted.example",
+ },
+ });
+
+ expect(res.statusCode).toBe(200);
+ expect(res.headers["access-control-allow-origin"]).toBe("https://self-hosted.example");
+ expect(res.headers["access-control-allow-credentials"]).toBeUndefined();
+ } finally {
+ await app.close();
+ }
+ });
+
+ it("allows public session-list requests without credentials", async () => {
+ const app = await buildCorsTestApp({
+ NODE_ENV: "production",
+ BASE_URL: "https://demo.rybbit.com",
+ });
+
+ try {
+ const res = await app.inject({
+ method: "GET",
+ url: "/api/sites/81/sessions?past_minutes_start=240&past_minutes_end=0&filters=[]&page=1&limit=100",
+ headers: {
+ origin: "https://docs.rybbit.com",
+ },
+ });
+
+ expect(res.statusCode).toBe(200);
+ expect(res.headers["access-control-allow-origin"]).toBe("https://docs.rybbit.com");
+ expect(res.headers["access-control-allow-credentials"]).toBeUndefined();
+ } finally {
+ await app.close();
+ }
+ });
+});
+
+describe("trusted CORS origins", () => {
+ it("normalizes quoted URLs to origins", () => {
+ expect(normalizeCorsOrigin('"https://rybbit.example.com/path"')).toBe("https://rybbit.example.com");
+ expect(normalizeCorsOrigin("javascript:alert(1)")).toBeNull();
+ });
+
+ it("uses BASE_URL in production and localhost client origins in development", () => {
+ expect(
+ getTrustedCorsOrigins({
+ NODE_ENV: "production",
+ BASE_URL: "https://rybbit.example.com",
+ })
+ ).toEqual(["https://rybbit.example.com"]);
+
+ expect(
+ getTrustedCorsOrigins({
+ NODE_ENV: "development",
+ BASE_URL: "https://rybbit.example.com",
+ })
+ ).toEqual(["https://rybbit.example.com", "http://localhost:3002", "http://127.0.0.1:3002"]);
+ });
+});
diff --git a/server/src/lib/cors.ts b/server/src/lib/cors.ts
new file mode 100644
index 000000000..4c6e3d51d
--- /dev/null
+++ b/server/src/lib/cors.ts
@@ -0,0 +1,151 @@
+import type { FastifyReply, FastifyRequest } from "fastify";
+
+const corsMethods = ["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"];
+const corsAllowedHeaders = ["Content-Type", "Authorization", "X-Requested-With", "x-captcha-response", "x-private-key"];
+
+type CorsOptions = {
+ origin: boolean;
+ methods: string[];
+ allowedHeaders: string[];
+ credentials: boolean;
+};
+
+type CorsDelegateCallback = (error: Error | null, options?: CorsOptions) => void;
+
+const commonCorsOptions = {
+ methods: corsMethods,
+ allowedHeaders: corsAllowedHeaders,
+};
+
+const devTrustedOrigins = ["http://localhost:3002", "http://127.0.0.1:3002"];
+const unsafeMethods = new Set(["POST", "PUT", "PATCH", "DELETE"]);
+
+function cleanEnvUrl(value: string | undefined): string | null {
+ const trimmed = value?.trim();
+ if (!trimmed) {
+ return null;
+ }
+
+ return trimmed.replace(/^['"]|['"]$/g, "");
+}
+
+export function normalizeCorsOrigin(value: string | undefined): string | null {
+ const cleaned = cleanEnvUrl(value);
+ if (!cleaned) {
+ return null;
+ }
+
+ try {
+ const parsed = new URL(cleaned);
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
+ return null;
+ }
+
+ return parsed.origin;
+ } catch {
+ return null;
+ }
+}
+
+// Trusted origins are static config (BASE_URL / NODE_ENV); cache per env object so
+// the URL parse + Set build runs once instead of on every request.
+const trustedOriginsCache = new WeakMap<NodeJS.ProcessEnv, string[]>();
+
+export function getTrustedCorsOrigins(env: NodeJS.ProcessEnv = process.env): string[] {
+ const cached = trustedOriginsCache.get(env);
+ if (cached) {
+ return cached;
+ }
+
+ const origins = new Set<string>();
+ const baseUrlOrigin = normalizeCorsOrigin(env.BASE_URL);
+
+ if (baseUrlOrigin) {
+ origins.add(baseUrlOrigin);
+ }
+
+ if (env.NODE_ENV !== "production") {
+ for (const origin of devTrustedOrigins) {
+ origins.add(origin);
+ }
+ }
+
+ const result = [...origins];
+ trustedOriginsCache.set(env, result);
+ return result;
+}
+
+function getRequestPath(request: FastifyRequest): string {
+ return (request.url || "/").split("?")[0] || "/";
+}
+
+export function isPublicCorsPath(path: string): boolean {
+ return (
+ path === "/api/track" ||
+ path === "/api/identify" ||
+ path === "/api/version" ||
+ path.startsWith("/api/session-replay/record/") ||
+ path.startsWith("/api/site/tracking-config/") ||
+ /^\/api\/sites\/[^/]+\/sessions$/.test(path) ||
+ /^\/api\/sites\/[^/]+\/embed-stats$/.test(path) ||
+ /^\/api\/site\/[^/]+\/feature-flags\/evaluate$/.test(path)
+ );
+}
+
+export function getCorsOptionsForRequest(
+ request: FastifyRequest,
+ env: NodeJS.ProcessEnv = process.env
+): CorsOptions {
+ const requestOrigin = normalizeCorsOrigin(request.headers.origin);
+ if (!requestOrigin) {
+ return {
+ ...commonCorsOptions,
+ origin: false,
+ credentials: false,
+ };
+ }
+
+ if (isPublicCorsPath(getRequestPath(request))) {
+ return {
+ ...commonCorsOptions,
+ origin: true,
+ credentials: false,
+ };
+ }
+
+ return {
+ ...commonCorsOptions,
+ origin: getTrustedCorsOrigins(env).includes(requestOrigin),
+ credentials: true,
+ };
+}
+
+export function shouldRejectUntrustedOrigin(
+ request: FastifyRequest,
+ env: NodeJS.ProcessEnv = process.env
+): boolean {
+ if (!unsafeMethods.has(request.method)) {
+ return false;
+ }
+
+ const requestOrigin = normalizeCorsOrigin(request.headers.origin);
+ if (!requestOrigin || isPublicCorsPath(getRequestPath(request))) {
+ return false;
+ }
+
+ return !getTrustedCorsOrigins(env).includes(requestOrigin);
+}
+
+export function createCorsOptionsDelegate(env: NodeJS.ProcessEnv = process.env) {
+ return (request: FastifyRequest, callback: CorsDelegateCallback) => {
+ callback(null, getCorsOptionsForRequest(request, env));
+ };
+}
+
+export function createRejectUntrustedOriginHook(env: NodeJS.ProcessEnv = process.env) {
+ return async (request: FastifyRequest, reply: FastifyReply) => {
+ if (shouldRejectUntrustedOrigin(request, env)) {
+ return reply.status(403).send({ error: "Origin not allowed" });
+ }
+ };
+}