🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
localhost tracking (#415)
Bill Yangb808dc5cd980
diff --git a/.claude/settings.local.json b/.claude/settings.local.jsonindex 2b587f0c2..ce8e3d913 100644--- a/.claude/settings.local.json+++ b/.claude/settings.local.json@@ -12,7 +12,10 @@"Bash(rm:*)","Bash(tsc --noEmit)","Bash(npx tsc:*)",- "Bash(npm run build:*)"+ "Bash(npm run build:*)",+ "Bash(npm run:*)",+ "Bash(mv:*)",+ "Bash(chmod:*)"]},"enableAllProjectMcpServers": falsediff --git a/client/src/api/admin/apiKey.ts b/client/src/api/admin/apiKey.tsnew file mode 100644index 000000000..d2413786f--- /dev/null+++ b/client/src/api/admin/apiKey.ts@@ -0,0 +1,75 @@+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { authedFetch } from "../utils";++interface ApiConfigResponse {+ apiKey: string | null;+}++interface UpdateApiConfigResponse {+ apiKey: string | null;+}++// Get API config+export const useGetApiConfig = (siteId: number) => {+ return useQuery({+ queryKey: ["apiConfig", siteId],+ queryFn: async () => {+ const response = await authedFetch<{+ success: boolean;+ data: ApiConfigResponse;+ }>(`/site/${siteId}/api-config`);+ return response.data;+ },+ enabled: !!siteId,+ });+};++// Generate API key+export const useGenerateApiKey = () => {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: async (siteId: number) => {+ const response = await authedFetch<{+ success: boolean;+ data: UpdateApiConfigResponse;+ }>(+ `/site/${siteId}/api-config`,+ {},+ {+ method: "POST",+ data: { action: "generate_api_key" },+ }+ );+ return response.data;+ },+ onSuccess: (_, siteId) => {+ queryClient.invalidateQueries({ queryKey: ["apiConfig", siteId] });+ },+ });+};++// Revoke API key+export const useRevokeApiKey = () => {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: async (siteId: number) => {+ const response = await authedFetch<{+ success: boolean;+ data: UpdateApiConfigResponse;+ }>(+ `/site/${siteId}/api-config`,+ {},+ {+ method: "POST",+ data: { action: "revoke_api_key" },+ }+ );+ return response.data;+ },+ onSuccess: (_, siteId) => {+ queryClient.invalidateQueries({ queryKey: ["apiConfig", siteId] });+ },+ });+};diff --git a/client/src/components/SiteSettings/ApiKeyManager.tsx b/client/src/components/SiteSettings/ApiKeyManager.tsxnew file mode 100644index 000000000..ae6002196--- /dev/null+++ b/client/src/components/SiteSettings/ApiKeyManager.tsx@@ -0,0 +1,171 @@+"use client";++import { Copy, Eye, EyeOff, Key } from "lucide-react";+import { useState } from "react";+import { toast } from "sonner";++import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogTrigger,+} from "@/components/ui/alert-dialog";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Skeleton } from "@/components/ui/skeleton";++import {+ useGenerateApiKey,+ useGetApiConfig,+ useRevokeApiKey,+} from "../../api/admin/apiKey";++interface ApiKeyManagerProps {+ siteId: number;+ disabled?: boolean;+}++export function ApiKeyManager({+ siteId,+ disabled = false,+}: ApiKeyManagerProps) {+ const [showApiKey, setShowApiKey] = useState(false);++ // API key hooks+ const { data: apiConfig, isLoading: isLoadingApiConfig } =+ useGetApiConfig(siteId);+ const generateApiKey = useGenerateApiKey();+ const revokeApiKey = useRevokeApiKey();++ // Use the API key from config or from newly generated key+ const apiKey = apiConfig?.apiKey || null;++ return (+ <div className="space-y-4">+ <div>+ <h4 className="text-sm font-semibold text-foreground">API Key</h4>+ <p className="text-xs text-muted-foreground mt-1">+ Generate an API key to track events using the API endpoint or from+ localhost during development.+ </p>+ </div>++ {isLoadingApiConfig ? (+ <div className="flex space-x-2">+ <Skeleton className="h-9 w-32" />+ </div>+ ) : apiKey ? (+ <div className="space-y-4">+ <div className="flex items-center space-x-2">+ <div className="flex-1">+ <div className="relative">+ <Input+ type={showApiKey ? "text" : "password"}+ value={+ showApiKey && apiKey+ ? apiKey+ : "rb_••••••••••••••••••••••••••••••••••"+ }+ readOnly+ className="pr-20 font-mono text-xs"+ />+ <div className="absolute right-1 top-1 flex space-x-1">+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={() => setShowApiKey(!showApiKey)}+ className="h-7 px-2"+ >+ {showApiKey ? (+ <EyeOff className="h-3 w-3" />+ ) : (+ <Eye className="h-3 w-3" />+ )}+ </Button>+ {apiKey && (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={() => {+ navigator.clipboard.writeText(apiKey);+ toast.success("API key copied to clipboard");+ }}+ className="h-7 px-2"+ >+ <Copy className="h-3 w-3" />+ </Button>+ )}+ </div>+ </div>+ </div>+ </div>++ <div>+ <AlertDialog>+ <AlertDialogTrigger asChild>+ <Button+ variant="destructive"+ size="sm"+ disabled={disabled || revokeApiKey.isPending}+ >+ Revoke API Key+ </Button>+ </AlertDialogTrigger>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Revoke API Key?</AlertDialogTitle>+ <AlertDialogDescription>+ This will immediately invalidate the current API key. Any+ applications using this key will stop working.+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ onClick={async () => {+ try {+ await revokeApiKey.mutateAsync(siteId);+ setShowApiKey(false);+ toast.success("API key revoked successfully");+ } catch (error) {+ toast.error("Failed to revoke API key");+ }+ }}+ variant="destructive"+ >+ Revoke Key+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </div>+ </div>+ ) : (+ <Button+ onClick={async () => {+ try {+ const result = await generateApiKey.mutateAsync(siteId);+ if (result.apiKey) {+ setShowApiKey(true);+ toast.success("API key generated successfully");+ }+ } catch (error) {+ toast.error("Failed to generate API key");+ }+ }}+ disabled={disabled || generateApiKey.isPending}+ >+ <Key className="h-4 w-4 mr-2" />+ Generate API Key+ </Button>+ )}+ </div>+ );+}diff --git a/client/src/components/SiteSettings/SiteConfiguration.tsx b/client/src/components/SiteSettings/SiteConfiguration.tsxnew file mode 100644index 000000000..397cd41ab--- /dev/null+++ b/client/src/components/SiteSettings/SiteConfiguration.tsx@@ -0,0 +1,288 @@+"use client";++import { AlertTriangle } from "lucide-react";+import { useRouter } from "next/navigation";+import { useState } from "react";+import { toast } from "sonner";++import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+ AlertDialogTrigger,+} from "@/components/ui/alert-dialog";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Switch } from "@/components/ui/switch";++import {+ changeSiteBlockBots,+ changeSiteDomain,+ changeSitePublic,+ changeSiteSalt,+ deleteSite,+ SiteResponse,+ useGetSitesFromOrg,+} from "@/api/admin/sites";++interface SiteConfigurationProps {+ siteMetadata: SiteResponse;+ disabled?: boolean;+ onClose?: () => void;+}++export function SiteConfiguration({+ siteMetadata,+ disabled = false,+ onClose+}: SiteConfigurationProps) {+ const { refetch } = useGetSitesFromOrg(siteMetadata?.organizationId ?? "");+ const router = useRouter();++ const [newDomain, setNewDomain] = useState(siteMetadata.domain);+ const [isChangingDomain, setIsChangingDomain] = useState(false);+ const [isPublic, setIsPublic] = useState(siteMetadata.public || false);+ const [isChangingPublic, setIsChangingPublic] = useState(false);+ const [isSalting, setIsSalting] = useState(siteMetadata.saltUserIds || false);+ const [isChangingSalt, setIsChangingSalt] = useState(false);+ const [isBlockingBots, setIsBlockingBots] = useState(+ siteMetadata.blockBots || false+ );+ const [isChangingBlockBots, setIsChangingBlockBots] = useState(false);+ const [isDeleting, setIsDeleting] = useState(false);++ const handleDomainChange = async () => {+ if (!newDomain) {+ toast.error("Domain cannot be empty");+ return;+ }++ try {+ setIsChangingDomain(true);+ await changeSiteDomain(siteMetadata.siteId, newDomain);+ toast.success("Domain updated successfully");+ router.refresh();+ refetch();+ } catch (error) {+ console.error("Error changing domain:", error);+ toast.error("Failed to update domain");+ } finally {+ setIsChangingDomain(false);+ }+ };++ const handleDelete = async () => {+ try {+ setIsDeleting(true);+ await deleteSite(siteMetadata.siteId);+ toast.success("Site deleted successfully");+ router.push("/");+ onClose?.();+ refetch();+ } catch (error) {+ console.error("Error deleting site:", error);+ toast.error("Failed to delete site");+ } finally {+ setIsDeleting(false);+ }+ };++ const handlePublicToggle = async (checked: boolean) => {+ try {+ setIsChangingPublic(true);+ await changeSitePublic(siteMetadata.siteId, checked);+ setIsPublic(checked);+ toast.success(+ checked ? "Site analytics made public" : "Site analytics made private"+ );+ refetch();+ } catch (error) {+ console.error("Error changing public status:", error);+ toast.error("Failed to update public status");+ setIsPublic(!checked); // Revert UI state on error+ } finally {+ setIsChangingPublic(false);+ }+ };++ const handleSaltToggle = async (checked: boolean) => {+ try {+ setIsChangingSalt(true);+ await changeSiteSalt(siteMetadata.siteId, checked);+ setIsSalting(checked);+ toast.success(+ checked ? "User ID salting enabled" : "User ID salting disabled"+ );+ refetch();+ } catch (error) {+ console.error("Error changing salt setting:", error);+ toast.error("Failed to update salting setting");+ setIsSalting(!checked); // Revert UI state on error+ } finally {+ setIsChangingSalt(false);+ }+ };++ const handleBlockBotsToggle = async (checked: boolean) => {+ try {+ setIsChangingBlockBots(true);+ await changeSiteBlockBots(siteMetadata.siteId, checked);+ setIsBlockingBots(checked);+ toast.success(checked ? "Bot blocking enabled" : "Bot blocking disabled");+ refetch();+ } catch (error) {+ console.error("Error changing bot blocking setting:", error);+ toast.error("Failed to update bot blocking setting");+ setIsBlockingBots(!checked); // Revert UI state on error+ } finally {+ setIsChangingBlockBots(false);+ }+ };++ return (+ <div 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>+ <Switch+ id="publicAnalytics"+ checked={isPublic}+ disabled={isChangingPublic || disabled}+ 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>+ </div>+ <Switch+ id="saltUserIds"+ checked={isSalting}+ disabled={isChangingSalt || disabled}+ onCheckedChange={handleSaltToggle}+ />+ </div>++ {/* Bot Blocking Section */}+ <div className="flex items-center justify-between">+ <div>+ <Label+ htmlFor="blockBots"+ className="text-sm font-medium text-foreground block"+ >+ Block Bot Traffic+ </Label>+ <p className="text-xs text-muted-foreground mt-1">+ When enabled, traffic from known bots and crawlers will not be+ tracked+ </p>+ </div>+ <Switch+ id="blockBots"+ checked={isBlockingBots}+ disabled={isChangingBlockBots || disabled}+ onCheckedChange={handleBlockBotsToggle}+ />+ </div>++ {/* 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.toLowerCase())}+ placeholder="example.com"+ />+ <Button+ variant="outline"+ onClick={handleDomainChange}+ disabled={+ isChangingDomain ||+ newDomain === siteMetadata.domain ||+ disabled+ }+ >+ {isChangingDomain ? "Updating..." : "Update"}+ </Button>+ </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"+ disabled={disabled}+ >+ <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>+ );+}\ No newline at end of filediff --git a/client/src/components/SiteSettings/SiteSettings.tsx b/client/src/components/SiteSettings/SiteSettings.tsxindex 0b092d291..6358a17a7 100644--- a/client/src/components/SiteSettings/SiteSettings.tsx+++ b/client/src/components/SiteSettings/SiteSettings.tsx@@ -1,21 +1,8 @@"use client";-import { AlertTriangle, Settings } from "lucide-react";-import { useRouter } from "next/navigation";+import { Settings } from "lucide-react";import { useState } from "react";-import { toast } from "sonner";-import {- AlertDialog,- AlertDialogAction,- AlertDialogCancel,- AlertDialogContent,- AlertDialogDescription,- AlertDialogFooter,- AlertDialogHeader,- AlertDialogTitle,- AlertDialogTrigger,-} from "@/components/ui/alert-dialog";import { Button } from "@/components/ui/button";import {Dialog,@@ -27,23 +14,13 @@ import {DialogTitle,DialogTrigger,} from "@/components/ui/dialog";-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 {- changeSiteBlockBots,- changeSiteDomain,- changeSitePublic,- changeSiteSalt,- deleteSite,- SiteResponse,- useGetSite,- useGetSitesFromOrg,-} from "@/api/admin/sites";+import { SiteResponse, useGetSite } from "@/api/admin/sites";import { useUserOrganizations } from "../../api/admin/organizations";+import { ApiKeyManager } from "./ApiKeyManager";import { ScriptBuilder } from "./ScriptBuilder";+import { SiteConfiguration } from "./SiteConfiguration";export function SiteSettings({siteId,@@ -68,116 +45,14 @@ function SiteSettingsInner({siteMetadata: SiteResponse;trigger?: React.ReactNode;}) {- const { refetch } = useGetSitesFromOrg(siteMetadata?.organizationId ?? "");const { data: userOrganizationsData } = useUserOrganizations();const disabled =!userOrganizationsData?.[0]?.role ||userOrganizationsData?.[0]?.role === "member";- const router = useRouter();- const [newDomain, setNewDomain] = useState(siteMetadata.domain);- const [isChangingDomain, setIsChangingDomain] = useState(false);- const [isPublic, setIsPublic] = useState(siteMetadata.public || false);- const [isChangingPublic, setIsChangingPublic] = useState(false);- const [isSalting, setIsSalting] = useState(siteMetadata.saltUserIds || false);- const [isChangingSalt, setIsChangingSalt] = useState(false);- const [isBlockingBots, setIsBlockingBots] = useState(- siteMetadata.blockBots || false- );- const [isChangingBlockBots, setIsChangingBlockBots] = useState(false);- const [isDeleting, setIsDeleting] = useState(false);const [dialogOpen, setDialogOpen] = useState(false);const [activeTab, setActiveTab] = useState("script");- const handleDomainChange = async () => {- if (!newDomain) {- toast.error("Domain cannot be empty");- return;- }-- try {- setIsChangingDomain(true);- await changeSiteDomain(siteMetadata.siteId, newDomain);- toast.success("Domain updated successfully");- router.refresh();- setDialogOpen(false);- refetch();- } catch (error) {- console.error("Error changing domain:", error);- toast.error("Failed to update domain");- } finally {- setIsChangingDomain(false);- }- };-- const handleDelete = async () => {- try {- setIsDeleting(true);- await deleteSite(siteMetadata.siteId);- toast.success("Site deleted successfully");- router.push("/");- setDialogOpen(false);- refetch();- } catch (error) {- console.error("Error deleting site:", error);- toast.error("Failed to delete site");- } finally {- setIsDeleting(false);- }- };-- const handlePublicToggle = async (checked: boolean) => {- try {- setIsChangingPublic(true);- await changeSitePublic(siteMetadata.siteId, checked);- setIsPublic(checked);- toast.success(- checked ? "Site analytics made public" : "Site analytics made private"- );- refetch();- } catch (error) {- console.error("Error changing public status:", error);- toast.error("Failed to update public status");- setIsPublic(!checked); // Revert UI state on error- } finally {- setIsChangingPublic(false);- }- };-- const handleSaltToggle = async (checked: boolean) => {- try {- setIsChangingSalt(true);- await changeSiteSalt(siteMetadata.siteId, checked);- setIsSalting(checked);- toast.success(- checked ? "User ID salting enabled" : "User ID salting disabled"- );- refetch();- } catch (error) {- console.error("Error changing salt setting:", error);- toast.error("Failed to update salting setting");- setIsSalting(!checked); // Revert UI state on error- } finally {- setIsChangingSalt(false);- }- };-- const handleBlockBotsToggle = async (checked: boolean) => {- try {- setIsChangingBlockBots(true);- await changeSiteBlockBots(siteMetadata.siteId, checked);- setIsBlockingBots(checked);- toast.success(checked ? "Bot blocking enabled" : "Bot blocking disabled");- refetch();- } catch (error) {- console.error("Error changing bot blocking setting:", error);- toast.error("Failed to update bot blocking setting");- setIsBlockingBots(!checked); // Revert UI state on error- } finally {- setIsChangingBlockBots(false);- }- };-if (!siteMetadata) {return null;}@@ -199,8 +74,9 @@ function SiteSettingsInner({</DialogDescription></DialogHeader><Tabs value={activeTab} onValueChange={setActiveTab} className="pb-4">- <TabsList className="grid w-full grid-cols-2">+ <TabsList className="grid w-full grid-cols-3"><TabsTrigger value="script">Tracking Script</TabsTrigger>+ <TabsTrigger value="apikey">API Key</TabsTrigger><TabsTrigger value="settings">Site Settings</TabsTrigger></TabsList>@@ -212,145 +88,18 @@ function SiteSettingsInner({</TabsContent><TabsContent- value="settings"- className="pt-4 space-y-6 max-h-[70vh] overflow-y-auto"+ value="apikey"+ className="pt-4 space-y-4 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>- <Switch- id="publicAnalytics"- checked={isPublic}- disabled={isChangingPublic || disabled}- 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>- </div>- <Switch- id="saltUserIds"- checked={isSalting}- disabled={isChangingSalt || disabled}- onCheckedChange={handleSaltToggle}- />- </div>-- {/* Bot Blocking Section */}- <div className="flex items-center justify-between">- <div>- <Label- htmlFor="blockBots"- className="text-sm font-medium text-foreground block"- >- Block Bot Traffic- </Label>- <p className="text-xs text-muted-foreground mt-1">- When enabled, traffic from known bots and crawlers will not be- tracked- </p>- </div>- <Switch- id="blockBots"- checked={isBlockingBots}- disabled={isChangingBlockBots || disabled}- onCheckedChange={handleBlockBotsToggle}- />- </div>-- {/* 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.toLowerCase())}- placeholder="example.com"- />- <Button- variant="outline"- onClick={handleDomainChange}- disabled={- isChangingDomain ||- newDomain === siteMetadata.domain ||- disabled- }- >- {isChangingDomain ? "Updating..." : "Update"}- </Button>- </div>- </div>+ <ApiKeyManager siteId={siteMetadata.siteId} disabled={disabled} />+ </TabsContent>- {/* 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"- disabled={disabled}- >- <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>+ <TabsContent value="settings">+ <SiteConfiguration+ siteMetadata={siteMetadata}+ disabled={disabled}+ onClose={() => setDialogOpen(false)}+ /></TabsContent></Tabs>@@ -362,4 +111,4 @@ function SiteSettingsInner({</DialogContent></Dialog>);-}+}\ No newline at end of filediff --git a/client/src/components/SiteSettings/index.ts b/client/src/components/SiteSettings/index.tsnew file mode 100644index 000000000..57f65c727--- /dev/null+++ b/client/src/components/SiteSettings/index.ts@@ -0,0 +1,4 @@+export { SiteSettings } from "./SiteSettings";+export { ScriptBuilder } from "./ScriptBuilder";+export { ApiKeyManager } from "./ApiKeyManager";+export { SiteConfiguration } from "./SiteConfiguration";\ No newline at end of filediff --git a/docs/src/app/layout.jsx b/docs/src/app/layout.jsxindex 5236fbc39..4da779aac 100644--- a/docs/src/app/layout.jsx+++ b/docs/src/app/layout.jsx@@ -149,6 +149,9 @@ export default async function RootLayout({ children }) {/>);const pageMap = await getPageMap();++ const isDev = process.env.NODE_ENV === "development";+return (<html lang="en" dir="ltr" suppressHydrationWarning><Head@@ -158,23 +161,14 @@ export default async function RootLayout({ children }) {lightness: 51,}}/>- {/* <script- src="https://app.rybbit.io/api/script.js"- site-id="2"- defer- data-enable-replay="true"- /> */}<scriptsrc="https://demo.rybbit.io/api/script.js"data-site-id="21"deferdata-enable-replay="true"- ></script>- <script- src="https://amdtest.tomato.gg/api/script.js"- data-site-id="2"- defer- data-enable-replay="true"+ {...(isDev && {+ "data-api-key": process.env.NEXT_PUBLIC_RYBBIT_API_KEY,+ })}></script><body><PostHogProvider>diff --git a/docs/src/content/_meta.js b/docs/src/content/_meta.jsindex a3fb28f01..2a010af1d 100644--- a/docs/src/content/_meta.js+++ b/docs/src/content/_meta.js@@ -9,6 +9,7 @@ export default {"track-events": "",sdks: "SDKs",guides: "",+ "localhost-tracking": "","hiding-own-traffic": "",_4: {type: "separator",diff --git a/docs/src/content/localhost-tracking.mdx b/docs/src/content/localhost-tracking.mdxnew file mode 100644index 000000000..a9cd50ebc--- /dev/null+++ b/docs/src/content/localhost-tracking.mdx@@ -0,0 +1,95 @@+import { Steps } from 'nextra/components'+import { Callout } from 'nextra/components'++# Localhost Tracking++By default, Rybbit validates tracking events come from your registered domain. During development, you can use API keys to track from localhost.++<Callout type="warning">+ **Important**: Remember to remove the API key before deploying to production!+</Callout>++## Setup++<Steps>+### Generate API Key++In your site dashboard: Settings → API Key tab → Generate API Key++### Add to Script++```html+<script+ defer+ src="https://your-rybbit-instance.com/api/script.js"+ data-site-id="YOUR_SITE_ID"+ data-api-key="rb_your_api_key_here">+</script>+```++### Remove for Production++<Callout type="error">+ Remove the `data-api-key` attribute before deploying!+</Callout>++```html+<!-- Production: NO API KEY -->+<script+ defer+ src="https://your-rybbit-instance.com/api/script.js"+ data-site-id="YOUR_SITE_ID">+</script>+```++</Steps>++## Best Practice: Environment Variables++Use conditional loading to automatically handle development vs production:++```jsx+// Next.js example+export function Analytics() {+ const isDev = process.env.NODE_ENV === 'development';++ return (+ <script+ defer+ src="https://your-rybbit-instance.com/api/script.js"+ data-site-id={process.env.NEXT_PUBLIC_RYBBIT_SITE_ID}+ {...(isDev && { 'data-api-key': process.env.NEXT_PUBLIC_RYBBIT_API_KEY })}+ />+ );+}+```++```javascript+// Vanilla JS example+const script = document.createElement('script');+script.defer = true;+script.src = 'https://your-rybbit-instance.com/api/script.js';+script.setAttribute('data-site-id', 'YOUR_SITE_ID');++// Only add API key in development+if (process.env.NODE_ENV === 'development') {+ script.setAttribute('data-api-key', process.env.RYBBIT_API_KEY);+}++document.head.appendChild(script);+```++## Troubleshooting++**Events not tracking?**+- Verify API key starts with `rb_` and is 35 characters+- Check browser console for errors+- Confirm API key hasn't been revoked++**Accidentally deployed with API key?**+<Steps>+### Immediate fix+1. Revoke the API key in dashboard+2. Deploy without the API key+3. Generate new key for development+</Steps>\ No newline at end of filediff --git a/docs/src/content/script.mdx b/docs/src/content/script.mdxindex 2cc191a04..392543cbe 100644--- a/docs/src/content/script.mdx+++ b/docs/src/content/script.mdx@@ -25,6 +25,7 @@ You can customize the script's behavior using `data-*` attributes on the `<scrip| `data-skip-patterns` | `string` | `[]` | A JSON string array of URL path patterns to ignore. Pageviews matching these patterns won't be tracked. Supports two types of wildcards: `*` (matches within a segment) and `**` (matches across segments). || `data-mask-patterns` | `string` | `[]` | A JSON string array of URL path patterns to mask for privacy. Pageviews matching these patterns will be tracked, but the actual URL path will be replaced with the pattern itself in analytics data. Supports the same wildcards as `data-skip-patterns`. || `data-debounce` | `string` | `"500"`| The delay (in milliseconds) before tracking a pageview after URL changes via the History API (`pushState`, `replaceState`). Set to `0` to disable debouncing. |+| `data-api-key` | `string` | `undefined` | API key for tracking from localhost during development. Bypasses origin validation. See [Localhost Tracking](/localhost-tracking) for details. |### Pattern Matching Detailsdiff --git a/server/examples/api-key-tracking.html b/server/examples/api-key-tracking.htmlnew file mode 100644index 000000000..6481be3ad--- /dev/null+++ b/server/examples/api-key-tracking.html@@ -0,0 +1,61 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>API Key Tracking Example</title>+</head>+<body>+ <h1>Rybbit Analytics - API Key Tracking Example</h1>++ <h2>Setup Instructions:</h2>+ <ol>+ <li>First, generate an API key for your site:+ <pre><code>POST /api/site/{siteId}/api-config+{+ "action": "generate_api_key"+}</code></pre>+ </li>++ <li>Include the script with the API key:+ <pre><code><script+ defer+ src="https://your-analytics-host.com/script.js"+ data-site-id="YOUR_SITE_ID"+ data-api-key="YOUR_API_KEY">+</script></code></pre>+ </li>+ </ol>++ <h2>Test Tracking:</h2>+ <button onclick="window.rybbit.event('button_click', { button: 'test' })">+ Send Test Event+ </button>++ <p>This example shows how to track events using an API key, which bypasses origin validation.</p>++ <h2>Use Cases:</h2>+ <ul>+ <li>Local development (localhost)</li>+ <li>Staging environments</li>+ <li>Server-side tracking (coming soon)</li>+ <li>CI/CD testing</li>+ </ul>++ <h2>Security Notes:</h2>+ <ul>+ <li>Keep API keys secret - treat them like passwords</li>+ <li>Use environment variables to store API keys</li>+ <li>Revoke API keys when no longer needed</li>+ <li>API keys bypass all origin validation</li>+ </ul>++ <!-- Example analytics script inclusion -->+ <script+ defer+ src="http://localhost:4005/script.js"+ data-site-id="1"+ data-api-key="YOUR_API_KEY_HERE">+ </script>+</body>+</html>\ No newline at end of filediff --git a/server/public/script-full.js b/server/public/script-full.jsindex 54df072c0..69a8aa0ae 100644--- a/server/public/script-full.js+++ b/server/public/script-full.js@@ -84,6 +84,7 @@scriptTag.getAttribute("data-mask-patterns"),[]);+ const apiKey = scriptTag.getAttribute("data-api-key") || void 0;return {analyticsHost,siteId,@@ -94,7 +95,8 @@trackOutbound: scriptTag.getAttribute("data-track-outbound") !== "false",enableWebVitals: scriptTag.getAttribute("data-web-vitals") === "true",skipPatterns,- maskPatterns+ maskPatterns,+ apiKey};}@@ -141,6 +143,9 @@if (this.customUserId) {payload.user_id = this.customUserId;}+ if (this.config.apiKey) {+ payload.api_key = this.config.apiKey;+ }return payload;}async sendTrackingData(payload) {diff --git a/server/public/script.js b/server/public/script.jsindex 2acd76959..7662a486e 100644--- a/server/public/script.js+++ b/server/public/script.js@@ -1 +1 @@-"use strict";(()=>{var it=Object.defineProperty;var at=(r,t,e)=>t in r?it(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var h=(r,t,e)=>at(r,typeof t!="symbol"?t+"":t,e);function st(r){let t="__DOUBLE_ASTERISK_TOKEN__",e="__SINGLE_ASTERISK_TOKEN__",i=r.replace(/\*\*/g,t).replace(/\*/g,e).replace(/[.+?^${}()|[\]\\]/g,"\\$&");i=i.replace(new RegExp(`/${t}/`,"g"),"/(?:.+/)?"),i=i.replace(new RegExp(t,"g"),".*"),i=i.replace(/\//g,"\\/");let c=i.replace(new RegExp(e,"g"),"[^/]+");return new RegExp("^"+c+"$")}function P(r,t){for(let e of t)try{if(st(e).test(r))return e}catch(n){console.error(`Invalid pattern: ${e}`,n)}return null}function N(r,t){let e=null;return(...n)=>{e&&clearTimeout(e),e=setTimeout(()=>r(...n),t)}}function W(r){try{let t=window.location.hostname,e=new URL(r).hostname;return e!==t&&e!==""}catch{return!1}}function S(r,t){if(!r)return t;try{let e=JSON.parse(r);return Array.isArray(t)&&!Array.isArray(e)?t:e}catch(e){return console.error("Error parsing JSON:",e),t}}function B(r){let t=r.getAttribute("src");if(!t)return console.error("Script src attribute is missing"),null;let e=t.split("/script.js")[0];if(!e)return console.error("Please provide a valid analytics host"),null;let n=r.getAttribute("data-site-id")||r.getAttribute("site-id");if(!n||isNaN(Number(n)))return console.error("Please provide a valid site ID using the data-site-id attribute"),null;let i=r.getAttribute("data-debounce")?Math.max(0,parseInt(r.getAttribute("data-debounce"))):500,c=S(r.getAttribute("data-skip-patterns"),[]),o=S(r.getAttribute("data-mask-patterns"),[]);return{analyticsHost:e,siteId:n,debounceDuration:i,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",skipPatterns:c,maskPatterns:o}}var b=class{constructor(t){this.customUserId=null;this.config=t,this.loadUserId()}loadUserId(){try{let t=localStorage.getItem("rybbit-user-id");t&&(this.customUserId=t)}catch{}}createBasePayload(){let t=new URL(window.location.href),e=t.pathname;if(t.hash&&t.hash.startsWith("#/")&&(e=t.hash.substring(1)),P(e,this.config.skipPatterns))return null;let n=P(e,this.config.maskPatterns);n&&(e=n);let i={site_id:this.config.siteId,hostname:t.hostname,pathname:e,querystring:this.config.trackQuerystring?t.search:"",screenWidth:window.innerWidth,screenHeight:window.innerHeight,language:navigator.language,page_title:document.title,referrer:document.referrer};return this.customUserId&&(i.user_id=this.customUserId),i}async sendTrackingData(t){try{await fetch(`${this.config.analyticsHost}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),mode:"cors",keepalive:!0})}catch(e){console.error("Failed to send tracking data:",e)}}track(t,e="",n={}){if(t==="custom_event"&&(!e||typeof e!="string")){console.error("Event name is required and must be a string for custom events");return}let i=this.createBasePayload();if(!i)return;let c={...i,type:t,event_name:e,properties:t==="custom_event"||t==="outbound"?JSON.stringify(n):void 0};this.sendTrackingData(c)}trackPageview(){this.track("pageview")}trackEvent(t,e={}){this.track("custom_event",t,e)}trackOutbound(t,e="",n="_self"){this.track("outbound","",{url:t,text:e,target:n})}trackWebVitals(t){let e=this.createBasePayload();if(!e)return;let n={...e,type:"performance",event_name:"web-vitals",...t};this.sendTrackingData(n)}identify(t){if(typeof t!="string"||t.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=t.trim();try{localStorage.setItem("rybbit-user-id",this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}}clearUserId(){this.customUserId=null;try{localStorage.removeItem("rybbit-user-id")}catch{}}getUserId(){return this.customUserId}};var G=-1,p=r=>{addEventListener("pageshow",t=>{t.persisted&&(G=t.timeStamp,r(t))},!0)},d=(r,t,e,n)=>{let i,c;return o=>{t.value>=0&&(o||n)&&(c=t.value-(i??0),(c||i===void 0)&&(i=t.value,t.delta=c,t.rating=((a,s)=>a>s[1]?"poor":a>s[0]?"needs-improvement":"good")(t.value,e),r(t)))}},M=r=>{requestAnimationFrame(()=>requestAnimationFrame(()=>r()))},R=()=>{let r=performance.getEntriesByType("navigation")[0];if(r&&r.responseStart>0&&r.responseStart<performance.now())return r},m=()=>R()?.activationStart??0,u=(r,t=-1)=>{let e=R(),n="navigate";return G>=0?n="back-forward-cache":e&&(document.prerendering||m()>0?n="prerender":document.wasDiscarded?n="restore":e.type&&(n=e.type.replace(/_/g,"-"))),{name:r,value:t,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:n}},E=new WeakMap;function O(r,t){return E.get(r)||E.set(r,new t),E.get(r)}var C=class{constructor(){h(this,"t");h(this,"i",0);h(this,"o",[])}h(t){if(t.hadRecentInput)return;let e=this.o[0],n=this.o.at(-1);this.i&&e&&n&&t.startTime-n.startTime<1e3&&t.startTime-e.startTime<5e3?(this.i+=t.value,this.o.push(t)):(this.i=t.value,this.o=[t]),this.t?.(t)}},f=(r,t,e={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(r)){let n=new PerformanceObserver(i=>{Promise.resolve().then(()=>{t(i.getEntries())})});return n.observe({type:r,buffered:!0,...e}),n}}catch{}},x=r=>{let t=!1;return()=>{t||(r(),t=!0)}},g=-1,H=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,y=r=>{document.visibilityState==="hidden"&&g>-1&&(g=r.type==="visibilitychange"?r.timeStamp:0,ot())},V=()=>{addEventListener("visibilitychange",y,!0),addEventListener("prerenderingchange",y,!0)},ot=()=>{removeEventListener("visibilitychange",y,!0),removeEventListener("prerenderingchange",y,!0)},Q=()=>{if(g<0){let r=m();g=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter(e=>e.name==="hidden"&&e.startTime>r)[0]?.startTime)??H(),V(),p(()=>{setTimeout(()=>{g=H(),V()})})}return{get firstHiddenTime(){return g}}},T=r=>{document.prerendering?addEventListener("prerenderingchange",()=>r(),!0):r()},F=[1800,3e3],U=(r,t={})=>{T(()=>{let e=Q(),n,i=u("FCP"),c=f("paint",o=>{for(let a of o)a.name==="first-contentful-paint"&&(c.disconnect(),a.startTime<e.firstHiddenTime&&(i.value=Math.max(a.startTime-m(),0),i.entries.push(a),n(!0)))});c&&(n=d(r,i,F,t.reportAllChanges),p(o=>{i=u("FCP"),n=d(r,i,F,t.reportAllChanges),M(()=>{i.value=performance.now()-o.timeStamp,n(!0)})}))})},$=[.1,.25],Y=(r,t={})=>{U(x(()=>{let e,n=u("CLS",0),i=O(t,C),c=a=>{for(let s of a)i.h(s);i.i>n.value&&(n.value=i.i,n.entries=i.o,e())},o=f("layout-shift",c);o&&(e=d(r,n,$,t.reportAllChanges),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(o.takeRecords()),e(!0))}),p(()=>{i.i=0,n=u("CLS",0),e=d(r,n,$,t.reportAllChanges),M(()=>e())}),setTimeout(e))}))},X=0,I=1/0,v=0,ct=r=>{for(let t of r)t.interactionId&&(I=Math.min(I,t.interactionId),v=Math.max(v,t.interactionId),X=v?(v-I)/7+1:0)},L,J=()=>L?X:performance.interactionCount??0,lt=()=>{"interactionCount"in performance||L||(L=f("event",ct,{type:"event",buffered:!0,durationThreshold:0}))},K=0,_=class{constructor(){h(this,"u",[]);h(this,"l",new Map);h(this,"m");h(this,"v")}p(){K=J(),this.u.length=0,this.l.clear()}P(){let t=Math.min(this.u.length-1,Math.floor((J()-K)/50));return this.u[t]}h(t){if(this.m?.(t),!t.interactionId&&t.entryType!=="first-input")return;let e=this.u.at(-1),n=this.l.get(t.interactionId);if(n||this.u.length<10||t.duration>e.T){if(n?t.duration>n.T?(n.entries=[t],n.T=t.duration):t.duration===n.T&&t.startTime===n.entries[0].startTime&&n.entries.push(t):(n={id:t.interactionId,entries:[t],T:t.duration},this.l.set(n.id,n),this.u.push(n)),this.u.sort((i,c)=>c.T-i.T),this.u.length>10){let i=this.u.splice(10);for(let c of i)this.l.delete(c.id)}this.v?.(n)}}},Z=r=>{let t=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?r():(r=x(r),document.addEventListener("visibilitychange",r,{once:!0}),t(()=>{r(),document.removeEventListener("visibilitychange",r)}))},q=[200,500],tt=(r,t={})=>{globalThis.PerformanceEventTiming&&"interactionId"in PerformanceEventTiming.prototype&&T(()=>{lt();let e,n=u("INP"),i=O(t,_),c=a=>{Z(()=>{for(let l of a)i.h(l);let s=i.P();s&&s.T!==n.value&&(n.value=s.T,n.entries=s.entries,e())})},o=f("event",c,{durationThreshold:t.durationThreshold??40});e=d(r,n,q,t.reportAllChanges),o&&(o.observe({type:"first-input",buffered:!0}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(o.takeRecords()),e(!0))}),p(()=>{i.p(),n=u("INP"),e=d(r,n,q,t.reportAllChanges)}))})},A=class{constructor(){h(this,"m")}h(t){this.m?.(t)}},z=[2500,4e3],et=(r,t={})=>{T(()=>{let e=Q(),n,i=u("LCP"),c=O(t,A),o=s=>{t.reportAllChanges||(s=s.slice(-1));for(let l of s)c.h(l),l.startTime<e.firstHiddenTime&&(i.value=Math.max(l.startTime-m(),0),i.entries=[l],n())},a=f("largest-contentful-paint",o);if(a){n=d(r,i,z,t.reportAllChanges);let s=x(()=>{o(a.takeRecords()),a.disconnect(),n(!0)});for(let l of["keydown","click","visibilitychange"])addEventListener(l,()=>Z(s),{capture:!0,once:!0});p(l=>{i=u("LCP"),n=d(r,i,z,t.reportAllChanges),M(()=>{i.value=performance.now()-l.timeStamp,n(!0)})})}})},j=[800,1800],D=r=>{document.prerendering?T(()=>D(r)):document.readyState!=="complete"?addEventListener("load",()=>D(r),!0):setTimeout(r)},rt=(r,t={})=>{let e=u("TTFB"),n=d(r,e,j,t.reportAllChanges);D(()=>{let i=R();i&&(e.value=Math.max(i.responseStart-m(),0),e.entries=[i],n(!0),p(()=>{e=u("TTFB",0),n=d(r,e,j,t.reportAllChanges),n(!0)}))})};var k=class{constructor(t){this.data={lcp:null,cls:null,inp:null,fcp:null,ttfb:null};this.sent=!1;this.timeout=null;this.onReadyCallback=null;this.onReadyCallback=t}initialize(){try{et(this.collectMetric.bind(this)),Y(this.collectMetric.bind(this)),tt(this.collectMetric.bind(this)),U(this.collectMetric.bind(this)),rt(this.collectMetric.bind(this)),this.timeout=setTimeout(()=>{this.sent||this.sendData()},2e4),window.addEventListener("beforeunload",()=>{this.sent||this.sendData()})}catch(t){console.warn("Error initializing web vitals tracking:",t)}}collectMetric(t){if(this.sent)return;let e=t.name.toLowerCase();this.data[e]=t.value,Object.values(this.data).every(i=>i!==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};return}let t=B(r);if(!t)return;let e=new b(t);t.enableWebVitals&&new k(a=>{e.trackWebVitals(a)}).initialize();let n=()=>e.trackPageview(),i=t.debounceDuration>0?N(n,t.debounceDuration):n;function c(){if(document.addEventListener("click",function(o){let a=o.target;for(;a&&a!==document.documentElement;){if(a.hasAttribute("data-rybbit-event")){let s=a.getAttribute("data-rybbit-event");if(s){let l={};for(let w of a.attributes)if(w.name.startsWith("data-rybbit-prop-")){let nt=w.name.replace("data-rybbit-prop-","");l[nt]=w.value}e.trackEvent(s,l)}break}a=a.parentElement}if(t.trackOutbound){let s=o.target.closest("a");s?.href&&W(s.href)&&e.trackOutbound(s.href,s.innerText||s.textContent||"",s.target||"_self")}}),t.autoTrackSpa){let o=history.pushState,a=history.replaceState;history.pushState=function(...s){o.apply(this,s),i()},history.replaceState=function(...s){a.apply(this,s),i()},window.addEventListener("popstate",i),window.addEventListener("hashchange",i)}}window.rybbit={pageview:()=>e.trackPageview(),event:(o,a={})=>e.trackEvent(o,a),trackOutbound:(o,a="",s="_self")=>e.trackOutbound(o,a,s),identify:o=>e.identify(o),clearUserId:()=>e.clearUserId(),getUserId:()=>e.getUserId()},c(),t.autoTrackPageview&&e.trackPageview()})();})();+"use strict";(()=>{var nt=Object.defineProperty;var at=(r,t,e)=>t in r?nt(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var h=(r,t,e)=>at(r,typeof t!="symbol"?t+"":t,e);function st(r){let t="__DOUBLE_ASTERISK_TOKEN__",e="__SINGLE_ASTERISK_TOKEN__",n=r.replace(/\*\*/g,t).replace(/\*/g,e).replace(/[.+?^${}()|[\]\\]/g,"\\$&");n=n.replace(new RegExp(`/${t}/`,"g"),"/(?:.+/)?"),n=n.replace(new RegExp(t,"g"),".*"),n=n.replace(/\//g,"\\/");let c=n.replace(new RegExp(e,"g"),"[^/]+");return new RegExp("^"+c+"$")}function P(r,t){for(let e of t)try{if(st(e).test(r))return e}catch(i){console.error(`Invalid pattern: ${e}`,i)}return null}function N(r,t){let e=null;return(...i)=>{e&&clearTimeout(e),e=setTimeout(()=>r(...i),t)}}function W(r){try{let t=window.location.hostname,e=new URL(r).hostname;return e!==t&&e!==""}catch{return!1}}function S(r,t){if(!r)return t;try{let e=JSON.parse(r);return Array.isArray(t)&&!Array.isArray(e)?t:e}catch(e){return console.error("Error parsing JSON:",e),t}}function B(r){let t=r.getAttribute("src");if(!t)return console.error("Script src attribute is missing"),null;let e=t.split("/script.js")[0];if(!e)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,c=S(r.getAttribute("data-skip-patterns"),[]),o=S(r.getAttribute("data-mask-patterns"),[]),a=r.getAttribute("data-api-key")||void 0;return{analyticsHost:e,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",skipPatterns:c,maskPatterns:o,apiKey:a}}var b=class{constructor(t){this.customUserId=null;this.config=t,this.loadUserId()}loadUserId(){try{let t=localStorage.getItem("rybbit-user-id");t&&(this.customUserId=t)}catch{}}createBasePayload(){let t=new URL(window.location.href),e=t.pathname;if(t.hash&&t.hash.startsWith("#/")&&(e=t.hash.substring(1)),P(e,this.config.skipPatterns))return null;let i=P(e,this.config.maskPatterns);i&&(e=i);let n={site_id:this.config.siteId,hostname:t.hostname,pathname:e,querystring:this.config.trackQuerystring?t.search:"",screenWidth:window.innerWidth,screenHeight:window.innerHeight,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(t){try{await fetch(`${this.config.analyticsHost}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),mode:"cors",keepalive:!0})}catch(e){console.error("Failed to send tracking data:",e)}}track(t,e="",i={}){if(t==="custom_event"&&(!e||typeof e!="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:t,event_name:e,properties:t==="custom_event"||t==="outbound"?JSON.stringify(i):void 0};this.sendTrackingData(c)}trackPageview(){this.track("pageview")}trackEvent(t,e={}){this.track("custom_event",t,e)}trackOutbound(t,e="",i="_self"){this.track("outbound","",{url:t,text:e,target:i})}trackWebVitals(t){let e=this.createBasePayload();if(!e)return;let i={...e,type:"performance",event_name:"web-vitals",...t};this.sendTrackingData(i)}identify(t){if(typeof t!="string"||t.trim()===""){console.error("User ID must be a non-empty string");return}this.customUserId=t.trim();try{localStorage.setItem("rybbit-user-id",this.customUserId)}catch{console.warn("Could not persist user ID to localStorage")}}clearUserId(){this.customUserId=null;try{localStorage.removeItem("rybbit-user-id")}catch{}}getUserId(){return this.customUserId}};var G=-1,g=r=>{addEventListener("pageshow",t=>{t.persisted&&(G=t.timeStamp,r(t))},!0)},d=(r,t,e,i)=>{let n,c;return o=>{t.value>=0&&(o||i)&&(c=t.value-(n??0),(c||n===void 0)&&(n=t.value,t.delta=c,t.rating=((a,s)=>a>s[1]?"poor":a>s[0]?"needs-improvement":"good")(t.value,e),r(t)))}},M=r=>{requestAnimationFrame(()=>requestAnimationFrame(()=>r()))},R=()=>{let r=performance.getEntriesByType("navigation")[0];if(r&&r.responseStart>0&&r.responseStart<performance.now())return r},m=()=>R()?.activationStart??0,u=(r,t=-1)=>{let e=R(),i="navigate";return G>=0?i="back-forward-cache":e&&(document.prerendering||m()>0?i="prerender":document.wasDiscarded?i="restore":e.type&&(i=e.type.replace(/_/g,"-"))),{name:r,value:t,rating:"good",delta:0,entries:[],id:`v5-${Date.now()}-${Math.floor(8999999999999*Math.random())+1e12}`,navigationType:i}},E=new WeakMap;function O(r,t){return E.get(r)||E.set(r,new t),E.get(r)}var C=class{constructor(){h(this,"t");h(this,"i",0);h(this,"o",[])}h(t){if(t.hadRecentInput)return;let e=this.o[0],i=this.o.at(-1);this.i&&e&&i&&t.startTime-i.startTime<1e3&&t.startTime-e.startTime<5e3?(this.i+=t.value,this.o.push(t)):(this.i=t.value,this.o=[t]),this.t?.(t)}},f=(r,t,e={})=>{try{if(PerformanceObserver.supportedEntryTypes.includes(r)){let i=new PerformanceObserver(n=>{Promise.resolve().then(()=>{t(n.getEntries())})});return i.observe({type:r,buffered:!0,...e}),i}}catch{}},x=r=>{let t=!1;return()=>{t||(r(),t=!0)}},p=-1,H=()=>document.visibilityState!=="hidden"||document.prerendering?1/0:0,y=r=>{document.visibilityState==="hidden"&&p>-1&&(p=r.type==="visibilitychange"?r.timeStamp:0,ot())},V=()=>{addEventListener("visibilitychange",y,!0),addEventListener("prerenderingchange",y,!0)},ot=()=>{removeEventListener("visibilitychange",y,!0),removeEventListener("prerenderingchange",y,!0)},Q=()=>{if(p<0){let r=m();p=(document.prerendering?void 0:globalThis.performance.getEntriesByType("visibility-state").filter(e=>e.name==="hidden"&&e.startTime>r)[0]?.startTime)??H(),V(),g(()=>{setTimeout(()=>{p=H(),V()})})}return{get firstHiddenTime(){return p}}},T=r=>{document.prerendering?addEventListener("prerenderingchange",()=>r(),!0):r()},F=[1800,3e3],U=(r,t={})=>{T(()=>{let e=Q(),i,n=u("FCP"),c=f("paint",o=>{for(let a of o)a.name==="first-contentful-paint"&&(c.disconnect(),a.startTime<e.firstHiddenTime&&(n.value=Math.max(a.startTime-m(),0),n.entries.push(a),i(!0)))});c&&(i=d(r,n,F,t.reportAllChanges),g(o=>{n=u("FCP"),i=d(r,n,F,t.reportAllChanges),M(()=>{n.value=performance.now()-o.timeStamp,i(!0)})}))})},K=[.1,.25],Y=(r,t={})=>{U(x(()=>{let e,i=u("CLS",0),n=O(t,C),c=a=>{for(let s of a)n.h(s);n.i>i.value&&(i.value=n.i,i.entries=n.o,e())},o=f("layout-shift",c);o&&(e=d(r,i,K,t.reportAllChanges),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(o.takeRecords()),e(!0))}),g(()=>{n.i=0,i=u("CLS",0),e=d(r,i,K,t.reportAllChanges),M(()=>e())}),setTimeout(e))}))},X=0,I=1/0,v=0,ct=r=>{for(let t of r)t.interactionId&&(I=Math.min(I,t.interactionId),v=Math.max(v,t.interactionId),X=v?(v-I)/7+1:0)},L,$=()=>L?X:performance.interactionCount??0,lt=()=>{"interactionCount"in performance||L||(L=f("event",ct,{type:"event",buffered:!0,durationThreshold:0}))},J=0,_=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 t=Math.min(this.u.length-1,Math.floor(($()-J)/50));return this.u[t]}h(t){if(this.m?.(t),!t.interactionId&&t.entryType!=="first-input")return;let e=this.u.at(-1),i=this.l.get(t.interactionId);if(i||this.u.length<10||t.duration>e.T){if(i?t.duration>i.T?(i.entries=[t],i.T=t.duration):t.duration===i.T&&t.startTime===i.entries[0].startTime&&i.entries.push(t):(i={id:t.interactionId,entries:[t],T:t.duration},this.l.set(i.id,i),this.u.push(i)),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?.(i)}}},Z=r=>{let t=globalThis.requestIdleCallback||setTimeout;document.visibilityState==="hidden"?r():(r=x(r),document.addEventListener("visibilitychange",r,{once:!0}),t(()=>{r(),document.removeEventListener("visibilitychange",r)}))},q=[200,500],tt=(r,t={})=>{globalThis.PerformanceEventTiming&&"interactionId"in PerformanceEventTiming.prototype&&T(()=>{lt();let e,i=u("INP"),n=O(t,_),c=a=>{Z(()=>{for(let l of a)n.h(l);let s=n.P();s&&s.T!==i.value&&(i.value=s.T,i.entries=s.entries,e())})},o=f("event",c,{durationThreshold:t.durationThreshold??40});e=d(r,i,q,t.reportAllChanges),o&&(o.observe({type:"first-input",buffered:!0}),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&(c(o.takeRecords()),e(!0))}),g(()=>{n.p(),i=u("INP"),e=d(r,i,q,t.reportAllChanges)}))})},A=class{constructor(){h(this,"m")}h(t){this.m?.(t)}},z=[2500,4e3],et=(r,t={})=>{T(()=>{let e=Q(),i,n=u("LCP"),c=O(t,A),o=s=>{t.reportAllChanges||(s=s.slice(-1));for(let l of s)c.h(l),l.startTime<e.firstHiddenTime&&(n.value=Math.max(l.startTime-m(),0),n.entries=[l],i())},a=f("largest-contentful-paint",o);if(a){i=d(r,n,z,t.reportAllChanges);let s=x(()=>{o(a.takeRecords()),a.disconnect(),i(!0)});for(let l of["keydown","click","visibilitychange"])addEventListener(l,()=>Z(s),{capture:!0,once:!0});g(l=>{n=u("LCP"),i=d(r,n,z,t.reportAllChanges),M(()=>{n.value=performance.now()-l.timeStamp,i(!0)})})}})},j=[800,1800],D=r=>{document.prerendering?T(()=>D(r)):document.readyState!=="complete"?addEventListener("load",()=>D(r),!0):setTimeout(r)},rt=(r,t={})=>{let e=u("TTFB"),i=d(r,e,j,t.reportAllChanges);D(()=>{let n=R();n&&(e.value=Math.max(n.responseStart-m(),0),e.entries=[n],i(!0),g(()=>{e=u("TTFB",0),i=d(r,e,j,t.reportAllChanges),i(!0)}))})};var k=class{constructor(t){this.data={lcp:null,cls:null,inp:null,fcp:null,ttfb:null};this.sent=!1;this.timeout=null;this.onReadyCallback=null;this.onReadyCallback=t}initialize(){try{et(this.collectMetric.bind(this)),Y(this.collectMetric.bind(this)),tt(this.collectMetric.bind(this)),U(this.collectMetric.bind(this)),rt(this.collectMetric.bind(this)),this.timeout=setTimeout(()=>{this.sent||this.sendData()},2e4),window.addEventListener("beforeunload",()=>{this.sent||this.sendData()})}catch(t){console.warn("Error initializing web vitals tracking:",t)}}collectMetric(t){if(this.sent)return;let e=t.name.toLowerCase();this.data[e]=t.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};return}let t=B(r);if(!t)return;let e=new b(t);t.enableWebVitals&&new k(a=>{e.trackWebVitals(a)}).initialize();let i=()=>e.trackPageview(),n=t.debounceDuration>0?N(i,t.debounceDuration):i;function c(){if(document.addEventListener("click",function(o){let a=o.target;for(;a&&a!==document.documentElement;){if(a.hasAttribute("data-rybbit-event")){let s=a.getAttribute("data-rybbit-event");if(s){let l={};for(let w of a.attributes)if(w.name.startsWith("data-rybbit-prop-")){let it=w.name.replace("data-rybbit-prop-","");l[it]=w.value}e.trackEvent(s,l)}break}a=a.parentElement}if(t.trackOutbound){let s=o.target.closest("a");s?.href&&W(s.href)&&e.trackOutbound(s.href,s.innerText||s.textContent||"",s.target||"_self")}}),t.autoTrackSpa){let o=history.pushState,a=history.replaceState;history.pushState=function(...s){o.apply(this,s),n()},history.replaceState=function(...s){a.apply(this,s),n()},window.addEventListener("popstate",n),window.addEventListener("hashchange",n)}}window.rybbit={pageview:()=>e.trackPageview(),event:(o,a={})=>e.trackEvent(o,a),trackOutbound:(o,a="",s="_self")=>e.trackOutbound(o,a,s),identify:o=>e.identify(o),clearUserId:()=>e.clearUserId(),getUserId:()=>e.getUserId()},c(),t.autoTrackPageview&&e.trackPageview()})();})();diff --git a/server/src/analytics-script/config.ts b/server/src/analytics-script/config.tsindex 03404f18e..b90c75df5 100644--- a/server/src/analytics-script/config.ts+++ b/server/src/analytics-script/config.ts@@ -37,6 +37,8 @@ export function parseScriptConfig(scriptTag: HTMLScriptElement): ScriptConfig |[]);+ const apiKey = scriptTag.getAttribute('data-api-key') || undefined;+return {analyticsHost,siteId,@@ -48,5 +50,6 @@ export function parseScriptConfig(scriptTag: HTMLScriptElement): ScriptConfig |enableWebVitals: scriptTag.getAttribute('data-web-vitals') === 'true',skipPatterns,maskPatterns,+ apiKey,};}\ No newline at end of filediff --git a/server/src/analytics-script/tracking.ts b/server/src/analytics-script/tracking.tsindex 820e080c3..f41837d6d 100644--- a/server/src/analytics-script/tracking.ts+++ b/server/src/analytics-script/tracking.ts@@ -57,6 +57,11 @@ export class Tracker {payload.user_id = this.customUserId;}+ // Include API key if configured+ if (this.config.apiKey) {+ payload.api_key = this.config.apiKey;+ }+return payload;}diff --git a/server/src/analytics-script/types.ts b/server/src/analytics-script/types.tsindex f0778818d..136d219ff 100644--- a/server/src/analytics-script/types.ts+++ b/server/src/analytics-script/types.ts@@ -9,6 +9,7 @@ export interface ScriptConfig {enableWebVitals: boolean;skipPatterns: string[];maskPatterns: string[];+ apiKey?: string;}export interface BasePayload {@@ -22,6 +23,7 @@ export interface BasePayload {page_title: string;referrer: string;user_id?: string;+ api_key?: string;}export interface TrackingPayload extends BasePayload {diff --git a/server/src/api/sites/getSiteApiConfig.ts b/server/src/api/sites/getSiteApiConfig.tsnew file mode 100644index 000000000..b33f3cab0--- /dev/null+++ b/server/src/api/sites/getSiteApiConfig.ts@@ -0,0 +1,57 @@+import { FastifyRequest, FastifyReply } from "fastify";+import { db } from "../../db/postgres/postgres.js";+import { sites } from "../../db/postgres/schema.js";+import { eq, and } from "drizzle-orm";+import { getUserHasAdminAccessToSite } from "../../lib/auth-utils.js";++export async function getSiteApiConfig(+ request: FastifyRequest,+ reply: FastifyReply+) {+ try {+ if (!request.user) {+ return reply.status(401).send({ success: false, error: "Unauthorized" });+ }++ const { siteId } = request.params as { siteId: string };+ const parsedSiteId = parseInt(siteId, 10);++ if (isNaN(parsedSiteId)) {+ return reply.status(400).send({ success: false, error: "Invalid site ID" });+ }++ const userHasAdminAccessToSite = await getUserHasAdminAccessToSite(+ request,+ String(parsedSiteId)+ );+ if (!userHasAdminAccessToSite) {+ return reply.status(403).send({ error: "Forbidden" });+ }++ // Get site data+ const site = await db+ .select({+ apiKey: sites.apiKey,+ })+ .from(sites)+ .where(eq(sites.siteId, parsedSiteId))+ .limit(1);++ if (site.length === 0) {+ return reply.status(404).send({ success: false, error: "Site not found" });+ }++ return reply.send({+ success: true,+ data: {+ apiKey: site[0].apiKey,+ },+ });+ } catch (error) {+ console.error("Error getting site dev config:", error);+ return reply.status(500).send({+ success: false,+ error: "Failed to get site API configuration",+ });+ }+}\ No newline at end of filediff --git a/server/src/api/sites/updateSiteApiConfig.ts b/server/src/api/sites/updateSiteApiConfig.tsnew file mode 100644index 000000000..e175b902c--- /dev/null+++ b/server/src/api/sites/updateSiteApiConfig.ts@@ -0,0 +1,91 @@+import { FastifyRequest, FastifyReply } from "fastify";+import { db } from "../../db/postgres/postgres.js";+import { sites } from "../../db/postgres/schema.js";+import { eq, and } from "drizzle-orm";+import { z } from "zod";+import { siteConfig } from "../../lib/siteConfig.js";+import { getUserHasAdminAccessToSite } from "../../lib/auth-utils.js";+import crypto from "crypto";++// Schema for updating API configuration+const updateApiConfigSchema = z.object({+ action: z.enum(["generate_api_key", "revoke_api_key"]),+});++export async function updateSiteApiConfig(+ request: FastifyRequest,+ reply: FastifyReply+) {+ try {+ if (!request.user) {+ return reply.status(401).send({ success: false, error: "Unauthorized" });+ }++ const { siteId } = request.params as { siteId: string };+ const parsedSiteId = parseInt(siteId, 10);++ if (isNaN(parsedSiteId)) {+ return reply.status(400).send({ success: false, error: "Invalid site ID" });+ }++ const userHasAdminAccessToSite = await getUserHasAdminAccessToSite(+ request,+ String(parsedSiteId)+ );+ if (!userHasAdminAccessToSite) {+ return reply.status(403).send({ error: "Forbidden" });+ }++ // Validate request body+ const validationResult = updateApiConfigSchema.safeParse(request.body);+ if (!validationResult.success) {+ return reply.status(400).send({+ success: false,+ error: "Invalid request body",+ details: validationResult.error.flatten(),+ });+ }++ const { action } = validationResult.data;++ let updateData: any = {};++ switch (action) {+ case "generate_api_key":+ // Generate a secure random API key with rb_ prefix+ const apiKey = `rb_${crypto.randomBytes(16).toString('hex')}`;+ updateData.apiKey = apiKey;+ break;++ case "revoke_api_key":+ updateData.apiKey = null;+ break;++ }++ // Update the site+ const updatedSite = await db+ .update(sites)+ .set(updateData)+ .where(eq(sites.siteId, parsedSiteId))+ .returning({+ apiKey: sites.apiKey,+ });++ // Update the site config cache+ if (action === "generate_api_key" || action === "revoke_api_key") {+ siteConfig.updateSiteApiKey(parsedSiteId, updateData.apiKey);+ }++ return reply.send({+ success: true,+ data: updatedSite[0],+ });+ } catch (error) {+ console.error("Error updating site dev config:", error);+ return reply.status(500).send({+ success: false,+ error: "Failed to update site API configuration",+ });+ }+}\ No newline at end of filediff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.tsindex f590bcdf7..dbf8bf017 100644--- a/server/src/db/postgres/schema.ts+++ b/server/src/db/postgres/schema.ts@@ -62,6 +62,7 @@ export const sites = pgTable(public: boolean().default(false),saltUserIds: boolean().default(false),blockBots: boolean().default(true).notNull(),+ apiKey: text("api_key"), // Format: rb_{32_hex_chars} = 35 chars total},(table) => [foreignKey({diff --git a/server/src/index.ts b/server/src/index.tsindex a35c889a4..37c228c7b 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -46,6 +46,8 @@ import { getSite } from "./api/sites/getSite.js";import { getSiteHasData } from "./api/sites/getSiteHasData.js";import { getSiteIsPublic } from "./api/sites/getSiteIsPublic.js";import { getSitesFromOrg } from "./api/sites/getSitesFromOrg.js";+import { getSiteApiConfig } from "./api/sites/getSiteApiConfig.js";+import { updateSiteApiConfig } from "./api/sites/updateSiteApiConfig.js";import { createCheckoutSession } from "./api/stripe/createCheckoutSession.js";import { createPortalSession } from "./api/stripe/createPortalSession.js";import { getSubscription } from "./api/stripe/getSubscription.js";@@ -257,6 +259,8 @@ server.post("/api/change-site-block-bots", changeSiteBlockBots);server.post("/api/delete-site/:id", deleteSite);server.get("/api/get-sites-from-org/:organizationId", getSitesFromOrg);server.get("/api/get-site/:id", getSite);+server.get("/api/site/:siteId/api-config", getSiteApiConfig);+server.post("/api/site/:siteId/api-config", updateSiteApiConfig);server.get("/api/list-organization-members/:organizationId",listOrganizationMembersdiff --git a/server/src/lib/siteConfig.ts b/server/src/lib/siteConfig.tsindex 732f6890e..abfd59d5a 100644--- a/server/src/lib/siteConfig.ts+++ b/server/src/lib/siteConfig.ts@@ -7,6 +7,7 @@ interface SiteConfigData {saltUserIds: boolean;domain: string;blockBots: boolean;+ apiKey?: string | null;}class SiteConfig {@@ -22,6 +23,7 @@ class SiteConfig {saltUserIds: sites.saltUserIds,domain: sites.domain,blockBots: sites.blockBots,+ apiKey: sites.apiKey,}).from(sites);@@ -35,6 +37,7 @@ class SiteConfig {saltUserIds: site.saltUserIds || false,domain: site.domain || "",blockBots: site.blockBots === undefined ? true : site.blockBots,+ apiKey: site.apiKey,});}@@ -82,16 +85,22 @@ class SiteConfig {return config?.domain || "";}+ /**+ * Get the full site configuration+ */+ getSiteConfig(siteId: string | number): SiteConfigData | undefined {+ const numericSiteId = Number(siteId);+ return this.siteConfigMap.get(numericSiteId);+ }+/*** Update the public status of a site in the cache*/updateSitePublicStatus(siteId: number, isPublic: boolean): void {- const config = this.siteConfigMap.get(siteId) || {- public: false,- saltUserIds: false,- domain: "",- blockBots: true,- };+ const config = this.siteConfigMap.get(siteId);+ if (!config) {+ return;+ }config.public = isPublic;this.siteConfigMap.set(siteId, config);}@@ -100,12 +109,10 @@ class SiteConfig {* Update the salt user IDs setting of a site in the cache*/updateSiteSaltSetting(siteId: number, saltUserIds: boolean): void {- const config = this.siteConfigMap.get(siteId) || {- public: false,- saltUserIds: false,- domain: "",- blockBots: true,- };+ const config = this.siteConfigMap.get(siteId);+ if (!config) {+ return;+ }config.saltUserIds = saltUserIds;this.siteConfigMap.set(siteId, config);}@@ -114,12 +121,10 @@ class SiteConfig {* Update the bot blocking setting of a site in the cache*/updateSiteBlockBotsSetting(siteId: number, blockBots: boolean): void {- const config = this.siteConfigMap.get(siteId) || {- public: false,- saltUserIds: false,- domain: "",- blockBots: true,- };+ const config = this.siteConfigMap.get(siteId);+ if (!config) {+ return;+ }config.blockBots = blockBots;this.siteConfigMap.set(siteId, config);}@@ -128,16 +133,25 @@ class SiteConfig {* 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: "",- blockBots: true,- };+ const config = this.siteConfigMap.get(siteId);+ if (!config) {+ return;+ }config.domain = domain;this.siteConfigMap.set(siteId, config);}+ /**+ * Update the API key of a site in the cache+ */+ updateSiteApiKey(siteId: number, apiKey: string | null): void {+ const config = this.siteConfigMap.get(siteId);+ if (config) {+ config.apiKey = apiKey;+ this.siteConfigMap.set(siteId, config);+ }+ }+/*** Add a new site to the cache*/diff --git a/server/src/tracker/trackEvent.ts b/server/src/tracker/trackEvent.tsindex b0f51eba4..d36b6e567 100644--- a/server/src/tracker/trackEvent.ts+++ b/server/src/tracker/trackEvent.ts@@ -32,6 +32,7 @@ export const trackingPayloadSchema = z.discriminatedUnion("type", [event_name: z.string().max(256).optional(),properties: z.string().max(2048).optional(),user_id: z.string().max(255).optional(),+ api_key: z.string().max(35).optional(), // rb_ prefix + 32 hex chars}),z.object({type: z.literal("custom_event"),@@ -61,6 +62,7 @@ export const trackingPayloadSchema = z.discriminatedUnion("type", [).optional(), // Optional but must be valid JSON if presentuser_id: z.string().max(255).optional(),+ api_key: z.string().max(35).optional(), // rb_ prefix + 32 hex chars}),z.object({type: z.literal("performance"),@@ -76,6 +78,7 @@ export const trackingPayloadSchema = z.discriminatedUnion("type", [event_name: z.string().max(256).optional(),properties: z.string().max(2048).optional(),user_id: z.string().max(255).optional(),+ api_key: z.string().max(35).optional(), // rb_ prefix + 32 hex chars// Performance metrics (can be null if not collected)lcp: z.number().positive().nullable().optional(),cls: z.number().min(0).nullable().optional(),@@ -164,7 +167,7 @@ async function processTrackingEvent(* @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) {+async function validateOrigin(siteId: string, requestOrigin?: string, apiKey?: string) {try {// If origin checking is disabled, return successif (DISABLE_ORIGIN_CHECK) {@@ -183,13 +186,13 @@ async function validateOrigin(siteId: string, requestOrigin?: string) {const numericSiteId =typeof siteId === "string" ? parseInt(siteId, 10) : siteId;- // Get the domain associated with this site- const siteDomain = siteConfig.getSiteDomain(numericSiteId);-- if (!siteDomain) {+ // Get the site configuration+ const site = await siteConfig.getSiteConfig(numericSiteId);++ if (!site) {return {success: false,- error: "Site not found or has no registered domain",+ error: "Site not found",};}@@ -205,6 +208,17 @@ async function validateOrigin(siteId: string, requestOrigin?: string) {// Parse the origin into URL componentsconst originUrl = new URL(requestOrigin);+ // Check if this is a request with valid API key+ if (apiKey && site.apiKey && apiKey === site.apiKey) {+ console.info(+ `[Tracking] Allowing API key authenticated request for site ${siteId} from origin: ${requestOrigin}`+ );+ return { success: true };+ }++ // Get the domain associated with this site+ const siteDomain = site.domain;+// Normalize domains by removing all subdomain prefixesconst normalizedOriginHost = normalizeOrigin(requestOrigin);const normalizedSiteDomain = normalizeOrigin(`https://${siteDomain}`);@@ -253,7 +267,8 @@ export async function trackEvent(request: FastifyRequest, reply: FastifyReply) {// Validate that the request is coming from the expected originconst originValidation = await validateOrigin(validatedPayload.site_id,- request.headers.origin as string+ request.headers.origin as string,+ validatedPayload.api_key);if (!originValidation.success) {