🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Add site settings for public analytics and user ID salting
Bill Yanga1f4c60fb9f3
diff --git a/client/src/api/admin/sites.ts b/client/src/api/admin/sites.tsindex 5b8d70a1d..14330294e 100644--- a/client/src/api/admin/sites.ts+++ b/client/src/api/admin/sites.ts@@ -38,13 +38,23 @@ export async function getSites() {return genericQuery<GetSitesResponse>("get-sites");}-export function addSite(domain: string, name: string, organizationId: string) {+export function addSite(+ domain: string,+ name: string,+ organizationId: string,+ settings?: {+ isPublic?: boolean;+ saltUserIds?: boolean;+ }+) {return authedFetch(`${BACKEND_URL}/add-site`, {method: "POST",body: JSON.stringify({domain,name,organizationId,+ public: settings?.isPublic || false,+ saltUserIds: settings?.saltUserIds || false,}),headers: {"Content-Type": "application/json",diff --git a/client/src/app/components/AddSite.tsx b/client/src/app/components/AddSite.tsxindex b75aa347f..cdfe3cf3c 100644--- a/client/src/app/components/AddSite.tsx+++ b/client/src/app/components/AddSite.tsx@@ -22,6 +22,7 @@ import {SelectTrigger,SelectValue,} from "../../components/ui/select";+import { Switch } from "../../components/ui/switch";import { authClient } from "../../lib/auth";/**@@ -52,6 +53,8 @@ export function AddSite({const [domain, setDomain] = useState("");const [selectedOrganizationId, setSelectedOrganizationId] =useState<string>("");+ const [isPublic, setIsPublic] = useState(false);+ const [saltUserIds, setSaltUserIds] = useState(false);const [error, setError] = useState("");// Set the first organization as the default selection when organizations are loaded@@ -79,7 +82,10 @@ export function AddSite({return;}- const response = await addSite(domain, domain, selectedOrganizationId);+ const response = await addSite(domain, domain, selectedOrganizationId, {+ isPublic,+ saltUserIds,+ });if (!response.ok) {const errorData = await response.json();setError(errorData.error || "Failed to add site");@@ -89,17 +95,25 @@ export function AddSite({refetch();};+ const resetForm = () => {+ setDomain("");+ setError("");+ setIsPublic(false);+ setSaltUserIds(false);+ // Reset organization to first one when opening dialog+ if (organizations && organizations.length > 0) {+ setSelectedOrganizationId(organizations[0].id);+ }+ };+return (<div><Dialogopen={open}onOpenChange={(isOpen) => {setOpen(isOpen);- setDomain("");- setError("");- // Reset organization to first one when opening dialog- if (isOpen && organizations && organizations.length > 0) {- setSelectedOrganizationId(organizations[0].id);+ if (isOpen) {+ resetForm();}}}>@@ -124,7 +138,12 @@ export function AddSite({<div className="grid gap-4 py-2"><div className="grid w-full items-center gap-1.5">- <Label htmlFor="domain">Domain</Label>+ <Label+ htmlFor="domain"+ className="text-sm font-medium text-white"+ >+ Domain+ </Label><Inputid="domain"value={domain}@@ -133,7 +152,12 @@ export function AddSite({/></div><div className="grid w-full items-center gap-1.5">- <Label htmlFor="organization">Organization</Label>+ <Label+ htmlFor="organization"+ className="text-sm font-medium text-white"+ >+ Organization+ </Label><Selectvalue={selectedOrganizationId}onValueChange={setSelectedOrganizationId}@@ -159,6 +183,46 @@ export function AddSite({</SelectContent></Select></div>++ {/* Public Analytics Setting */}+ <div className="flex items-center justify-between">+ <div>+ <Label+ htmlFor="isPublic"+ className="text-sm font-medium text-white"+ >+ Public Analytics+ </Label>+ <p className="text-xs text-muted-foreground mt-1">+ When enabled, anyone can view analytics without logging in+ </p>+ </div>+ <Switch+ id="isPublic"+ checked={isPublic}+ onCheckedChange={setIsPublic}+ />+ </div>++ {/* User ID Salting Setting */}+ <div className="flex items-center justify-between">+ <div>+ <Label+ htmlFor="saltUserIds"+ className="text-sm font-medium text-white"+ >+ Enable User ID Salting+ </Label>+ <p className="text-xs text-muted-foreground mt-1">+ Enhance privacy with daily rotating salts for user IDs+ </p>+ </div>+ <Switch+ id="saltUserIds"+ checked={saltUserIds}+ onCheckedChange={setSaltUserIds}+ />+ </div></div>{error && (diff --git a/client/src/components/SiteSettings/ScriptBuilder.tsx b/client/src/components/SiteSettings/ScriptBuilder.tsxnew file mode 100644index 000000000..689aab69e--- /dev/null+++ b/client/src/components/SiteSettings/ScriptBuilder.tsx@@ -0,0 +1,295 @@+"use client";++import { useState } from "react";+import { CodeSnippet } from "@/components/CodeSnippet";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Switch } from "@/components/ui/switch";+import { BACKEND_URL } from "@/lib/const";+import { Textarea } from "@/components/ui/textarea";++interface ScriptBuilderProps {+ siteId: number;+}++export function ScriptBuilder({ siteId }: ScriptBuilderProps) {+ // Script configuration options+ const [debounceValue, setDebounceValue] = useState(500);+ const [autoTrack, setAutoTrack] = useState(true);+ const [trackQuery, setTrackQuery] = useState(true);+ const [trackOutbound, setTrackOutbound] = useState(true);+ const [skipPatterns, setSkipPatterns] = useState<string[]>([]);+ const [skipPatternsText, setSkipPatternsText] = useState("");+ const [maskPatterns, setMaskPatterns] = useState<string[]>([]);+ const [maskPatternsText, setMaskPatternsText] = useState("");++ // Handle pattern text area changes+ const handleSkipPatternsChange = (+ e: React.ChangeEvent<HTMLTextAreaElement>+ ) => {+ setSkipPatternsText(e.target.value);+ try {+ // Try to parse as JSON if it starts with [ and ends with ]+ if (+ e.target.value.trim().startsWith("[") &&+ e.target.value.trim().endsWith("]")+ ) {+ setSkipPatterns(JSON.parse(e.target.value.trim()));+ } else {+ // Otherwise treat as line-separated values+ setSkipPatterns(+ e.target.value+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line.length > 0)+ );+ }+ } catch (err) {+ // If parsing fails, split by new lines+ setSkipPatterns(+ e.target.value+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line.length > 0)+ );+ }+ };++ const handleMaskPatternsChange = (+ e: React.ChangeEvent<HTMLTextAreaElement>+ ) => {+ setMaskPatternsText(e.target.value);+ try {+ // Try to parse as JSON if it starts with [ and ends with ]+ if (+ e.target.value.trim().startsWith("[") &&+ e.target.value.trim().endsWith("]")+ ) {+ setMaskPatterns(JSON.parse(e.target.value.trim()));+ } else {+ // Otherwise treat as line-separated values+ setMaskPatterns(+ e.target.value+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line.length > 0)+ );+ }+ } catch (err) {+ // If parsing fails, split by new lines+ setMaskPatterns(+ e.target.value+ .split("\n")+ .map((line) => line.trim())+ .filter((line) => line.length > 0)+ );+ }+ };++ // Generate tracking script dynamically based on options+ const trackingScript = `<script+ src="${BACKEND_URL}/script.js"+ data-site-id="${siteId}"${+ debounceValue !== 500+ ? `+ data-debounce="${debounceValue}"`+ : ""+ }${+ !autoTrack+ ? `+ data-track-spa="false"`+ : ""+ }${+ !trackQuery+ ? `+ data-track-query="false"`+ : ""+ }${+ !trackOutbound+ ? `+ data-track-outbound="false"`+ : ""+ }${+ skipPatterns.length > 0+ ? `+ data-skip-patterns='${JSON.stringify(skipPatterns)}'`+ : ""+ }${+ maskPatterns.length > 0+ ? `+ data-mask-patterns='${JSON.stringify(maskPatterns)}'`+ : ""+ }+ defer+/>`;++ return (+ <div className="space-y-6">+ <div className="space-y-3">+ <div>+ <h4 className="text-sm font-semibold text-foreground">+ Tracking Script+ </h4>+ <p className="text-xs text-muted-foreground">+ Add this script to the <code><head></code> of your website+ </p>+ </div>+ <CodeSnippet language="HTML" code={trackingScript} />++ {/* Script Options Section */}+ <div className="space-y-4">+ {/* Auto Track (SPA) Option */}+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <div>+ <Label+ htmlFor="autoTrack"+ className="text-sm font-medium text-foreground block"+ >+ Automatically track SPA navigation+ </Label>+ <p className="text-xs text-muted-foreground mt-1">+ For SPAs: track page views when URL changes (using History+ API)+ </p>+ </div>+ <Switch+ id="autoTrack"+ checked={autoTrack}+ onCheckedChange={setAutoTrack}+ />+ </div>+ </div>++ {/* Track Query Params Option */}+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <div>+ <Label+ htmlFor="trackQuery"+ className="text-sm font-medium text-foreground block"+ >+ Track URL query parameters+ </Label>+ <p className="text-xs text-muted-foreground mt-1">+ Include query parameters in tracked URLs (may contain+ sensitive data)+ </p>+ </div>+ <Switch+ id="trackQuery"+ checked={trackQuery}+ onCheckedChange={setTrackQuery}+ />+ </div>+ </div>++ {/* Track Outbound Links Option */}+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <div>+ <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}+ />+ </div>+ </div>++ {/* Skip Patterns Option */}+ <div className="space-y-2">+ <div>+ <Label+ htmlFor="skipPatterns"+ className="text-sm font-medium text-foreground block"+ >+ Skip Patterns+ </Label>+ <p className="text-xs text-muted-foreground mt-1">+ URL patterns to exclude from tracking (one per line)+ </p>+ <p className="text-xs text-muted-foreground mt-1">+ Use <code>*</code> for single segment wildcard, <code>**</code>{" "}+ for multi-segment wildcard+ </p>+ <Textarea+ id="skipPatterns"+ placeholder="/admin/** /preview/*"+ className="mt-2 font-mono text-sm"+ value={skipPatternsText}+ onChange={handleSkipPatternsChange}+ />+ </div>+ </div>++ {/* Mask Patterns Option */}+ <div className="space-y-2">+ <div>+ <Label+ htmlFor="maskPatterns"+ className="text-sm font-medium text-foreground block"+ >+ Mask Patterns+ </Label>+ <p className="text-xs text-muted-foreground mt-1">+ URL patterns to anonymize in analytics (one per line)+ </p>+ <p className="text-xs text-muted-foreground mt-1">+ E.g. <code>/users/*/profile</code> will hide usernames,{" "}+ <code>/orders/**</code> will hide order details+ </p>+ <Textarea+ id="maskPatterns"+ placeholder="/users/*/profile /orders/**"+ className="mt-2 font-mono text-sm"+ value={maskPatternsText}+ onChange={handleMaskPatternsChange}+ />+ </div>+ </div>++ {/* Debounce Option */}+ <div className="space-y-2">+ <div className="flex flex-col gap-1.5">+ <Label+ htmlFor="debounce"+ className="text-sm font-medium text-foreground"+ >+ Debounce Duration (ms)+ </Label>+ <div className="flex items-center gap-2">+ <Input+ id="debounce"+ type="number"+ min="0"+ max="5000"+ value={debounceValue}+ onChange={(e) =>+ setDebounceValue(parseInt(e.target.value) || 0)+ }+ className="max-w-[120px]"+ />+ <span className="text-xs text-muted-foreground">+ Default: 500ms+ </span>+ </div>+ </div>+ <p className="text-xs text-muted-foreground">+ Time to wait before tracking a pageview after URL changes+ </p>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/client/src/components/SiteSettings/SiteSettings.tsx b/client/src/components/SiteSettings/SiteSettings.tsxindex adcd8627d..e533227bd 100644--- a/client/src/components/SiteSettings/SiteSettings.tsx+++ b/client/src/components/SiteSettings/SiteSettings.tsx@@ -5,7 +5,6 @@ import { useRouter } from "next/navigation";import { useState } from "react";import { toast } from "sonner";-import { CodeSnippet } from "@/components/CodeSnippet";import {AlertDialog,AlertDialogAction,@@ -31,6 +30,7 @@ import {import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import { Switch } from "@/components/ui/switch";+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";import {changeSiteDomain,@@ -42,7 +42,7 @@ import {useGetSite,useGetSites,} from "@/api/admin/sites";-import { BACKEND_URL } from "@/lib/const";+import { ScriptBuilder } from "./ScriptBuilder";export function SiteSettings({siteId,@@ -77,27 +77,7 @@ export function SiteSettingsInner({const [isChangingSalt, setIsChangingSalt] = useState(false);const [isDeleting, setIsDeleting] = useState(false);const [dialogOpen, setDialogOpen] = useState(false);-- // Script configuration options- const [debounceValue, setDebounceValue] = useState(500);- const [autoTrack, setAutoTrack] = useState(true);-- // Generate tracking script dynamically based on options- const trackingScript = `<script- src="${BACKEND_URL}/script.js"- data-site-id="${siteMetadata.siteId}"${- debounceValue !== 500- ? `- data-debounce="${debounceValue}"`- : ""- }${- !autoTrack- ? `- data-auto-track="false"`- : ""- }- defer-/>`;+ const [activeTab, setActiveTab] = useState("script");const handleDomainChange = async () => {if (!newDomain) {@@ -192,180 +172,133 @@ export function SiteSettingsInner({Manage settings for {siteMetadata.domain}</DialogDescription></DialogHeader>- <div className="space-y-6 py-4 max-h-[70vh] overflow-y-auto">- <div className="space-y-3">- <div>- <h4 className="text-sm font-semibold text-foreground">- Tracking Script- </h4>- <p className="text-xs text-muted-foreground">- Add this script to the <code><head></code> of your website- </p>- </div>- <CodeSnippet language="HTML" code={trackingScript} />- {/* Script Options Section */}- <div className="space-y-3 pl-4">- <h4 className="text-sm font-semibold text-foreground">- Script Options- </h4>- <div className="space-y-2">- <div className="flex flex-col gap-1.5">- <Label- htmlFor="debounce"- className="text-sm font-medium text-foreground"- >- Debounce Duration (ms)- </Label>- <div className="flex items-center gap-2">- <Input- id="debounce"- type="number"- min="0"- max="5000"- value={debounceValue}- onChange={(e) =>- setDebounceValue(parseInt(e.target.value) || 0)- }- className="max-w-[120px]"- />- <span className="text-xs text-muted-foreground">- Default: 500ms- </span>- </div>- </div>- <p className="text-xs text-muted-foreground">- Time to wait before tracking a pageview after URL changes+ <Tabs value={activeTab} onValueChange={setActiveTab} className="pb-4">+ <TabsList className="grid w-full grid-cols-2">+ <TabsTrigger value="script">Tracking Script</TabsTrigger>+ <TabsTrigger value="settings">Site Settings</TabsTrigger>+ </TabsList>++ <TabsContent+ value="script"+ className="pt-4 space-y-4 max-h-[70vh] overflow-y-auto"+ >+ <ScriptBuilder siteId={siteMetadata.siteId} />+ </TabsContent>++ <TabsContent+ value="settings"+ className="pt-4 space-y-6 max-h-[70vh] overflow-y-auto"+ >+ {/* Public Analytics Section */}+ <div className="flex items-center justify-between">+ <div>+ <Label+ htmlFor="publicAnalytics"+ className="text-sm font-medium text-foreground block"+ >+ Public Analytics+ </Label>+ <p className="text-xs text-muted-foreground mt-1">+ When enabled, anyone can view your site analytics without+ logging in</p></div>- <div className="space-y-2">- <div className="flex items-center justify-between">- <div>- <Label- htmlFor="autoTrack"- className="text-sm font-medium text-foreground block"- >- Automatically track URL changes- </Label>- <p className="text-xs text-muted-foreground mt-1">- For SPAs: track page views when URL changes (using History- API)- </p>- </div>- <Switch- id="autoTrack"- checked={autoTrack}- onCheckedChange={setAutoTrack}- />- </div>- </div>+ <Switch+ id="publicAnalytics"+ checked={isPublic}+ disabled={isChangingPublic}+ onCheckedChange={handlePublicToggle}+ /></div>- </div>- {/* Public Analytics Section */}- <div className="flex items-center justify-between">- <div>- <Label- htmlFor="publicAnalytics"- className="text-sm font-medium text-foreground block"- >- Public Analytics- </Label>- <p className="text-xs text-muted-foreground mt-1">- When enabled, anyone can view your site analytics without- logging in- </p>+ {/* User ID Salting Section */}+ <div className="flex items-center justify-between">+ <div>+ <Label+ htmlFor="saltUserIds"+ className="text-sm font-medium text-foreground block"+ >+ Enable User ID Salting+ </Label>+ <p className="text-xs text-muted-foreground mt-1">+ When enabled, user IDs will be salted with a daily rotating+ key for enhanced privacy+ </p>+ </div>+ <Switch+ id="saltUserIds"+ checked={isSalting}+ disabled={isChangingSalt}+ onCheckedChange={handleSaltToggle}+ /></div>- <Switch- id="publicAnalytics"- checked={isPublic}- disabled={isChangingPublic}- onCheckedChange={handlePublicToggle}- />- </div>- {/* User ID Salting Section */}- <div className="flex items-center justify-between">- <div>- <Label- htmlFor="saltUserIds"- className="text-sm font-medium text-foreground block"- >- Enable User ID Salting- </Label>- <p className="text-xs text-muted-foreground mt-1">- When enabled, user IDs will be salted with a daily rotating key- for enhanced privacy- </p>+ {/* Domain Settings Section */}+ <div className="space-y-3">+ <div>+ <h4 className="text-sm font-semibold text-foreground">+ Change Domain+ </h4>+ <p className="text-xs text-muted-foreground">+ Update the domain for this site+ </p>+ </div>+ <div className="flex space-x-2">+ <Input+ value={newDomain}+ onChange={(e) => setNewDomain(e.target.value)}+ placeholder="example.com"+ />+ <Button+ variant="outline"+ onClick={handleDomainChange}+ disabled={+ isChangingDomain || newDomain === siteMetadata.domain+ }+ >+ {isChangingDomain ? "Updating..." : "Update"}+ </Button>+ </div></div>- <Switch- id="saltUserIds"- checked={isSalting}- disabled={isChangingSalt}- onCheckedChange={handleSaltToggle}- />- </div>- {/* Domain Settings Section */}- <div className="space-y-3">- <div>- <h4 className="text-sm font-semibold text-foreground">- Change Domain+ {/* Danger Zone Section */}+ <div className="space-y-3 pt-3">+ <h4 className="text-sm font-semibold text-destructive">+ Danger Zone</h4>- <p className="text-xs text-muted-foreground">- Update the domain for this site- </p>- </div>- <div className="flex space-x-2">- <Input- value={newDomain}- onChange={(e) => setNewDomain(e.target.value)}- placeholder="example.com"- />- <Button- variant="outline"- onClick={handleDomainChange}- disabled={isChangingDomain || newDomain === siteMetadata.domain}- >- {isChangingDomain ? "Updating..." : "Update"}- </Button>+ <AlertDialog>+ <AlertDialogTrigger asChild>+ <Button variant="destructive" className="w-full">+ <AlertTriangle className="h-4 w-4 mr-2" />+ Delete Site+ </Button>+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>+ Are you absolutely sure?+ </AlertDialogTitle>+ <AlertDialogDescription>+ This action cannot be undone. This will permanently delete+ the site "{siteMetadata.name}" and all of its+ analytics data.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ onClick={handleDelete}+ disabled={isDeleting}+ variant="destructive"+ >+ {isDeleting ? "Deleting..." : "Yes, delete site"}+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog></div>- </div>-- {/* Danger Zone Section */}- <div className="space-y-3 pt-3">- <h4 className="text-sm font-semibold text-destructive">- Danger Zone- </h4>- <AlertDialog>- <AlertDialogTrigger asChild>- <Button variant="destructive" className="w-full">- <AlertTriangle className="h-4 w-4 mr-2" />- Delete Site- </Button>- </AlertDialogTrigger>- <AlertDialogContent>- <AlertDialogHeader>- <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>- <AlertDialogDescription>- This action cannot be undone. This will permanently delete- the site "{siteMetadata.name}" and all of its- analytics data.- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogCancel>Cancel</AlertDialogCancel>- <AlertDialogAction- onClick={handleDelete}- disabled={isDeleting}- variant="destructive"- >- {isDeleting ? "Deleting..." : "Yes, delete site"}- </AlertDialogAction>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog>- </div>- </div>+ </TabsContent>+ </Tabs><DialogFooter><DialogClose asChild>diff --git a/client/src/components/ui/textarea.tsx b/client/src/components/ui/textarea.tsxnew file mode 100644index 000000000..a065d8853--- /dev/null+++ b/client/src/components/ui/textarea.tsx@@ -0,0 +1,22 @@+import * as React from "react"++import { cn } from "@/lib/utils"++const Textarea = React.forwardRef<+ HTMLTextAreaElement,+ React.ComponentProps<"textarea">+>(({ className, ...props }, ref) => {+ return (+ <textarea+ className={cn(+ "flex min-h-[60px] w-full rounded-md border border-neutral-200 bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-neutral-500 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-950 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:border-neutral-800 dark:placeholder:text-neutral-400 dark:focus-visible:ring-neutral-300",+ className+ )}+ ref={ref}+ {...props}+ />+ )+})+Textarea.displayName = "Textarea"++export { Textarea }diff --git a/server/src/api/sites/addSite.ts b/server/src/api/sites/addSite.tsindex d13b798d7..b4eeb1001 100644--- a/server/src/api/sites/addSite.ts+++ b/server/src/api/sites/addSite.ts@@ -7,11 +7,23 @@ import { siteConfig } from "../../lib/siteConfig.js";export async function addSite(request: FastifyRequest<{- Body: { domain: string; name: string; organizationId: string };+ Body: {+ domain: string;+ name: string;+ organizationId: string;+ public?: boolean;+ saltUserIds?: boolean;+ };}>,reply: FastifyReply) {- const { domain, name, organizationId } = request.body;+ const {+ domain,+ name,+ organizationId,+ public: isPublic,+ saltUserIds,+ } = request.body;// Validate domain format using regexconst domainRegex =@@ -85,6 +97,8 @@ export async function addSite(name,createdBy: session.user.id,organizationId,+ public: isPublic || false,+ saltUserIds: saltUserIds || false,}).returning();