Skip to content

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

Add DISABLE_TELEMETRY support and update documentation for self-hosting (#485)

Bill Yangff9c6b84695c
diff --git a/docker-compose.yml b/docker-compose.yml
index 471fdafb1..25238e834 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -86,6 +86,7 @@ services:
- BETTER_AUTH_SECRET=${BETTER_AUTH_SECRET}
- BASE_URL=${BASE_URL}
- DISABLE_SIGNUP=${DISABLE_SIGNUP}
+ - DISABLE_TELEMETRY=${DISABLE_TELEMETRY}
depends_on:
clickhouse:
condition: service_healthy
diff --git a/docs/src/content/self-hosting.mdx b/docs/src/content/self-hosting.mdx
index 7601dab11..4c56b5b0a 100644
--- a/docs/src/content/self-hosting.mdx
+++ b/docs/src/content/self-hosting.mdx
@@ -137,4 +137,19 @@ sudo ufw status # Check the status
Ensure you allow SSH access (typically port 22) before enabling the firewall, otherwise you might lock yourself out of your VPS!
</Callout> */}
+## Anonymous Usage Telemetry
+
+To help us improve Rybbit, self-hosted instances automatically send anonymous usage statistics to our cloud service. This includes:
+
+- Number of rows in each ClickHouse table
+- Total database size
+- Your Rybbit version
+- A hashed instance identifier
+
+No personal data, website content, or visitor information is ever collected.
+
+<Callout type="info">
+You can completely disable telemetry by adding `DISABLE_TELEMETRY=true` to your `.env` file and restarting your services.
+</Callout>
+
If you run into any issues or need help, feel free to join our Discord community!
diff --git a/server/package.json b/server/package.json
index 031a1ff6a..ff5139893 100644
--- a/server/package.json
+++ b/server/package.json
@@ -1,7 +1,7 @@
{
- "name": "analytics-backend",
- "version": "1.0.0",
- "description": "Self-hosted analytics backend using ClickHouse",
+ "name": "rybbit-backend",
+ "version": "1.5.0",
+ "description": "Rybbit backend",
"main": "dist/index.js",
"type": "module",
"scripts": {
diff --git a/server/src/api/admin/collectTelemetry.ts b/server/src/api/admin/collectTelemetry.ts
new file mode 100644
index 000000000..d64cc9eda
--- /dev/null
+++ b/server/src/api/admin/collectTelemetry.ts
@@ -0,0 +1,43 @@
+import { FastifyReply, FastifyRequest } from "fastify";
+import { IS_CLOUD } from "../../lib/const.js";
+import { db } from "../../db/postgres/postgres.js";
+import { telemetry } from "../../db/postgres/schema.js";
+
+export async function collectTelemetry(
+ request: FastifyRequest<{
+ Body: {
+ instanceId: string;
+ version: string;
+ tableCounts: Record<string, number>;
+ clickhouseSizeGb: number;
+ };
+ }>,
+ reply: FastifyReply
+) {
+ // Only allow telemetry collection on cloud instances
+ if (!IS_CLOUD) {
+ return reply.status(403).send({ error: "Telemetry collection is only available on cloud instances" });
+ }
+
+ try {
+ const { instanceId, version, tableCounts, clickhouseSizeGb } = request.body;
+
+ // Validate required fields
+ if (!instanceId || !version || !tableCounts || clickhouseSizeGb === undefined) {
+ return reply.status(400).send({ error: "Missing required fields" });
+ }
+
+ // Insert telemetry data
+ await db.insert(telemetry).values({
+ instanceId,
+ version,
+ tableCounts,
+ clickhouseSizeGb,
+ });
+
+ return reply.send({ success: true });
+ } catch (error) {
+ console.error("Error collecting telemetry:", error);
+ return reply.status(500).send({ error: "Failed to collect telemetry" });
+ }
+}
\ No newline at end of file
diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.ts
index d2669b1b6..b3861d8d6 100644
--- a/server/src/db/postgres/schema.ts
+++ b/server/src/db/postgres/schema.ts
@@ -8,6 +8,7 @@ import {
timestamp,
foreignKey,
unique,
+ real,
} from "drizzle-orm/pg-core";
// User table
@@ -31,10 +32,7 @@ export const user = pgTable(
overMonthlyLimit: boolean().default(false),
monthlyEventCount: integer().default(0),
},
- (table) => [
- unique("user_username_unique").on(table.username),
- unique("user_email_unique").on(table.email),
- ]
+ (table) => [unique("user_username_unique").on(table.username), unique("user_email_unique").on(table.email)],
);
export const verification = pgTable("verification", {
@@ -75,7 +73,7 @@ export const sites = pgTable(
foreignColumns: [organization.id],
name: "sites_organization_id_organization_id_fk",
}),
- ]
+ ],
);
// Active sessions table
@@ -108,7 +106,7 @@ export const funnels = pgTable(
foreignColumns: [user.id],
name: "funnels_user_id_user_id_fk",
}),
- ]
+ ],
);
export const account = pgTable(
@@ -134,7 +132,7 @@ export const account = pgTable(
foreignColumns: [user.id],
name: "account_userId_user_id_fk",
}),
- ]
+ ],
);
export const organization = pgTable(
@@ -150,7 +148,7 @@ export const organization = pgTable(
monthlyEventCount: integer().default(0),
overMonthlyLimit: boolean().default(false),
},
- (table) => [unique("organization_slug_unique").on(table.slug)]
+ (table) => [unique("organization_slug_unique").on(table.slug)],
);
export const member = pgTable(
@@ -173,7 +171,7 @@ export const member = pgTable(
foreignColumns: [user.id],
name: "member_userId_user_id_fk",
}),
- ]
+ ],
);
export const invitation = pgTable(
@@ -198,7 +196,7 @@ export const invitation = pgTable(
foreignColumns: [organization.id],
name: "invitation_organizationId_organization_id_fk",
}),
- ]
+ ],
);
export const session = pgTable(
@@ -222,7 +220,7 @@ export const session = pgTable(
name: "session_userId_user_id_fk",
}),
unique("session_token_unique").on(table.token),
- ]
+ ],
);
// Goals table for tracking conversion goals
@@ -250,5 +248,15 @@ export const goals = pgTable(
foreignColumns: [sites.siteId],
name: "goals_site_id_sites_site_id_fk",
}),
- ]
+ ],
);
+
+// Telemetry table for tracking self-hosted instances
+export const telemetry = pgTable("telemetry", {
+ id: serial("id").primaryKey().notNull(),
+ instanceId: text("instance_id").notNull(),
+ timestamp: timestamp("timestamp", { mode: "string" }).notNull().defaultNow(),
+ version: text("version").notNull(),
+ tableCounts: jsonb("table_counts").notNull().$type<Record<string, number>>(),
+ clickhouseSizeGb: real("clickhouse_size_gb").notNull(),
+});
diff --git a/server/src/index.ts b/server/src/index.ts
index d281b843b..a2da04148 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -4,6 +4,7 @@ import { toNodeHandler } from "better-auth/node";
import Fastify from "fastify";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
+import { collectTelemetry } from "./api/admin/collectTelemetry.js";
import { getAdminOrganizations } from "./api/admin/getAdminOrganizations.js";
import { getAdminSites } from "./api/admin/getAdminSites.js";
import { getEventNames } from "./api/analytics/events/getEventNames.js";
@@ -58,18 +59,20 @@ import { createCheckoutSession } from "./api/stripe/createCheckoutSession.js";
import { createPortalSession } from "./api/stripe/createPortalSession.js";
import { getSubscription } from "./api/stripe/getSubscription.js";
import { handleWebhook } from "./api/stripe/webhook.js";
+import { addUserToOrganization } from "./api/user/addUserToOrganization.js";
import { getUserOrganizations } from "./api/user/getUserOrganizations.js";
import { listOrganizationMembers } from "./api/user/listOrganizationMembers.js";
import { initializeClickhouse } from "./db/clickhouse/clickhouse.js";
+import { initPostgres } from "./db/postgres/initPostgres.js";
import { loadAllowedDomains } from "./lib/allowedDomains.js";
import { getSessionFromReq, mapHeaders } from "./lib/auth-utils.js";
import { auth } from "./lib/auth.js";
import { IS_CLOUD } from "./lib/const.js";
import { siteConfig } from "./lib/siteConfig.js";
import { trackEvent } from "./services/tracker/trackEvent.js";
+// need to import telemetry service here to start it
+import { telemetryService } from "./services/telemetryService.js";
import { extractSiteId, isSitePublic } from "./utils.js";
-import { addUserToOrganization } from "./api/user/addUserToOrganization.js";
-import { initPostgres } from "./db/postgres/initPostgres.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -146,6 +149,7 @@ const PUBLIC_ROUTES: string[] = [
"/api/auth/callback/github",
"/api/stripe/webhook",
"/api/session-replay/record",
+ "/api/admin/telemetry",
];
// Define analytics routes that can be public
@@ -297,6 +301,7 @@ if (IS_CLOUD) {
// Admin Routes
server.get("/api/admin/sites", getAdminSites);
server.get("/api/admin/organizations", getAdminOrganizations);
+ server.post("/api/admin/telemetry", collectTelemetry);
}
server.post("/track", trackEvent);
@@ -309,6 +314,8 @@ const start = async () => {
console.info("Starting server...");
await Promise.all([initializeClickhouse(), loadAllowedDomains(), siteConfig.loadSiteConfigs(), initPostgres()]);
+ telemetryService.startTelemetryCron();
+
// Start the server
await server.listen({ port: 3001, host: "0.0.0.0" });
} catch (err) {
diff --git a/server/src/lib/const.ts b/server/src/lib/const.ts
index 39dafad8b..10b9d0aa2 100644
--- a/server/src/lib/const.ts
+++ b/server/src/lib/const.ts
@@ -4,6 +4,8 @@ dotenv.config();
export const IS_CLOUD = process.env.CLOUD === "true";
export const DISABLE_SIGNUP = process.env.DISABLE_SIGNUP === "true";
+export const DISABLE_TELEMETRY = process.env.DISABLE_TELEMETRY === "true";
+export const SECRET = process.env.BETTER_AUTH_SECRET;
// Trial constants (commented out as we're replacing with free tier)
// export const TRIAL_DURATION_DAYS = 14;
diff --git a/server/src/services/telemetryService.ts b/server/src/services/telemetryService.ts
new file mode 100644
index 000000000..f5be1bf5a
--- /dev/null
+++ b/server/src/services/telemetryService.ts
@@ -0,0 +1,161 @@
+import * as cron from "node-cron";
+import { createHash } from "crypto";
+import fs from "fs/promises";
+import path from "path";
+import { fileURLToPath } from "url";
+import { clickhouse } from "../db/clickhouse/clickhouse.js";
+import { IS_CLOUD, DISABLE_TELEMETRY, SECRET } from "../lib/const.js";
+import { processResults } from "../api/analytics/utils.js";
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+class TelemetryService {
+ private telemetryTask: cron.ScheduledTask | null = null;
+
+ constructor() {}
+
+ private initializeTelemetryCron() {
+ // Only initialize if not cloud and telemetry is not disabled
+ if (!IS_CLOUD && !DISABLE_TELEMETRY) {
+ console.info("[TelemetryService] Initializing telemetry cron");
+ // Schedule telemetry to run every 24 hours at midnight
+ this.telemetryTask = cron.schedule("0 0 * * *", async () => {
+ try {
+ await this.collectAndSendTelemetry();
+ } catch (error) {
+ console.error("[TelemetryService] Error during telemetry collection:", error);
+ }
+ });
+
+ // Run immediately on startup
+ this.collectAndSendTelemetry();
+
+ console.log("[TelemetryService] Telemetry collection initialized (runs daily at midnight)");
+ }
+ }
+
+ // Generate instance ID from hashed secret
+ private getInstanceId(): string {
+ if (!SECRET) {
+ // Fallback to a default value if SECRET is not set
+ return "no-secret-configured";
+ }
+
+ // Create a SHA-256 hash of the secret and take first 12 characters
+ const hash = createHash("sha256").update(SECRET).digest("hex");
+ return hash.substring(0, 12);
+ }
+
+ // Get table row counts from ClickHouse
+ private async getTableCounts() {
+ const tables = ["events", "session_replay_events", "session_replay_metadata", "hourly_events_by_site_mv_target"];
+
+ const counts: Record<string, number> = {};
+
+ for (const table of tables) {
+ try {
+ const result = await clickhouse.query({
+ query: `SELECT count() as count FROM ${table}`,
+ format: "JSONEachRow",
+ });
+ const data = await processResults<{ count: number }>(result);
+ counts[table] = data[0]?.count || 0;
+ } catch (error) {
+ // Table might not exist, especially hourly_events_by_site_mv_target in self-hosted
+ counts[table] = 0;
+ }
+ }
+
+ return counts;
+ }
+
+ // Get ClickHouse database size in GB
+ private async getClickhouseSizeGb(): Promise<number> {
+ try {
+ const result = await clickhouse.query({
+ query: `
+ SELECT sum(bytes_on_disk) / (1024 * 1024 * 1024) as size_gb
+ FROM system.parts
+ WHERE active
+ `,
+ format: "JSONEachRow",
+ });
+ const data = await processResults<{ size_gb: number }>(result);
+ return data[0]?.size_gb || 0;
+ } catch (error) {
+ console.error("Error getting ClickHouse size:", error);
+ return 0;
+ }
+ }
+
+ // Get package version
+ private async getVersion(): Promise<string> {
+ const packageJsonPath = path.join(__dirname, "../../package.json");
+ const packageJson = JSON.parse(await fs.readFile(packageJsonPath, "utf-8"));
+ return packageJson.version;
+ }
+
+ // Send telemetry to cloud instance
+ private async sendTelemetry(data: any) {
+ try {
+ const response = await fetch("https://demo.rybbit.io/api/admin/telemetry", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(data),
+ });
+
+ if (!response.ok) {
+ console.error("Failed to send telemetry:", response.status, response.statusText);
+ }
+ } catch (error) {
+ console.error("Error sending telemetry:", error);
+ }
+ }
+
+ // Main telemetry collection function
+ public async collectAndSendTelemetry() {
+ // Skip if in cloud environment or telemetry is disabled
+ if (IS_CLOUD || DISABLE_TELEMETRY) {
+ return;
+ }
+
+ try {
+ const instanceId = this.getInstanceId();
+ const [version, tableCounts, clickhouseSizeGb] = await Promise.all([
+ this.getVersion(),
+ this.getTableCounts(),
+ this.getClickhouseSizeGb(),
+ ]);
+
+ const telemetryData = {
+ instanceId,
+ version,
+ tableCounts,
+ clickhouseSizeGb,
+ };
+
+ await this.sendTelemetry(telemetryData);
+ console.log("[TelemetryService] Telemetry sent successfully");
+ } catch (error) {
+ console.error("Error collecting telemetry:", error);
+ }
+ }
+
+ // Method to stop the telemetry cron job (useful for graceful shutdown)
+ public stopTelemetryCron() {
+ if (this.telemetryTask) {
+ this.telemetryTask.stop();
+ console.log("[TelemetryService] Telemetry collection cron stopped");
+ }
+ }
+
+ public startTelemetryCron() {
+ this.initializeTelemetryCron();
+ }
+}
+
+// Create a singleton instance
+export const telemetryService = new TelemetryService();
diff --git a/server/src/services/userId/userIdService.ts b/server/src/services/userId/userIdService.ts
index 6ca3a2131..5a6ad014f 100644
--- a/server/src/services/userId/userIdService.ts
+++ b/server/src/services/userId/userIdService.ts
@@ -1,4 +1,5 @@
import crypto from "crypto";
+import { SECRET } from "../../lib/const.js";
import { siteConfig } from "../../lib/siteConfig.js";
class UserIdService {
@@ -14,11 +15,9 @@ class UserIdService {
* @returns {string} The daily salt as a hex string.
*/
private getDailySalt(): string {
- const secretKey = process.env.BETTER_AUTH_SECRET;
-
- if (!secretKey) {
+ if (!SECRET) {
console.error(
- "FATAL: BETTER_AUTH_SECRET environment variable is not set. User ID generation will be insecure or fail."
+ "FATAL: BETTER_AUTH_SECRET environment variable is not set. User ID generation will be insecure or fail.",
);
throw new Error("BETTER_AUTH_SECRET environment variable is missing.");
}
@@ -31,7 +30,7 @@ class UserIdService {
return this.cachedSalt;
}
- const input = secretKey + currentDate;
+ const input = SECRET + currentDate;
const newSalt = crypto.createHash("sha256").update(input).digest("hex");
this.cachedSalt = newSalt;
@@ -48,11 +47,7 @@ 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 {
+ generateUserId(ip: string, userAgent: string, siteId?: string | number): string {
// Only apply salt if the site has salting enabled
if (siteId && siteConfig.shouldSaltUserIds(siteId)) {
const dailySalt = this.getDailySalt(); // Get the salt for the current day
@@ -70,4 +65,4 @@ class UserIdService {
}
}
-export const userIdService = new UserIdService();
\ No newline at end of file
+export const userIdService = new UserIdService();