Skip to content

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

feat: domain-first onboarding (try a site before signing up) (#1183)

Goldflag3d3666d34d4b
diff --git a/client/messages/en.json b/client/messages/en.json
index 9111f7ecd..fcbe6df6a 100644
--- a/client/messages/en.json
+++ b/client/messages/en.json
@@ -1864,5 +1864,22 @@
"QOaR8l": "Submitted form to \"{action}\"",
"IQ5tZg": "Submitted form",
"+B+qvw": "Changed {type}input \"{name}\"",
- "vDpLV2": "Changed {type}input"
+ "vDpLV2": "Changed {type}input",
+ "MiQ4id": "Setting up your dashboard for {domain}…",
+ "4QHutO": "See who's on your site",
+ "kL9vD5": "Enter your domain to open a live dashboard. No account needed until you want to keep it.",
+ "wjMsGC": "See my dashboard",
+ "OxNUFK": "Your dashboard stays open for 24 hours. Claim it with a free 7-day trial to keep it.",
+ "G6KGGR": "{domain} has expired and will be deleted shortly.",
+ "Vk8VDq": "{domain} isn't claimed. It will be deleted in {remaining} unless you claim it.",
+ "+r0Iwt": "Claim this site",
+ "+Sy0Cl": "Could not find a matching plan. Please try a different selection.",
+ "0o6QyV": "Failed to create checkout session",
+ "PmX9kv": "Keep {domain}",
+ "cUXDNU": "The site moves into this organization.",
+ "PktqJk": "We'll create an organization named {domain} and move the site into it.",
+ "osCh7/": "Claim site",
+ "bH/RfA": "Claim {domain} to keep its dashboard and everything it has collected.",
+ "GcLrWX": "Your dashboard stays open for 24 hours. Create an account to keep it.",
+ "9RoSN0": "Signup is disabled"
}
diff --git a/client/src/api/admin/endpoints/index.ts b/client/src/api/admin/endpoints/index.ts
index fab3d5ed8..d51fbd4a2 100644
--- a/client/src/api/admin/endpoints/index.ts
+++ b/client/src/api/admin/endpoints/index.ts
@@ -1,6 +1,8 @@
// Sites endpoints
export {
addSite,
+ claimSite,
+ createUnclaimedSite,
deleteSite,
moveSite,
updateSiteConfig,
@@ -10,7 +12,7 @@ export {
fetchSiteIsPublic,
fetchSiteUsage,
} from "./sites";
-export type { SiteResponse, GetSitesFromOrgResponse, SiteUsageResponse } from "./sites";
+export type { SiteResponse, GetSitesFromOrgResponse, SiteUsageResponse, UnclaimedSiteResponse } from "./sites";
// Organizations endpoints
export {
diff --git a/client/src/api/admin/endpoints/sites.ts b/client/src/api/admin/endpoints/sites.ts
index 5b31d7b0d..0b6cb9f42 100644
--- a/client/src/api/admin/endpoints/sites.ts
+++ b/client/src/api/admin/endpoints/sites.ts
@@ -8,8 +8,11 @@ export type SiteResponse = {
domain: string;
createdAt: string;
updatedAt: string;
- createdBy: string;
+ createdBy: string | null;
organizationId: string | null;
+ // Set while the site has no organization (created from the landing-page
+ // domain input). Cleared on claim.
+ claimExpiresAt?: string | null;
public: boolean;
embedEnabled?: boolean;
saltUserIds: boolean;
@@ -206,3 +209,31 @@ export function fetchSiteHasData(siteId: string) {
export function fetchSiteIsPublic(siteId: string | number) {
return authedFetch<{ isPublic: boolean }>(`/sites/${siteId}/is-public`);
}
+
+export type UnclaimedSiteResponse = {
+ id: string | null;
+ siteId: number;
+ domain: string;
+ privateLinkKey: string;
+ claimExpiresAt: string;
+};
+
+/** Creates an owner-less site for a domain. No session required. */
+export function createUnclaimedSite(domain: string) {
+ return authedFetch<UnclaimedSiteResponse>("/sites/unclaimed", undefined, {
+ method: "POST",
+ data: { domain },
+ });
+}
+
+/** Moves an unclaimed site into the caller's organization. Requires a session. */
+export function claimSite(siteId: number | string, privateLinkKey: string, organizationId: string) {
+ return authedFetch<{ id: string | null; siteId: number; domain: string; organizationId: string }>(
+ `/sites/${siteId}/claim`,
+ undefined,
+ {
+ method: "POST",
+ data: { privateLinkKey, organizationId },
+ }
+ );
+}
diff --git a/client/src/api/admin/hooks/useOrganizations.ts b/client/src/api/admin/hooks/useOrganizations.ts
index c61d85acb..1931b756c 100644
--- a/client/src/api/admin/hooks/useOrganizations.ts
+++ b/client/src/api/admin/hooks/useOrganizations.ts
@@ -12,10 +12,11 @@ import {
export { USER_ORGANIZATIONS_QUERY_KEY } from "../endpoints";
-export function useUserOrganizations() {
+export function useUserOrganizations(options?: { enabled?: boolean }) {
return useQuery({
queryKey: [USER_ORGANIZATIONS_QUERY_KEY],
queryFn: getUserOrganizations,
+ enabled: options?.enabled,
});
}
diff --git a/client/src/app/[site]/components/Header/ClaimSiteBanner.test.tsx b/client/src/app/[site]/components/Header/ClaimSiteBanner.test.tsx
new file mode 100644
index 000000000..447b57c42
--- /dev/null
+++ b/client/src/app/[site]/components/Header/ClaimSiteBanner.test.tsx
@@ -0,0 +1,208 @@
+import React from "react";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider, useQuery } from "@tanstack/react-query";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const state = vi.hoisted(() => ({
+ cloud: true,
+ user: { id: "u1" } as { id: string } | null,
+ site: {} as any,
+ path: "/7/aaaaaaaaaaaa/main",
+ params: new URLSearchParams(),
+ organizations: [] as any[],
+ pending: false,
+ disableSignup: false,
+ replace: vi.fn(),
+ claim: vi.fn(),
+ createOrg: vi.fn(),
+ setActive: vi.fn(),
+ signup: vi.fn(),
+}));
+vi.mock("next-intl", () => ({ useExtracted: () => (message: string) => message }));
+vi.mock("next/navigation", () => ({
+ usePathname: () => state.path,
+ useSearchParams: () => state.params,
+ useRouter: () => ({ replace: state.replace }),
+}));
+vi.mock("@/lib/const", () => ({
+ get IS_CLOUD() {
+ return state.cloud;
+ },
+ BACKEND_URL: "/api",
+}));
+vi.mock("@/lib/configs", () => ({
+ useConfigs: () => ({ configs: { disableSignup: state.disableSignup }, isLoading: false }),
+}));
+vi.mock("@/lib/userStore", () => ({
+ userStore: Object.assign(() => ({ user: state.user }), {
+ setState: (next: any) => {
+ state.user = next.user;
+ },
+ }),
+}));
+vi.mock("@/lib/store", () => ({
+ useStore: () => ({ site: "7", privateKey: state.path.includes("aaaaaaaaaaaa") ? "aaaaaaaaaaaa" : null }),
+}));
+vi.mock("@/api/admin/hooks/useSites", () => ({
+ useGetSite: (siteId: string) => useQuery({ queryKey: ["get-site", siteId], queryFn: async () => state.site }),
+}));
+vi.mock("@/api/admin/hooks/useOrganizations", () => ({
+ USER_ORGANIZATIONS_QUERY_KEY: "organizations",
+ useUserOrganizations: () => ({ data: state.organizations, isPending: state.pending }),
+}));
+vi.mock("@/api/admin/endpoints", () => ({ claimSite: state.claim }));
+vi.mock("@/lib/auth", () => ({
+ authClient: {
+ organization: { create: state.createOrg, setActive: state.setActive },
+ signUp: { email: state.signup },
+ },
+}));
+vi.mock("@/lib/trackAdEvent", () => ({ trackAdEvent: vi.fn() }));
+vi.mock("@/app/signup/components/PlanStep", () => ({
+ PlanStep: ({ onSubscribe }: any) => <button onClick={onSubscribe}>Start free trial</button>,
+}));
+vi.mock("@/app/signup/components/AccountStep", () => ({
+ AccountStep: ({ socialCallbackURL, loginHref, onSubmit }: any) => (
+ <div>
+ <a href={socialCallbackURL}>OAuth</a>
+ <a href={loginHref}>Log in</a>
+ <button onClick={onSubmit}>Create account</button>
+ </div>
+ ),
+}));
+vi.mock("@/app/subscribe/components/utils", () => ({
+ EVENT_TIERS: [100_000],
+ findPriceForTier: () => ({ priceId: "price_test", name: "Pro" }),
+}));
+vi.mock("@/components/subscription/components/CheckoutModal", () => ({
+ CheckoutModal: ({ open, clientSecret }: any) => (open ? <div>Checkout {clientSecret}</div> : null),
+}));
+vi.mock("./NoData", () => ({ NoData: () => null }));
+vi.mock("./AffiliateBanner", () => ({ AffiliateBanner: () => null }));
+vi.mock("./DemoSignupBanner", () => ({ DemoSignupBanner: () => null }));
+vi.mock("./UsageBanners", () => ({ UsageBanners: () => null }));
+vi.mock("@/components/FreePlanBanner", () => ({ FreePlanBanner: () => null }));
+import { Header } from "./Header";
+
+let client: QueryClient;
+beforeEach(() => {
+ vi.clearAllMocks();
+ state.cloud = true;
+ state.disableSignup = false;
+ state.user = { id: "u1" };
+ state.path = "/7/aaaaaaaaaaaa/main";
+ state.params = new URLSearchParams();
+ state.organizations = [];
+ state.pending = false;
+ state.site = {
+ siteId: 7,
+ domain: "acme.dev",
+ organizationId: null,
+ claimExpiresAt: new Date(Date.now() + 60_000).toISOString(),
+ };
+ state.createOrg.mockResolvedValue({ data: { id: "org_1" } });
+ state.setActive.mockResolvedValue({ data: {} });
+ state.signup.mockResolvedValue({ data: { user: { id: "u1" } } });
+ state.replace.mockImplementation((path: string) => {
+ state.path = path.split("?")[0];
+ state.params = new URLSearchParams(path.split("?")[1]);
+ });
+ state.claim.mockImplementation(async () => {
+ state.site = { ...state.site, organizationId: "org_1", claimExpiresAt: null, isOwner: true };
+ return state.site;
+ });
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(async () => ({ ok: true, json: async () => ({ clientSecret: "secret_test" }) }))
+ );
+});
+afterEach(() => {
+ cleanup();
+ client.clear();
+ vi.unstubAllGlobals();
+});
+function show() {
+ return render(
+ <QueryClientProvider client={client}>
+ <Header />
+ </QueryClientProvider>
+ );
+}
+async function openClaim() {
+ fireEvent.click(await screen.findByRole("button", { name: "Claim this site" }));
+}
+
+describe("claim flow", () => {
+ it("keeps the plan and checkout mounted after revoking the link and refreshing metadata", async () => {
+ show();
+ await openClaim();
+ fireEvent.click(await screen.findByRole("button", { name: "Claim site" }));
+ const subscribe = await screen.findByRole("button", { name: "Start free trial" });
+ await waitFor(() => expect(screen.queryByRole("button", { name: "Claim this site" })).toBeNull());
+ expect(state.claim).toHaveBeenCalledWith(7, "aaaaaaaaaaaa", "org_1");
+ expect(state.replace).toHaveBeenCalledWith("/7/main?claim=plan");
+ fireEvent.click(subscribe);
+ await screen.findByText("Checkout secret_test");
+ const body = JSON.parse((fetch as any).mock.calls[0][1].body);
+ expect(body.organizationId).toBe("org_1");
+ expect(body.returnUrl).toBe(`${window.location.origin}/7?session_id={CHECKOUT_SESSION_ID}`);
+ });
+ it("reopens the claim step after OAuth returns", async () => {
+ state.params = new URLSearchParams("claim=1");
+ show();
+ await screen.findByRole("button", { name: "Claim site" });
+ expect(state.claim).not.toHaveBeenCalled();
+ });
+ it("resumes the plan after a reload on the owned URL", async () => {
+ state.path = "/7/main";
+ state.params = new URLSearchParams("claim=plan");
+ state.site = { ...state.site, organizationId: "org_1", claimExpiresAt: null, isOwner: true };
+ show();
+ await screen.findByRole("button", { name: "Start free trial" });
+ expect(state.claim).not.toHaveBeenCalled();
+ });
+ it("shows the banner on the globe and preserves OAuth and login return paths", async () => {
+ state.path = "/7/aaaaaaaaaaaa/globe";
+ state.user = null;
+ show();
+ await openClaim();
+ expect((await screen.findByRole("link", { name: "OAuth" })).getAttribute("href")).toBe("/7/aaaaaaaaaaaa?claim=1");
+ expect(screen.getByRole("link", { name: "Log in" }).getAttribute("href")).toBe(
+ "/login?returnTo=%2F7%2Faaaaaaaaaaaa%3Fclaim%3D1"
+ );
+ });
+ it("waits for memberships before offering to create an organization", async () => {
+ state.pending = true;
+ show();
+ await openClaim();
+ await screen.findByText("Loading...");
+ expect(screen.queryByRole("button", { name: "Claim site" })).toBeNull();
+ expect(state.createOrg).not.toHaveBeenCalled();
+ });
+ it("lets an existing admin claim into their organization", async () => {
+ state.organizations = [{ id: "org_1", name: "Existing", role: "admin" }];
+ show();
+ await openClaim();
+ fireEvent.click(await screen.findByRole("button", { name: "Claim site" }));
+ await waitFor(() => expect(state.replace).toHaveBeenCalledWith("/7"));
+ expect(state.createOrg).not.toHaveBeenCalled();
+ });
+ it("finishes self-hosted signup without checkout", async () => {
+ state.cloud = false;
+ state.user = null;
+ show();
+ await openClaim();
+ fireEvent.click(await screen.findByRole("button", { name: "Create account" }));
+ await waitFor(() => expect(state.replace).toHaveBeenCalledWith("/7"));
+ expect(fetch).not.toHaveBeenCalled();
+ });
+ it("offers login when signup is disabled", async () => {
+ state.disableSignup = true;
+ state.user = null;
+ show();
+ await openClaim();
+ await screen.findByText("Signup is disabled");
+ expect(screen.queryByRole("button", { name: "Create account" })).toBeNull();
+ });
+});
diff --git a/client/src/app/[site]/components/Header/ClaimSiteBanner.tsx b/client/src/app/[site]/components/Header/ClaimSiteBanner.tsx
new file mode 100644
index 000000000..2ee18b9ec
--- /dev/null
+++ b/client/src/app/[site]/components/Header/ClaimSiteBanner.tsx
@@ -0,0 +1,120 @@
+"use client";
+
+import { Clock } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { useSearchParams } from "next/navigation";
+import { useEffect, useState } from "react";
+import { useGetSite } from "../../../../api/admin/hooks/useSites";
+import { Button } from "../../../../components/ui/button";
+import { useStore } from "../../../../lib/store";
+import { userStore } from "../../../../lib/userStore";
+import { ClaimSiteDialog } from "./ClaimSiteDialog";
+
+function formatRemaining(ms: number) {
+ if (ms <= 0) return "0m";
+ const totalMinutes = Math.floor(ms / 60_000);
+ const hours = Math.floor(totalMinutes / 60);
+ const minutes = totalMinutes % 60;
+ return hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`;
+}
+
+/**
+ * Shown on every page of an unclaimed site's dashboard, for as long as it is
+ * unclaimed. It never collapses or hides: the deadline is real.
+ */
+export function ClaimSiteBanner() {
+ const t = useExtracted();
+ const { site, privateKey } = useStore();
+ const { user } = userStore();
+ const { data: siteMetadata } = useGetSite(site);
+ const searchParams = useSearchParams();
+
+ // OAuth signup returns here with ?claim=1 so the dialog reopens at the claim step.
+ const [open, setOpen] = useState(false);
+ const [claimTarget, setClaimTarget] = useState<{
+ siteId: number;
+ domain: string;
+ privateLinkKey: string;
+ } | null>(null);
+ const [now, setNow] = useState(() => Date.now());
+
+ const isUnclaimed = !!siteMetadata && siteMetadata.organizationId === null && !!siteMetadata.claimExpiresAt;
+
+ useEffect(() => {
+ if (!isUnclaimed) return;
+ const id = setInterval(() => setNow(Date.now()), 30_000);
+ return () => clearInterval(id);
+ }, [isUnclaimed]);
+
+ const resumePlan = !!user && siteMetadata?.isOwner && searchParams.get("claim") === "plan";
+ const target =
+ claimTarget ??
+ (siteMetadata && (isUnclaimed || resumePlan)
+ ? {
+ siteId: siteMetadata.siteId,
+ domain: siteMetadata.domain,
+ privateLinkKey: privateKey ?? "",
+ }
+ : null);
+
+ const changeOpen = (next: boolean) => {
+ if (next && target) setClaimTarget(target);
+ setOpen(next);
+ };
+
+ useEffect(() => {
+ if ((isUnclaimed && user && searchParams.get("claim") === "1") || resumePlan) {
+ if (siteMetadata)
+ setClaimTarget({
+ siteId: siteMetadata.siteId,
+ domain: siteMetadata.domain,
+ privateLinkKey: privateKey ?? "",
+ });
+ setOpen(true);
+ }
+ }, [isUnclaimed, user, searchParams, resumePlan, siteMetadata, privateKey]);
+
+ const remainingMs = siteMetadata?.claimExpiresAt ? new Date(siteMetadata.claimExpiresAt).getTime() - now : 0;
+ const expired = remainingMs <= 0;
+
+ return (
+ <>
+ {isUnclaimed && siteMetadata && (
+ <div
+ role="status"
+ className="mt-4 flex flex-wrap items-center gap-x-4 gap-y-2 rounded-lg border border-yellow-500/40 bg-yellow-500/10 px-4 py-3 text-sm dark:border-yellow-400/30 dark:bg-yellow-400/10"
+ >
+ <div className="flex min-w-0 items-center gap-2">
+ <Clock className="h-4 w-4 shrink-0 text-yellow-700 dark:text-yellow-300" aria-hidden="true" />
+ <span className="text-neutral-800 dark:text-neutral-100">
+ {expired
+ ? t("{domain} has expired and will be deleted shortly.", { domain: siteMetadata.domain })
+ : t("{domain} isn't claimed. It will be deleted in {remaining} unless you claim it.", {
+ domain: siteMetadata.domain,
+ remaining: formatRemaining(remainingMs),
+ })}
+ </span>
+ </div>
+ <Button
+ variant="success"
+ size="sm"
+ className="ml-auto"
+ onClick={() => changeOpen(true)}
+ disabled={expired || !privateKey}
+ >
+ {t("Claim this site")}
+ </Button>
+ </div>
+ )}
+ {target && (
+ <ClaimSiteDialog
+ key={target.siteId}
+ open={open}
+ onOpenChange={changeOpen}
+ {...target}
+ organizationId={resumePlan ? (siteMetadata?.organizationId ?? undefined) : undefined}
+ />
+ )}
+ </>
+ );
+}
diff --git a/client/src/app/[site]/components/Header/ClaimSiteDialog.tsx b/client/src/app/[site]/components/Header/ClaimSiteDialog.tsx
new file mode 100644
index 000000000..060c222fa
--- /dev/null
+++ b/client/src/app/[site]/components/Header/ClaimSiteDialog.tsx
@@ -0,0 +1,412 @@
+"use client";
+
+import { AuthError } from "@/components/auth/AuthError";
+import { CheckoutModal } from "@/components/subscription/components/CheckoutModal";
+import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
+import { Label } from "@/components/ui/label";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { useQueryClient } from "@tanstack/react-query";
+import { ArrowRight, Check } from "lucide-react";
+import { useExtracted } from "next-intl";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import React, { useState } from "react";
+import type { SiteResponse } from "../../../../api/admin/endpoints/sites";
+import { claimSite } from "../../../../api/admin/endpoints";
+import { USER_ORGANIZATIONS_QUERY_KEY, useUserOrganizations } from "../../../../api/admin/hooks/useOrganizations";
+import { authClient } from "../../../../lib/auth";
+import { useConfigs } from "../../../../lib/configs";
+import { BACKEND_URL, IS_CLOUD } from "../../../../lib/const";
+import { trackAdEvent } from "../../../../lib/trackAdEvent";
+import { userStore } from "../../../../lib/userStore";
+import { cn } from "../../../../lib/utils";
+import { AccountStep } from "../../../signup/components/AccountStep";
+import { PlanStep } from "../../../signup/components/PlanStep";
+import { EVENT_TIERS, findPriceForTier } from "../../../subscribe/components/utils";
+
+interface ClaimSiteDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ siteId: number;
+ domain: string;
+ privateLinkKey: string;
+ organizationId?: string;
+}
+
+function slugFromDomain(domain: string) {
+ const base = domain
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "");
+ return `${base || "site"}-${Math.random().toString(36).slice(2, 6)}`;
+}
+
+/**
+ * The signup flow, minus the "Add site" step: the site already exists. A new
+ * visitor creates an account, we create an organization named after the
+ * domain and claim the site into it, then (cloud) they pick a plan. A visitor
+ * who is already signed in only picks which organization keeps the site.
+ */
+export function ClaimSiteDialog({
+ open,
+ onOpenChange,
+ siteId,
+ domain,
+ privateLinkKey,
+ organizationId: resumeOrganizationId,
+}: ClaimSiteDialogProps) {
+ const t = useExtracted();
+ const router = useRouter();
+ const queryClient = useQueryClient();
+ const { user } = userStore();
+ const { configs, isLoading: isLoadingConfigs } = useConfigs();
+ const {
+ data: organizations,
+ isPending: isLoadingOrganizations,
+ error: organizationsError,
+ } = useUserOrganizations({ enabled: !!user });
+
+ const [isLoading, setIsLoading] = useState(false);
+ const [error, setError] = useState("");
+
+ // Account step
+ const [email, setEmail] = useState("");
+ const [password, setPassword] = useState("");
+ const [turnstileToken, setTurnstileToken] = useState("");
+
+ // Plan step (cloud)
+ const [eventLimitIndex, setEventLimitIndex] = useState(0);
+ const [isAnnual, setIsAnnual] = useState(true);
+ const [selectedPlan, setSelectedPlan] = useState<"standard" | "pro">("pro");
+ const [checkoutClientSecret, setCheckoutClientSecret] = useState<string | null>(null);
+
+ const [claimedOrganizationId, setClaimedOrganizationId] = useState<string | null>(resumeOrganizationId ?? null);
+ const planOrganizationId = claimedOrganizationId ?? resumeOrganizationId;
+ const returnPath = `/${siteId}/${privateLinkKey}?claim=1`;
+ const [selectedOrganizationId, setSelectedOrganizationId] = useState<string>("");
+
+ const adminOrganizations = (organizations ?? []).filter(org => org.role === "owner" || org.role === "admin");
+ const hasExistingOrganization = !!user && adminOrganizations.length > 0;
+
+ // Step 1 = account (skipped when signed in), step 2 = claim (existing org only), step 3 = plan (cloud only)
+ const steps = IS_CLOUD ? [{ label: t("Account") }, { label: t("Pick plan") }] : [{ label: t("Account") }];
+ const currentStepIndex = planOrganizationId ? 1 : 0;
+
+ const claimInto = async (organizationId: string, pickPlan = false) => {
+ const active = await authClient.organization.setActive({ organizationId });
+ if (active.error) throw new Error(active.error.message);
+ await claimSite(siteId, privateLinkKey, organizationId);
+ setClaimedOrganizationId(organizationId);
+
+ // Move off the revoked link immediately. The dialog stays mounted in the
+ // site layout, and ?claim=plan can resume the plan step after a reload.
+ router.replace(`/${siteId}/main${pickPlan && IS_CLOUD ? "?claim=plan" : ""}`);
+ await queryClient.cancelQueries({ queryKey: ["get-site"] });
+ for (const id of [siteId, String(siteId)]) {
+ queryClient.setQueryData(["get-site", id], (site: SiteResponse | null | undefined) =>
+ site
+ ? {
+ ...site,
+ organizationId,
+ claimExpiresAt: null,
+ isOwner: true,
+ }
+ : site
+ );
+ }
+ void queryClient.invalidateQueries({ queryKey: ["get-site"] });
+ void queryClient.invalidateQueries({ queryKey: ["get-sites-from-org", organizationId] });
+ void queryClient.invalidateQueries({ queryKey: ["site-is-public"] });
+ void queryClient.invalidateQueries({ queryKey: [USER_ORGANIZATIONS_QUERY_KEY] });
+ };
+
+ const createOrganizationAndClaim = async () => {
+ const { data, error: orgError } = await authClient.organization.create({
+ name: domain,
+ slug: slugFromDomain(domain),
+ });
+ if (orgError) {
+ throw new Error(orgError.message || t("Failed to create organization"));
+ }
+ if (!data?.id) {
+ throw new Error(t("No organization ID returned"));
+ }
+ await claimInto(data.id, true);
+ return data.id;
+ };
+
+ const finish = () => {
+ onOpenChange(false);
+ router.replace(`/${siteId}`);
+ };
+
+ const handleAccountSubmit = async () => {
+ setIsLoading(true);
+ setError("");
+
+ try {
+ if (IS_CLOUD && !turnstileToken) {
+ setError(t("Please complete the captcha verification"));
+ return;
+ }
+
+ const { data, error: signupError } = await authClient.signUp.email(
+ { email, name: email.split("@")[0], password },
+ {
+ onRequest: context => {
+ if (IS_CLOUD && turnstileToken) {
+ context.headers.set("x-captcha-response", turnstileToken);
+ }
+ },
+ }
+ );
+
+ if (signupError) {
+ setError(signupError.message ?? "");
+ return;
+ }
+
+ if (data?.user) {
+ userStore.setState({ user: data.user });
+ trackAdEvent("signup");
+ await createOrganizationAndClaim();
+ if (!IS_CLOUD) finish();
+ }
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const handleExistingUserClaim = async () => {
+ setIsLoading(true);
+ setError("");
+
+ try {
+ if (hasExistingOrganization) {
+ const organizationId = selectedOrganizationId || adminOrganizations[0].id;
+ await claimInto(organizationId);
+ finish();
+ } else {
+ await createOrganizationAndClaim();
+ if (!IS_CLOUD) finish();
+ }
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const handleSubscribe = async () => {
+ setIsLoading(true);
+ setError("");
+
+ try {
+ const eventLimit = EVENT_TIERS[eventLimitIndex];
+ if (eventLimit === "Custom") return;
+
+ const selectedTierPrice = findPriceForTier(eventLimit, isAnnual ? "year" : "month", selectedPlan);
+ if (!selectedTierPrice) {
+ setError(t("Could not find a matching plan. Please try a different selection."));
+ return;
+ }
+
+ const returnUrl = `${window.location.origin}/${siteId}?session_id={CHECKOUT_SESSION_ID}`;
+ const checkoutResponse = await fetch(`${BACKEND_URL}/stripe/create-checkout-session`, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ credentials: "include",
+ body: JSON.stringify({
+ priceId: selectedTierPrice.priceId,
+ returnUrl,
+ organizationId: planOrganizationId,
+ referral: (window as any).Rewardful?.referral || undefined,
+ }),
+ });
+
+ const checkoutData = await checkoutResponse.json();
+ if (!checkoutResponse.ok) {
+ throw new Error(checkoutData.error || t("Failed to create checkout session"));
+ }
+
+ trackAdEvent("checkout", { tier: selectedTierPrice.name });
+ setCheckoutClientSecret(checkoutData.clientSecret);
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const renderContent = () => {
+ if (planOrganizationId && IS_CLOUD) {
+ return (
+ <PlanStep
+ eventLimitIndex={eventLimitIndex}
+ setEventLimitIndex={setEventLimitIndex}
+ isAnnual={isAnnual}
+ setIsAnnual={setIsAnnual}
+ selectedPlan={selectedPlan}
+ setSelectedPlan={setSelectedPlan}
+ onSubscribe={handleSubscribe}
+ isLoading={isLoading}
+ />
+ );
+ }
+
+ if (user) {
+ if (isLoadingOrganizations) return <p>{t("Loading...")}</p>;
+ if (organizationsError) return <AuthError error={organizationsError.message} />;
+ return (
+ <div className="space-y-4">
+ <h2 className="text-2xl font-semibold">{t("Keep {domain}", { domain })}</h2>
+ {hasExistingOrganization ? (
+ <div className="space-y-2">
+ <Label htmlFor="claim-organization">{t("Organization")}</Label>
+ <Select
+ value={selectedOrganizationId || adminOrganizations[0].id}
+ onValueChange={setSelectedOrganizationId}
+ >
+ <SelectTrigger id="claim-organization" className="h-10">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {adminOrganizations.map(org => (
+ <SelectItem key={org.id} value={org.id}>
+ {org.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <p className="text-xs text-muted-foreground">{t("The site moves into this organization.")}</p>
+ </div>
+ ) : (
+ <p className="text-sm text-neutral-600 dark:text-neutral-400">
+ {t("We'll create an organization named {domain} and move the site into it.", { domain })}
+ </p>
+ )}
+ <Button
+ variant="success"
+ className="h-11 w-full bg-emerald-600 text-white hover:bg-emerald-500"
+ onClick={handleExistingUserClaim}
+ disabled={isLoading}
+ >
+ {t("Claim site")}
+ <ArrowRight className="ml-2 h-4 w-4" />
+ </Button>
+ </div>
+ );
+ }
+
+ if (isLoadingConfigs) return <p>{t("Loading...")}</p>;
+ if (configs?.disableSignup)
+ return (
+ <div className="space-y-4">
+ <p>{t("Signup is disabled")}</p>
+ <Link href={`/login?returnTo=${encodeURIComponent(returnPath)}`}>{t("Log in")}</Link>
+ </div>
+ );
+
+ return (
+ <AccountStep
+ email={email}
+ setEmail={setEmail}
+ password={password}
+ setPassword={setPassword}
+ turnstileToken={turnstileToken}
+ setTurnstileToken={setTurnstileToken}
+ isLoading={isLoading}
+ onSubmit={handleAccountSubmit}
+ setError={setError}
+ socialCallbackURL={returnPath}
+ loginHref={`/login?returnTo=${encodeURIComponent(returnPath)}`}
+ />
+ );
+ };
+
+ return (
+ <>
+ <Dialog
+ open={open && !checkoutClientSecret}
+ onOpenChange={next => {
+ if (isLoading) return;
+ if (!next && planOrganizationId) finish();
+ else onOpenChange(next);
+ }}
+ >
+ <DialogContent className="max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-[560px]">
+ <div className="mb-2">
+ <DialogTitle className="text-3xl font-medium">
+ {IS_CLOUD ? t("Start your 7-day free trial") : t("Get started with Rybbit")}
+ </DialogTitle>
+ <p className="mt-3 text-sm text-neutral-500 dark:text-neutral-400">
+ {t("Claim {domain} to keep its dashboard and everything it has collected.", { domain })}
+ </p>
+ </div>
+
+ {steps.length > 1 && (
+ <div className="mb-4 flex w-full items-center">
+ {steps.map(({ label }, index, arr) => (
+ <React.Fragment key={label}>
+ <div className="flex flex-col items-center gap-2">
+ <div
+ className={cn(
+ "flex h-8 w-8 items-center justify-center rounded-full text-xs font-medium transition-all duration-300",
+ currentStepIndex === index
+ ? "bg-emerald-600 text-white shadow-lg shadow-emerald-600/30"
+ : currentStepIndex > index
+ ? "bg-emerald-600 text-white"
+ : "bg-neutral-200 text-neutral-500 dark:bg-neutral-800 dark:text-neutral-400"
+ )}
+ >
+ {currentStepIndex > index ? <Check className="h-4 w-4" /> : index + 1}
+ </div>
+ <span
+ className={cn(
+ "text-xs font-medium transition-colors duration-300",
+ currentStepIndex >= index
+ ? "text-neutral-900 dark:text-neutral-100"
+ : "text-neutral-400 dark:text-neutral-500"
+ )}
+ >
+ {label}
+ </span>
+ </div>
+ {index < arr.length - 1 && (
+ <div
+ className={cn(
+ "mx-3 mb-6 h-0.5 flex-1 rounded-full transition-all duration-300",
+ currentStepIndex > index ? "bg-emerald-600" : "bg-neutral-200 dark:bg-neutral-800"
+ )}
+ />
+ )}
+ </React.Fragment>
+ ))}
+ </div>
+ )}
+
+ <div className="flex flex-col gap-4">
+ {renderContent()}
+ <AuthError error={error} />
+ </div>
+ </DialogContent>
+ </Dialog>
+
+ {IS_CLOUD && (
+ <CheckoutModal
+ clientSecret={checkoutClientSecret}
+ open={!!checkoutClientSecret}
+ onOpenChange={next => {
+ if (!next) {
+ setCheckoutClientSecret(null);
+ finish();
+ }
+ }}
+ />
+ )}
+ </>
+ );
+}
diff --git a/client/src/app/[site]/components/Header/Header.tsx b/client/src/app/[site]/components/Header/Header.tsx
index 2fc5fe0ac..016dde26f 100644
--- a/client/src/app/[site]/components/Header/Header.tsx
+++ b/client/src/app/[site]/components/Header/Header.tsx
@@ -1,28 +1,46 @@
"use client";
import { usePathname } from "next/navigation";
+import { useGetSite } from "../../../../api/admin/hooks/useSites";
import { FreePlanBanner } from "../../../../components/FreePlanBanner";
+import { useStore } from "../../../../lib/store";
import { userStore } from "../../../../lib/userStore";
import { AffiliateBanner } from "./AffiliateBanner";
+import { ClaimSiteBanner } from "./ClaimSiteBanner";
import { DemoSignupBanner } from "./DemoSignupBanner";
import { NoData } from "./NoData";
import { UsageBanners } from "./UsageBanners";
export function Header() {
const { user } = userStore();
+ const { site } = useStore();
+ const { data: siteMetadata } = useGetSite(site);
const pathname = usePathname();
+ // An unclaimed site's visitor has no session, but still needs the claim
+ // banner and the install instructions.
+ const isUnclaimed = !!siteMetadata && siteMetadata.organizationId === null && !!siteMetadata.claimExpiresAt;
+
+ const isGlobe = pathname.includes("/globe");
+
+ if (!user && !isUnclaimed) {
+ return <div className="flex flex-col" />;
+ }
+
return (
<div className="flex flex-col">
- {user && !pathname.includes("/globe") && (
- <div className="flex flex-col px-2 md:px-4">
- <DemoSignupBanner />
- <AffiliateBanner />
- <FreePlanBanner />
- <UsageBanners />
- <NoData />
- </div>
- )}
+ <div className="flex flex-col px-2 md:px-4">
+ <ClaimSiteBanner />
+ {user && !isGlobe && !isUnclaimed && (
+ <>
+ <DemoSignupBanner />
+ <AffiliateBanner />
+ <FreePlanBanner />
+ <UsageBanners />
+ </>
+ )}
+ {!isGlobe && <NoData />}
+ </div>
</div>
);
}
diff --git a/client/src/app/login/page.tsx b/client/src/app/login/page.tsx
index a88eb100f..852e67071 100644
--- a/client/src/app/login/page.tsx
+++ b/client/src/app/login/page.tsx
@@ -7,8 +7,8 @@ import { SocialButtons } from "@/components/auth/SocialButtons";
import { Turnstile } from "@/components/auth/Turnstile";
import { useExtracted } from "next-intl";
import Link from "next/link";
-import { useRouter } from "next/navigation";
-import { useState } from "react";
+import { useRouter, useSearchParams } from "next/navigation";
+import { Suspense, useState } from "react";
import { RybbitTextLogo } from "../../components/RybbitLogo";
import { SpinningGlobe } from "../../components/SpinningGlobe";
import { useSetPageTitle } from "../../hooks/useSetPageTitle";
@@ -17,7 +17,10 @@ import { useConfigs } from "../../lib/configs";
import { IS_CLOUD } from "../../lib/const";
import { userStore } from "../../lib/userStore";
-export default function Page() {
+function LoginPage() {
+ const searchParams = useSearchParams();
+ const requestedReturn = searchParams.get("returnTo") ?? "";
+ const returnTo = /^\/\d+\/[a-f0-9]{12}\?claim=1$/i.test(requestedReturn) ? requestedReturn : "/";
const { configs, isLoading: isLoadingConfigs } = useConfigs();
useSetPageTitle("Login");
const t = useExtracted();
@@ -59,7 +62,7 @@ export default function Page() {
userStore.setState({
user: data.user,
});
- router.push("/");
+ router.push(returnTo);
}
if (error) {
@@ -86,7 +89,7 @@ export default function Page() {
<div className="flex-1 flex flex-col justify-center w-full max-w-[550px] mx-auto">
<h1 className="text-lg text-neutral-600 dark:text-neutral-300 mb-6">{t("Welcome back")}</h1>
<div className="flex flex-col gap-4">
- <SocialButtons onError={setError} />
+ <SocialButtons onError={setError} callbackURL={returnTo} />
<form onSubmit={handleSubmit}>
<div className="flex flex-col gap-4">
<AuthInput
@@ -172,3 +175,11 @@ export default function Page() {
</div>
);
}
+
+export default function Page() {
+ return (
+ <Suspense fallback={null}>
+ <LoginPage />
+ </Suspense>
+ );
+}
diff --git a/client/src/app/signup/components/AccountStep.tsx b/client/src/app/signup/components/AccountStep.tsx
index a5462c6a3..88bb569e4 100644
--- a/client/src/app/signup/components/AccountStep.tsx
+++ b/client/src/app/signup/components/AccountStep.tsx
@@ -18,6 +18,9 @@ interface AccountStepProps {
isLoading: boolean;
onSubmit: () => void;
setError: (v: string) => void;
+ /** Where OAuth returns to. Defaults to the signup page's next step. */
+ socialCallbackURL?: string;
+ loginHref?: string;
}
export function AccountStep({
@@ -30,6 +33,8 @@ export function AccountStep({
isLoading,
onSubmit,
setError,
+ socialCallbackURL = "/signup?step=2",
+ loginHref = "/login",
}: AccountStepProps) {
const t = useExtracted();
@@ -37,7 +42,7 @@ export function AccountStep({
<div>
<h2 className="text-2xl font-semibold mb-4">{t("Signup")}</h2>
<div className="space-y-4">
- <SocialButtons onError={setError} callbackURL="/signup?step=2" mode="signup" />
+ <SocialButtons onError={setError} callbackURL={socialCallbackURL} mode="signup" />
<AuthInput
id="email"
label={t("Email")}
@@ -78,7 +83,7 @@ export function AccountStep({
<div className="text-center text-sm">
{t("Already have an account?")}{" "}
<Link
- href="/login"
+ href={loginHref}
className="underline underline-offset-4 hover:text-emerald-400 transition-colors duration-300"
>
{t("Log in")}
diff --git a/client/src/app/try/page.tsx b/client/src/app/try/page.tsx
new file mode 100644
index 000000000..6fcc74da2
--- /dev/null
+++ b/client/src/app/try/page.tsx
@@ -0,0 +1,151 @@
+"use client";
+
+import { AuthError } from "@/components/auth/AuthError";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { ArrowRight } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { useRouter, useSearchParams } from "next/navigation";
+import { Suspense, useEffect, useRef, useState } from "react";
+import { createUnclaimedSite } from "../../api/admin/endpoints";
+import { RybbitTextLogo } from "../../components/RybbitLogo";
+import { useSetPageTitle } from "../../hooks/useSetPageTitle";
+import { useConfigs } from "../../lib/configs";
+import { IS_CLOUD } from "../../lib/const";
+import { isValidDomain, normalizeDomain } from "../../lib/utils";
+
+/**
+ * Landing-page entry point: /try?domain=example.com creates an owner-less site
+ * and drops the visitor straight into its private-link dashboard. They claim it
+ * from the banner there. Without a usable domain, or on failure, this page
+ * shows the same input so the visitor can retry.
+ */
+function TryPageContent() {
+ const t = useExtracted();
+ const { configs, isLoading: isLoadingConfigs, error: configError } = useConfigs();
+ useSetPageTitle("Start tracking");
+ const router = useRouter();
+ const searchParams = useSearchParams();
+ const initialDomain = normalizeDomain(searchParams.get("domain") ?? "");
+
+ const [domain, setDomain] = useState(initialDomain);
+ const [error, setError] = useState("");
+ const [isLoading, setIsLoading] = useState(false);
+ const autoSubmitted = useRef(false);
+
+ const submit = async (value: string) => {
+ const normalized = normalizeDomain(value);
+ if (!isValidDomain(normalized)) {
+ setError(t("Invalid domain format. Must be a valid domain like example.com or sub.example.com"));
+ return;
+ }
+
+ setIsLoading(true);
+ setError("");
+ try {
+ const site = await createUnclaimedSite(normalized);
+ router.replace(`/${site.siteId}/${site.privateLinkKey}`);
+ } catch (e) {
+ setError(e instanceof Error ? e.message : String(e));
+ setIsLoading(false);
+ }
+ };
+
+ // Arriving from the landing page with a valid domain: go straight through.
+ useEffect(() => {
+ if (!configs || configs.disableSignup) return;
+ if (autoSubmitted.current || !initialDomain || !isValidDomain(initialDomain)) return;
+ autoSubmitted.current = true;
+ void submit(initialDomain);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [initialDomain, configs]);
+
+ if (configs?.disableSignup || configError) {
+ return (
+ <div className="mx-auto max-w-md p-8">
+ <AuthError error={configError?.message ?? t("Signup is disabled")} />
+ </div>
+ );
+ }
+
+ if ((isLoading || isLoadingConfigs) && !error) {
+ return (
+ <div className="flex h-dvh w-full items-center justify-center">
+ <div className="flex flex-col items-center gap-4 text-center">
+ <div className="h-8 w-8 animate-spin rounded-full border-2 border-emerald-500 border-t-transparent" />
+ <p className="text-sm text-neutral-500 dark:text-neutral-400">
+ {t("Setting up your dashboard for {domain}…", { domain })}
+ </p>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex h-dvh w-full justify-center">
+ <div className="flex w-full max-w-[550px] flex-col p-6 lg:p-10">
+ <div className="mb-8">
+ <a href="https://rybbit.com" target="_blank" className="inline-block">
+ <RybbitTextLogo />
+ </a>
+ </div>
+
+ <form
+ className="flex flex-1 flex-col justify-center gap-6"
+ onSubmit={e => {
+ e.preventDefault();
+ void submit(domain);
+ }}
+ >
+ <div>
+ <h1 className="text-3xl font-medium">{t("See who's on your site")}</h1>
+ <p className="mt-3 text-sm text-neutral-500 dark:text-neutral-400">
+ {t("Enter your domain to open a live dashboard. No account needed until you want to keep it.")}
+ </p>
+ </div>
+
+ <div className="space-y-2">
+ <Label htmlFor="domain">{t("Website Domain")}</Label>
+ <Input
+ id="domain"
+ type="text"
+ autoFocus
+ placeholder="example.com or sub.example.com"
+ value={domain}
+ onChange={e => setDomain(e.target.value.toLowerCase())}
+ required
+ className="h-11 bg-neutral-100 transition-all dark:bg-neutral-800/50 border-neutral-200 dark:border-neutral-700"
+ />
+ </div>
+
+ <Button
+ type="submit"
+ variant="success"
+ className="h-11 w-full bg-emerald-600 text-white transition-all duration-300 hover:bg-emerald-500"
+ disabled={isLoading || !domain || !isValidDomain(normalizeDomain(domain))}
+ >
+ {t("See my dashboard")}
+ <ArrowRight className="ml-2 h-4 w-4" />
+ </Button>
+
+ <AuthError error={error} />
+
+ <p className="text-xs text-neutral-500 dark:text-neutral-400">
+ {IS_CLOUD
+ ? t("Your dashboard stays open for 24 hours. Claim it with a free 7-day trial to keep it.")
+ : t("Your dashboard stays open for 24 hours. Create an account to keep it.")}
+ </p>
+ </form>
+ </div>
+ </div>
+ );
+}
+
+export default function TryPage() {
+ return (
+ <Suspense fallback={null}>
+ <TryPageContent />
+ </Suspense>
+ );
+}
diff --git a/client/src/components/AuthenticationGuard.tsx b/client/src/components/AuthenticationGuard.tsx
index 0ebff8213..b34364075 100644
--- a/client/src/components/AuthenticationGuard.tsx
+++ b/client/src/components/AuthenticationGuard.tsx
@@ -5,7 +5,7 @@ import { redirect, usePathname } from "next/navigation";
import { userStore } from "../lib/userStore";
import { useGetSiteIsPublic } from "../api/admin/hooks/useSites";
-const PUBLIC_ROUTES = ["/login", "/signup", "/invitation", "/reset-password", "/as/callback", "/auth/consent"];
+const PUBLIC_ROUTES = ["/login", "/signup", "/try", "/invitation", "/reset-password", "/as/callback", "/auth/consent"];
export function AuthenticationGuard() {
const { user, isPending } = userStore();
diff --git a/client/src/proxy.test.ts b/client/src/proxy.test.ts
new file mode 100644
index 000000000..377513c5a
--- /dev/null
+++ b/client/src/proxy.test.ts
@@ -0,0 +1,18 @@
+import { NextRequest } from "next/server";
+import { describe, expect, it } from "vitest";
+import { proxy } from "./proxy";
+
+describe("onboarding routes", () => {
+ it("serves /try instead of treating it as a site ID", async () => {
+ const response = await proxy(new NextRequest("https://app.rybbit.io/try?domain=acme.dev"));
+ expect(response.headers.get("location")).toBeNull();
+ });
+ it("preserves the OAuth claim flag when opening a private dashboard", async () => {
+ const response = await proxy(new NextRequest("https://app.rybbit.io/7/aaaaaaaaaaaa?claim=1"));
+ expect(response.headers.get("location")).toBe("https://app.rybbit.io/7/aaaaaaaaaaaa/main?claim=1");
+ });
+ it("preserves the checkout session on the owned dashboard redirect", async () => {
+ const response = await proxy(new NextRequest("https://app.rybbit.io/7?session_id=cs_test"));
+ expect(response.headers.get("location")).toBe("https://app.rybbit.io/7/main?session_id=cs_test");
+ });
+});
diff --git a/client/src/proxy.ts b/client/src/proxy.ts
index b8d8918f2..f90ab5e31 100644
--- a/client/src/proxy.ts
+++ b/client/src/proxy.ts
@@ -36,6 +36,7 @@ export async function proxy(request: NextRequest) {
const excludedRoutes = [
"login",
"signup",
+ "try",
"subscribe",
"invitation",
"reset-password",
diff --git a/docs/messages/en.json b/docs/messages/en.json
index 406e9f8e2..072b369ab 100644
--- a/docs/messages/en.json
+++ b/docs/messages/en.json
@@ -424,5 +424,14 @@
"wYsv4Z": "Monthly",
"2C6TrW": "Annual",
"HJ5o5M": "4 months free",
- "tGb9bA": "Go to pricing option {number}"
+ "tGb9bA": "Go to pricing option {number}",
+ "pnufjq": "Or open the live demo",
+ "uH9HRD": "No account needed. Claim your site later with a 7-day free trial.",
+ "FHZK07": "Your website domain",
+ "G1qHRE": "yourdomain.com",
+ "wjMsGC": "See my dashboard",
+ "Jh8pKq": "Enter a domain like example.com",
+ "oHdA+N": "Ready for better analytics?",
+ "0Ha+fM": "Start for $0",
+ "/KlgcS": "7-day free trial. Cancel anytime."
}
diff --git a/docs/src/components/CTASection.tsx b/docs/src/components/CTASection.tsx
index 7a06ea476..e96cccbf0 100644
--- a/docs/src/components/CTASection.tsx
+++ b/docs/src/components/CTASection.tsx
@@ -1,4 +1,5 @@
import { CtaDataLine } from "@/components/deco/CtaDataLine";
+import { DomainStartForm } from "@/components/DomainStartForm";
import { WatchfulFrog } from "@/components/deco/WatchfulFrog";
import { GridCrosses } from "@/components/GridCrosses";
import { TrackedButton } from "@/components/TrackedButton";
@@ -19,7 +20,7 @@ export function CTASection({
title,
description,
primaryButtonText,
- primaryButtonHref = "https://app.rybbit.io/signup",
+ primaryButtonHref,
secondaryButtonText,
secondaryButtonHref = "https://demo.rybbit.com/81",
eventLocation = "bottom_cta",
@@ -28,8 +29,12 @@ export function CTASection({
const resolvedTitle = title ?? t("Ready for better analytics?");
const resolvedDescription =
description ?? t("The full analytics surface on one dashboard: cookieless, open source, and live in minutes.");
+ const resolvedPrimaryButtonHref = primaryButtonHref ?? "https://app.rybbit.io/signup";
const resolvedPrimaryButtonText = primaryButtonText ?? t("Start for $0");
const resolvedSecondaryButtonText = secondaryButtonText ?? t("Live demo");
+ // Pages that route the primary action somewhere else keep their button; the
+ // default signup destination becomes the domain input.
+ const useDomainInput = primaryButtonHref === undefined && primaryButtonText === undefined;
return (
<section className="group relative overflow-hidden border-b border-emerald-900 bg-emerald-950 text-white">
@@ -55,19 +60,29 @@ export function CTASection({
<div className="relative z-10 flex flex-col justify-center px-5 py-12 sm:px-8 lg:col-span-4 lg:px-10">
<p className="max-w-md text-base leading-7 text-emerald-100/80">{resolvedDescription}</p>
- <div className="mt-8 flex flex-col gap-3 sm:flex-row lg:flex-col xl:flex-row">
- <TrackedButton
- href={primaryButtonHref}
- eventName="signup"
- eventProps={{ location: eventLocation, button_text: resolvedPrimaryButtonText }}
- className="group inline-flex min-h-11 items-center justify-center gap-2 rounded-md bg-white px-5 py-2.5 text-sm font-medium text-emerald-950 transition-colors duration-200 hover:bg-emerald-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-offset-2 focus-visible:ring-offset-emerald-950"
- >
- {resolvedPrimaryButtonText}
- <ArrowRight
- className="size-4 transition-transform duration-200 group-hover:translate-x-0.5 motion-reduce:transition-none"
- aria-hidden="true"
- />
- </TrackedButton>
+ <div
+ className={
+ useDomainInput
+ ? "mt-8 flex flex-col gap-3"
+ : "mt-8 flex flex-col gap-3 sm:flex-row lg:flex-col xl:flex-row"
+ }
+ >
+ {useDomainInput ? (
+ <DomainStartForm location={eventLocation} variant="inverted" className="sm:max-w-none xl:max-w-md" />
+ ) : (
+ <TrackedButton
+ href={resolvedPrimaryButtonHref}
+ eventName="signup"
+ eventProps={{ location: eventLocation, button_text: resolvedPrimaryButtonText }}
+ className="group inline-flex min-h-11 items-center justify-center gap-2 rounded-md bg-white px-5 py-2.5 text-sm font-medium text-emerald-950 transition-colors duration-200 hover:bg-emerald-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-offset-2 focus-visible:ring-offset-emerald-950"
+ >
+ {resolvedPrimaryButtonText}
+ <ArrowRight
+ className="size-4 transition-transform duration-200 group-hover:translate-x-0.5 motion-reduce:transition-none"
+ aria-hidden="true"
+ />
+ </TrackedButton>
+ )}
<TrackedButton
href={secondaryButtonHref}
eventName="demo"
@@ -84,7 +99,11 @@ export function CTASection({
</TrackedButton>
</div>
- <p className="mt-6 text-sm text-emerald-100/60">{t("7-day free trial. Cancel anytime.")}</p>
+ <p className="mt-6 text-sm text-emerald-100/60">
+ {useDomainInput
+ ? t("No account needed. Claim your site later with a 7-day free trial.")
+ : t("7-day free trial. Cancel anytime.")}
+ </p>
</div>
</div>
</section>
diff --git a/docs/src/components/DomainStartForm.tsx b/docs/src/components/DomainStartForm.tsx
new file mode 100644
index 000000000..7644ae64e
--- /dev/null
+++ b/docs/src/components/DomainStartForm.tsx
@@ -0,0 +1,110 @@
+"use client";
+
+import { appendReferral } from "@/lib/rewardful";
+import { ArrowRight } from "lucide-react";
+import { useExtracted } from "next-intl";
+import { useState } from "react";
+
+const DOMAIN_PATTERN = /^(?:[\p{L}\p{N}](?:[\p{L}\p{N}-]{0,61}[\p{L}\p{N}])?\.)+\p{L}{2,}$/u;
+
+export function normalizeDomain(value: string) {
+ return value
+ .trim()
+ .toLowerCase()
+ .replace(/^https?:\/\//, "")
+ .replace(/^www\./, "")
+ .split(/[/?#]/)[0];
+}
+
+interface DomainStartFormProps {
+ /** Where on the page the form sits; sent with the analytics event. */
+ location: string;
+ /** "hero" sits on the page ground; "inverted" sits on the emerald CTA band. */
+ variant?: "hero" | "inverted";
+ buttonText?: string;
+ className?: string;
+}
+
+/**
+ * Replaces the signup button: the visitor types a domain and lands on a live
+ * dashboard for it (app.rybbit.io/try creates the site, no account needed).
+ */
+export function DomainStartForm({ location, variant = "hero", buttonText, className = "" }: DomainStartFormProps) {
+ const t = useExtracted();
+ const [domain, setDomain] = useState("");
+ const [invalid, setInvalid] = useState(false);
+ const inverted = variant === "inverted";
+
+ const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
+ e.preventDefault();
+ const normalized = normalizeDomain(domain);
+ if (!DOMAIN_PATTERN.test(normalized)) {
+ setInvalid(true);
+ return;
+ }
+ window.rybbit?.event?.("signup", { location, method: "domain_input" });
+ const href = `https://app.rybbit.io/try?domain=${encodeURIComponent(normalized)}`;
+ window.location.href = appendReferral(href);
+ };
+
+ const inputId = `domain-start-${location}`;
+
+ return (
+ <form onSubmit={onSubmit} className={`flex w-full max-w-md flex-col gap-2 ${className}`} noValidate>
+ <label htmlFor={inputId} className="sr-only">
+ {t("Your website domain")}
+ </label>
+ <div
+ className={
+ inverted
+ ? "flex min-h-11 flex-col items-stretch overflow-hidden rounded-md border border-white/25 bg-white/10 transition-colors focus-within:border-white/60 focus-within:ring-2 focus-within:ring-white/40"
+ : "flex min-h-11 flex-col items-stretch overflow-hidden rounded-md border border-neutral-300 sm:flex-row bg-white transition-colors focus-within:border-neutral-400 focus-within:ring-2 focus-within:ring-emerald-500/40 dark:border-neutral-700 dark:bg-neutral-950 dark:focus-within:border-neutral-500"
+ }
+ >
+ <input
+ id={inputId}
+ type="text"
+ inputMode="url"
+ autoComplete="url"
+ autoCapitalize="off"
+ spellCheck={false}
+ placeholder={t("yourdomain.com")}
+ value={domain}
+ onChange={e => {
+ setDomain(e.target.value);
+ if (invalid) setInvalid(false);
+ }}
+ aria-invalid={invalid || undefined}
+ aria-describedby={invalid ? `${inputId}-error` : undefined}
+ className={
+ inverted
+ ? "min-h-11 min-w-0 flex-1 bg-transparent px-3.5 text-sm text-white placeholder:text-emerald-100/50 focus:outline-none"
+ : "min-h-11 min-w-0 flex-1 bg-transparent px-3.5 text-sm text-neutral-900 placeholder:text-neutral-500 focus:outline-none dark:text-white dark:placeholder:text-neutral-500"
+ }
+ />
+ <button
+ type="submit"
+ className={
+ inverted
+ ? "group inline-flex min-h-11 shrink-0 items-center justify-center gap-2 bg-white px-4 text-sm font-medium text-emerald-950 transition-colors duration-200 hover:bg-emerald-50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white focus-visible:ring-inset"
+ : "group inline-flex min-h-11 shrink-0 items-center justify-center gap-2 bg-emerald-600 px-4 text-sm font-medium text-white transition-colors duration-200 hover:bg-emerald-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500 focus-visible:ring-inset"
+ }
+ >
+ {buttonText ?? t("See my dashboard")}
+ <ArrowRight
+ className="size-4 transition-transform duration-200 group-hover:translate-x-0.5 motion-reduce:transition-none"
+ aria-hidden="true"
+ />
+ </button>
+ </div>
+ {invalid && (
+ <p
+ id={`${inputId}-error`}
+ className={inverted ? "text-xs text-emerald-100/80" : "text-xs text-red-600 dark:text-red-400"}
+ >
+ {t("Enter a domain like example.com")}
+ </p>
+ )}
+ </form>
+ );
+}
diff --git a/docs/src/components/HeroSection.tsx b/docs/src/components/HeroSection.tsx
index 527527e00..20b3b3cfa 100644
--- a/docs/src/components/HeroSection.tsx
+++ b/docs/src/components/HeroSection.tsx
@@ -1,9 +1,10 @@
import { GitHubStarButton } from "@/components/GitHubStarButton";
import { GridCrosses } from "@/components/GridCrosses";
+import { DomainStartForm } from "@/components/DomainStartForm";
import { HeroDataLine } from "@/components/HeroDataLine";
import { WatchfulFrog } from "@/components/deco/WatchfulFrog";
import { TrackedButton } from "@/components/TrackedButton";
-import { ArrowRight, ExternalLink } from "lucide-react";
+import { ExternalLink } from "lucide-react";
import { useExtracted } from "next-intl";
const EUFlag = () => (
@@ -62,28 +63,17 @@ export function HeroSection({ title, subtitle, showEUFlag = true, showGitHubStar
</div>
)}
- <div className="mt-6 flex flex-col gap-3 sm:flex-row">
- <TrackedButton
- href="https://app.rybbit.io/signup"
- eventName="signup"
- eventProps={{ location: "hero", button_text: "get started" }}
- className="group inline-flex min-h-11 items-center justify-center gap-2 rounded-md bg-emerald-600 px-5 py-2.5 text-sm font-medium text-white transition-colors duration-200 hover:bg-emerald-500 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-500 focus-visible:ring-offset-2 focus-visible:ring-offset-white dark:focus-visible:ring-offset-neutral-950"
- >
- {t("Start for $0")}
- <ArrowRight
- className="size-4 transition-transform duration-200 group-hover:translate-x-0.5 motion-reduce:transition-none"
- aria-hidden="true"
- />
- </TrackedButton>
+ <div className="mt-6 flex flex-col gap-3">
+ <DomainStartForm location="hero" />
<TrackedButton
href="https://demo.rybbit.com/81"
eventName="demo"
target="_blank"
rel="noopener noreferrer"
eventProps={{ location: "hero", button_text: "Live demo" }}
- className="group inline-flex min-h-11 items-center justify-center gap-2 rounded-md border border-neutral-300 px-5 py-2.5 text-sm font-medium text-neutral-900 transition-colors duration-200 hover:bg-neutral-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-500 focus-visible:ring-offset-2 dark:border-neutral-700 dark:text-white dark:hover:bg-neutral-900 dark:focus-visible:ring-offset-neutral-950"
+ className="group inline-flex w-fit items-center gap-1.5 text-sm font-medium text-neutral-600 transition-colors duration-200 hover:text-neutral-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-neutral-500 focus-visible:ring-offset-2 dark:text-neutral-400 dark:hover:text-white dark:focus-visible:ring-offset-neutral-950"
>
- {t("Live demo")}
+ {t("Or open the live demo")}
<ExternalLink
className="size-3.5 transition-transform duration-200 group-hover:-translate-y-0.5 group-hover:translate-x-0.5 motion-reduce:transition-none"
aria-hidden="true"
@@ -92,7 +82,7 @@ export function HeroSection({ title, subtitle, showEUFlag = true, showGitHubStar
</div>
<p className="mt-4 text-sm text-neutral-500 dark:text-neutral-400">
- {t("7-day free trial. Cancel anytime.")}
+ {t("No account needed. Claim your site later with a 7-day free trial.")}
</p>
</div>
</div>
diff --git a/server/drizzle/0020_unclaimed_sites.sql b/server/drizzle/0020_unclaimed_sites.sql
new file mode 100644
index 000000000..b2c1d96e1
--- /dev/null
+++ b/server/drizzle/0020_unclaimed_sites.sql
@@ -0,0 +1 @@
+ALTER TABLE "sites" ADD COLUMN "claim_expires_at" timestamp;
\ No newline at end of file
diff --git a/server/drizzle/meta/0020_snapshot.json b/server/drizzle/meta/0020_snapshot.json
new file mode 100644
index 000000000..28cd05978
--- /dev/null
+++ b/server/drizzle/meta/0020_snapshot.json
@@ -0,0 +1,4549 @@
+{
+ "id": "0b0237da-9eb1-4b21-b26e-0db3bef8c568",
+ "prevId": "7b3a6cd9-f9ab-4707-960c-ded6c41265a1",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.account": {
+ "name": "account",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "accountId": {
+ "name": "accountId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "providerId": {
+ "name": "providerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "accessToken": {
+ "name": "accessToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refreshToken": {
+ "name": "refreshToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "idToken": {
+ "name": "idToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessTokenExpiresAt": {
+ "name": "accessTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refreshTokenExpiresAt": {
+ "name": "refreshTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "account_userId_user_id_fk": {
+ "name": "account_userId_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.active_sessions": {
+ "name": "active_sessions",
+ "schema": "",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "start_time": {
+ "name": "start_time",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "last_activity": {
+ "name": "last_activity",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.annotations": {
+ "name": "annotations",
+ "schema": "",
+ "columns": {
+ "annotation_id": {
+ "name": "annotation_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "date": {
+ "name": "date",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "end_date": {
+ "name": "end_date",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_public": {
+ "name": "is_public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "annotations_site_date_idx": {
+ "name": "annotations_site_date_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "date",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "annotations_org_date_idx": {
+ "name": "annotations_org_date_idx",
+ "columns": [
+ {
+ "expression": "organization_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "date",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "annotations_site_id_sites_site_id_fk": {
+ "name": "annotations_site_id_sites_site_id_fk",
+ "tableFrom": "annotations",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "annotations_organization_id_organization_id_fk": {
+ "name": "annotations_organization_id_organization_id_fk",
+ "tableFrom": "annotations",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "annotations_user_id_user_id_fk": {
+ "name": "annotations_user_id_user_id_fk",
+ "tableFrom": "annotations",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.apikey": {
+ "name": "apikey",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "start": {
+ "name": "start",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "prefix": {
+ "name": "prefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refillInterval": {
+ "name": "refillInterval",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refillAmount": {
+ "name": "refillAmount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastRefillAt": {
+ "name": "lastRefillAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "rateLimitEnabled": {
+ "name": "rateLimitEnabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "rateLimitTimeWindow": {
+ "name": "rateLimitTimeWindow",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rateLimitMax": {
+ "name": "rateLimitMax",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requestCount": {
+ "name": "requestCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "remaining": {
+ "name": "remaining",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastRequest": {
+ "name": "lastRequest",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "configId": {
+ "name": "configId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.cancellation_feedback": {
+ "name": "cancellation_feedback",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "reason_details": {
+ "name": "reason_details",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "retention_offer_shown": {
+ "name": "retention_offer_shown",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "retention_offer_accepted": {
+ "name": "retention_offer_accepted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "outcome": {
+ "name": "outcome",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "plan_name_at_cancellation": {
+ "name": "plan_name_at_cancellation",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "monthly_event_count_at_cancellation": {
+ "name": "monthly_event_count_at_cancellation",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.dashboards": {
+ "name": "dashboards",
+ "schema": "",
+ "columns": {
+ "dashboard_id": {
+ "name": "dashboard_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{\"cards\":[]}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "dashboards_site_id_sites_site_id_fk": {
+ "name": "dashboards_site_id_sites_site_id_fk",
+ "tableFrom": "dashboards",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "dashboards_user_id_user_id_fk": {
+ "name": "dashboards_user_id_user_id_fk",
+ "tableFrom": "dashboards",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.experiments": {
+ "name": "experiments",
+ "schema": "",
+ "columns": {
+ "experiment_id": {
+ "name": "experiment_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "feature_flag_id": {
+ "name": "feature_flag_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "primary_goal_id": {
+ "name": "primary_goal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "hypothesis": {
+ "name": "hypothesis",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'draft'"
+ },
+ "winning_variant": {
+ "name": "winning_variant",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "experiments_site_idx": {
+ "name": "experiments_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "experiments_feature_flag_idx": {
+ "name": "experiments_feature_flag_idx",
+ "columns": [
+ {
+ "expression": "feature_flag_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "experiments_primary_goal_idx": {
+ "name": "experiments_primary_goal_idx",
+ "columns": [
+ {
+ "expression": "primary_goal_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "experiments_site_id_sites_site_id_fk": {
+ "name": "experiments_site_id_sites_site_id_fk",
+ "tableFrom": "experiments",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "experiments_feature_flag_id_feature_flags_flag_id_fk": {
+ "name": "experiments_feature_flag_id_feature_flags_flag_id_fk",
+ "tableFrom": "experiments",
+ "tableTo": "feature_flags",
+ "columnsFrom": [
+ "feature_flag_id"
+ ],
+ "columnsTo": [
+ "flag_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "experiments_primary_goal_id_goals_goal_id_fk": {
+ "name": "experiments_primary_goal_id_goals_goal_id_fk",
+ "tableFrom": "experiments",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "primary_goal_id"
+ ],
+ "columnsTo": [
+ "goal_id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "experiments_site_flag_unique": {
+ "name": "experiments_site_flag_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "site_id",
+ "feature_flag_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "experiments_status_check": {
+ "name": "experiments_status_check",
+ "value": "status IN ('draft', 'running', 'paused', 'completed')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.feature_flags": {
+ "name": "feature_flags",
+ "schema": "",
+ "columns": {
+ "flag_id": {
+ "name": "flag_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "runtime": {
+ "name": "runtime",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'client'"
+ },
+ "flag_type": {
+ "name": "flag_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'boolean'"
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "variants": {
+ "name": "variants",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "rollout_percentage": {
+ "name": "rollout_percentage",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 100
+ },
+ "rules": {
+ "name": "rules",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "condition_sets": {
+ "name": "condition_sets",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "salt": {
+ "name": "salt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "md5(random()::text || clock_timestamp()::text)"
+ },
+ "version": {
+ "name": "version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "feature_flags_site_idx": {
+ "name": "feature_flags_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "feature_flags_site_id_sites_site_id_fk": {
+ "name": "feature_flags_site_id_sites_site_id_fk",
+ "tableFrom": "feature_flags",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "feature_flags_site_key_unique": {
+ "name": "feature_flags_site_key_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "site_id",
+ "key"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "feature_flags_rollout_check": {
+ "name": "feature_flags_rollout_check",
+ "value": "rollout_percentage >= 0 AND rollout_percentage <= 100"
+ },
+ "feature_flags_runtime_check": {
+ "name": "feature_flags_runtime_check",
+ "value": "runtime IN ('client', 'server', 'both')"
+ },
+ "feature_flags_type_check": {
+ "name": "feature_flags_type_check",
+ "value": "flag_type IN ('boolean', 'multivariate', 'remote_config')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.funnels": {
+ "name": "funnels",
+ "schema": "",
+ "columns": {
+ "report_id": {
+ "name": "report_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data": {
+ "name": "data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "funnels_site_id_sites_site_id_fk": {
+ "name": "funnels_site_id_sites_site_id_fk",
+ "tableFrom": "funnels",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "funnels_user_id_user_id_fk": {
+ "name": "funnels_user_id_user_id_fk",
+ "tableFrom": "funnels",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.goals": {
+ "name": "goals",
+ "schema": "",
+ "columns": {
+ "goal_id": {
+ "name": "goal_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "goal_type": {
+ "name": "goal_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "goals_site_id_sites_site_id_fk": {
+ "name": "goals_site_id_sites_site_id_fk",
+ "tableFrom": "goals",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.gsc_connections": {
+ "name": "gsc_connections",
+ "schema": "",
+ "columns": {
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "gsc_property_url": {
+ "name": "gsc_property_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "gsc_connections_site_id_sites_site_id_fk": {
+ "name": "gsc_connections_site_id_sites_site_id_fk",
+ "tableFrom": "gsc_connections",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.import_status": {
+ "name": "import_status",
+ "schema": "",
+ "columns": {
+ "import_id": {
+ "name": "import_id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "platform": {
+ "name": "platform",
+ "type": "import_platform_enum",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "imported_events": {
+ "name": "imported_events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "skipped_events": {
+ "name": "skipped_events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "invalid_events": {
+ "name": "invalid_events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "import_status_site_id_sites_site_id_fk": {
+ "name": "import_status_site_id_sites_site_id_fk",
+ "tableFrom": "import_status",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "import_status_organization_id_organization_id_fk": {
+ "name": "import_status_organization_id_organization_id_fk",
+ "tableFrom": "import_status",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.invitation": {
+ "name": "invitation",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "inviterId": {
+ "name": "inviterId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "has_restricted_site_access": {
+ "name": "has_restricted_site_access",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "site_ids": {
+ "name": "site_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "teamId": {
+ "name": "teamId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "invitation_inviterId_user_id_fk": {
+ "name": "invitation_inviterId_user_id_fk",
+ "tableFrom": "invitation",
+ "tableTo": "user",
+ "columnsFrom": [
+ "inviterId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "invitation_organizationId_organization_id_fk": {
+ "name": "invitation_organizationId_organization_id_fk",
+ "tableFrom": "invitation",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organizationId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "invitation_teamId_team_id_fk": {
+ "name": "invitation_teamId_team_id_fk",
+ "tableFrom": "invitation",
+ "tableTo": "team",
+ "columnsFrom": [
+ "teamId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.jwks": {
+ "name": "jwks",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "publicKey": {
+ "name": "publicKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "privateKey": {
+ "name": "privateKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "alg": {
+ "name": "alg",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "crv": {
+ "name": "crv",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.lifecycle_email_log": {
+ "name": "lifecycle_email_log",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email_key": {
+ "name": "email_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "lifecycle_email_log_user_id_user_id_fk": {
+ "name": "lifecycle_email_log_user_id_user_id_fk",
+ "tableFrom": "lifecycle_email_log",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "lifecycle_email_log_user_email_key_unique": {
+ "name": "lifecycle_email_log_user_email_key_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "user_id",
+ "email_key"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.member": {
+ "name": "member",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "has_restricted_site_access": {
+ "name": "has_restricted_site_access",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "member_organizationId_organization_id_fk": {
+ "name": "member_organizationId_organization_id_fk",
+ "tableFrom": "member",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organizationId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "member_userId_user_id_fk": {
+ "name": "member_userId_user_id_fk",
+ "tableFrom": "member",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.member_site_access": {
+ "name": "member_site_access",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "member_id": {
+ "name": "member_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "member_site_access_member_idx": {
+ "name": "member_site_access_member_idx",
+ "columns": [
+ {
+ "expression": "member_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "member_site_access_site_idx": {
+ "name": "member_site_access_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "member_site_access_member_id_member_id_fk": {
+ "name": "member_site_access_member_id_member_id_fk",
+ "tableFrom": "member_site_access",
+ "tableTo": "member",
+ "columnsFrom": [
+ "member_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "member_site_access_site_id_sites_site_id_fk": {
+ "name": "member_site_access_site_id_sites_site_id_fk",
+ "tableFrom": "member_site_access",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "member_site_access_created_by_user_id_fk": {
+ "name": "member_site_access_created_by_user_id_fk",
+ "tableFrom": "member_site_access",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "member_site_access_unique": {
+ "name": "member_site_access_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "member_id",
+ "site_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthAccessToken": {
+ "name": "oauthAccessToken",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "accessToken": {
+ "name": "accessToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refreshToken": {
+ "name": "refreshToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessTokenExpiresAt": {
+ "name": "accessTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refreshTokenExpiresAt": {
+ "name": "refreshTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauthAccessToken_clientId_oauthApplication_clientId_fk": {
+ "name": "oauthAccessToken_clientId_oauthApplication_clientId_fk",
+ "tableFrom": "oauthAccessToken",
+ "tableTo": "oauthApplication",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthAccessToken_userId_user_id_fk": {
+ "name": "oauthAccessToken_userId_user_id_fk",
+ "tableFrom": "oauthAccessToken",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthAccessToken_accessToken_unique": {
+ "name": "oauthAccessToken_accessToken_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "accessToken"
+ ]
+ },
+ "oauthAccessToken_refreshToken_unique": {
+ "name": "oauthAccessToken_refreshToken_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "refreshToken"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthAccessTokenV2": {
+ "name": "oauthAccessTokenV2",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sessionId": {
+ "name": "sessionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authorizationCodeId": {
+ "name": "authorizationCodeId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resources": {
+ "name": "resources",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requestedUserInfoClaims": {
+ "name": "requestedUserInfoClaims",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refreshId": {
+ "name": "refreshId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "revoked": {
+ "name": "revoked",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "confirmation": {
+ "name": "confirmation",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "oauthAccessTokenV2_clientId_idx": {
+ "name": "oauthAccessTokenV2_clientId_idx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthAccessTokenV2_sessionId_idx": {
+ "name": "oauthAccessTokenV2_sessionId_idx",
+ "columns": [
+ {
+ "expression": "sessionId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthAccessTokenV2_userId_idx": {
+ "name": "oauthAccessTokenV2_userId_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthAccessTokenV2_authorizationCodeId_idx": {
+ "name": "oauthAccessTokenV2_authorizationCodeId_idx",
+ "columns": [
+ {
+ "expression": "authorizationCodeId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthAccessTokenV2_refreshId_idx": {
+ "name": "oauthAccessTokenV2_refreshId_idx",
+ "columns": [
+ {
+ "expression": "refreshId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauthAccessTokenV2_clientId_oauthClient_clientId_fk": {
+ "name": "oauthAccessTokenV2_clientId_oauthClient_clientId_fk",
+ "tableFrom": "oauthAccessTokenV2",
+ "tableTo": "oauthClient",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthAccessTokenV2_sessionId_session_id_fk": {
+ "name": "oauthAccessTokenV2_sessionId_session_id_fk",
+ "tableFrom": "oauthAccessTokenV2",
+ "tableTo": "session",
+ "columnsFrom": [
+ "sessionId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "oauthAccessTokenV2_userId_user_id_fk": {
+ "name": "oauthAccessTokenV2_userId_user_id_fk",
+ "tableFrom": "oauthAccessTokenV2",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthAccessTokenV2_refreshId_oauthRefreshToken_id_fk": {
+ "name": "oauthAccessTokenV2_refreshId_oauthRefreshToken_id_fk",
+ "tableFrom": "oauthAccessTokenV2",
+ "tableTo": "oauthRefreshToken",
+ "columnsFrom": [
+ "refreshId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthAccessTokenV2_token_unique": {
+ "name": "oauthAccessTokenV2_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthApplication": {
+ "name": "oauthApplication",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientSecret": {
+ "name": "clientSecret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "redirectUrls": {
+ "name": "redirectUrls",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "disabled": {
+ "name": "disabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauthApplication_userId_user_id_fk": {
+ "name": "oauthApplication_userId_user_id_fk",
+ "tableFrom": "oauthApplication",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthApplication_clientId_unique": {
+ "name": "oauthApplication_clientId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "clientId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthClient": {
+ "name": "oauthClient",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientSecret": {
+ "name": "clientSecret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "clientDiscoveryId": {
+ "name": "clientDiscoveryId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "disabled": {
+ "name": "disabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "skipConsent": {
+ "name": "skipConsent",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enableEndSession": {
+ "name": "enableEndSession",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "subjectType": {
+ "name": "subjectType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "clientCredentialsScopes": {
+ "name": "clientCredentialsScopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "uri": {
+ "name": "uri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "contacts": {
+ "name": "contacts",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tos": {
+ "name": "tos",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "policy": {
+ "name": "policy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "softwareId": {
+ "name": "softwareId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "softwareVersion": {
+ "name": "softwareVersion",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "softwareStatement": {
+ "name": "softwareStatement",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "redirectUris": {
+ "name": "redirectUris",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "postLogoutRedirectUris": {
+ "name": "postLogoutRedirectUris",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "backchannelLogoutUri": {
+ "name": "backchannelLogoutUri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "backchannelLogoutSessionRequired": {
+ "name": "backchannelLogoutSessionRequired",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tokenEndpointAuthMethod": {
+ "name": "tokenEndpointAuthMethod",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "applicationType": {
+ "name": "applicationType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "jwks": {
+ "name": "jwks",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "jwksUri": {
+ "name": "jwksUri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "grantTypes": {
+ "name": "grantTypes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "responseTypes": {
+ "name": "responseTypes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requirePKCE": {
+ "name": "requirePKCE",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "dpopBoundAccessTokens": {
+ "name": "dpopBoundAccessTokens",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "oauthClient_userId_idx": {
+ "name": "oauthClient_userId_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauthClient_userId_user_id_fk": {
+ "name": "oauthClient_userId_user_id_fk",
+ "tableFrom": "oauthClient",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthClient_clientId_unique": {
+ "name": "oauthClient_clientId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "clientId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthClientAssertion": {
+ "name": "oauthClientAssertion",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthClientResource": {
+ "name": "oauthClientResource",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "resourceId": {
+ "name": "resourceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "oauthClientResource_clientId_resourceId_uidx": {
+ "name": "oauthClientResource_clientId_resourceId_uidx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "resourceId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthClientResource_clientId_idx": {
+ "name": "oauthClientResource_clientId_idx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthClientResource_resourceId_idx": {
+ "name": "oauthClientResource_resourceId_idx",
+ "columns": [
+ {
+ "expression": "resourceId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauthClientResource_clientId_oauthClient_clientId_fk": {
+ "name": "oauthClientResource_clientId_oauthClient_clientId_fk",
+ "tableFrom": "oauthClientResource",
+ "tableTo": "oauthClient",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthClientResource_resourceId_oauthResource_identifier_fk": {
+ "name": "oauthClientResource_resourceId_oauthResource_identifier_fk",
+ "tableFrom": "oauthClientResource",
+ "tableTo": "oauthResource",
+ "columnsFrom": [
+ "resourceId"
+ ],
+ "columnsTo": [
+ "identifier"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthConsent": {
+ "name": "oauthConsent",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "consentGiven": {
+ "name": "consentGiven",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauthConsent_clientId_oauthApplication_clientId_fk": {
+ "name": "oauthConsent_clientId_oauthApplication_clientId_fk",
+ "tableFrom": "oauthConsent",
+ "tableTo": "oauthApplication",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthConsent_userId_user_id_fk": {
+ "name": "oauthConsent_userId_user_id_fk",
+ "tableFrom": "oauthConsent",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthConsentV2": {
+ "name": "oauthConsentV2",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resources": {
+ "name": "resources",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requestedUserInfoClaims": {
+ "name": "requestedUserInfoClaims",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "oauthConsentV2_clientId_idx": {
+ "name": "oauthConsentV2_clientId_idx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthConsentV2_userId_idx": {
+ "name": "oauthConsentV2_userId_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauthConsentV2_clientId_oauthClient_clientId_fk": {
+ "name": "oauthConsentV2_clientId_oauthClient_clientId_fk",
+ "tableFrom": "oauthConsentV2",
+ "tableTo": "oauthClient",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthConsentV2_userId_user_id_fk": {
+ "name": "oauthConsentV2_userId_user_id_fk",
+ "tableFrom": "oauthConsentV2",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthRefreshToken": {
+ "name": "oauthRefreshToken",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sessionId": {
+ "name": "sessionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authorizationCodeId": {
+ "name": "authorizationCodeId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resources": {
+ "name": "resources",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requestedUserInfoClaims": {
+ "name": "requestedUserInfoClaims",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "revoked": {
+ "name": "revoked",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rotatedAt": {
+ "name": "rotatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rotationReplayResponse": {
+ "name": "rotationReplayResponse",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rotationReplayExpiresAt": {
+ "name": "rotationReplayExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authTime": {
+ "name": "authTime",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "confirmation": {
+ "name": "confirmation",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "oauthRefreshToken_clientId_idx": {
+ "name": "oauthRefreshToken_clientId_idx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthRefreshToken_sessionId_idx": {
+ "name": "oauthRefreshToken_sessionId_idx",
+ "columns": [
+ {
+ "expression": "sessionId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthRefreshToken_userId_idx": {
+ "name": "oauthRefreshToken_userId_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthRefreshToken_authorizationCodeId_idx": {
+ "name": "oauthRefreshToken_authorizationCodeId_idx",
+ "columns": [
+ {
+ "expression": "authorizationCodeId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauthRefreshToken_clientId_oauthClient_clientId_fk": {
+ "name": "oauthRefreshToken_clientId_oauthClient_clientId_fk",
+ "tableFrom": "oauthRefreshToken",
+ "tableTo": "oauthClient",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthRefreshToken_sessionId_session_id_fk": {
+ "name": "oauthRefreshToken_sessionId_session_id_fk",
+ "tableFrom": "oauthRefreshToken",
+ "tableTo": "session",
+ "columnsFrom": [
+ "sessionId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "oauthRefreshToken_userId_user_id_fk": {
+ "name": "oauthRefreshToken_userId_user_id_fk",
+ "tableFrom": "oauthRefreshToken",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthRefreshToken_token_unique": {
+ "name": "oauthRefreshToken_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthResource": {
+ "name": "oauthResource",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "accessTokenTtl": {
+ "name": "accessTokenTtl",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refreshTokenTtl": {
+ "name": "refreshTokenTtl",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "signingAlgorithm": {
+ "name": "signingAlgorithm",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "signingKeyId": {
+ "name": "signingKeyId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "allowedScopes": {
+ "name": "allowedScopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "customClaims": {
+ "name": "customClaims",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "dpopBoundAccessTokensRequired": {
+ "name": "dpopBoundAccessTokensRequired",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "disabled": {
+ "name": "disabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "policyVersion": {
+ "name": "policyVersion",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 1
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthResource_identifier_unique": {
+ "name": "oauthResource_identifier_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "identifier"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.organization": {
+ "name": "organization",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "logo": {
+ "name": "logo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "monthlyEventCount": {
+ "name": "monthlyEventCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "overMonthlyLimit": {
+ "name": "overMonthlyLimit",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "approachingLimitNotifiedPeriodStart": {
+ "name": "approachingLimitNotifiedPeriodStart",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "planOverride": {
+ "name": "planOverride",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "custom_plan": {
+ "name": "custom_plan",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "organization_slug_unique": {
+ "name": "organization_slug_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "slug"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.segments": {
+ "name": "segments",
+ "schema": "",
+ "columns": {
+ "segment_id": {
+ "name": "segment_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "filters": {
+ "name": "filters",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "is_public": {
+ "name": "is_public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'segment'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "segments_organization_idx": {
+ "name": "segments_organization_idx",
+ "columns": [
+ {
+ "expression": "organization_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "segments_site_idx": {
+ "name": "segments_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "segments_organization_id_organization_id_fk": {
+ "name": "segments_organization_id_organization_id_fk",
+ "tableFrom": "segments",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "segments_site_id_sites_site_id_fk": {
+ "name": "segments_site_id_sites_site_id_fk",
+ "tableFrom": "segments",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "segments_user_id_user_id_fk": {
+ "name": "segments_user_id_user_id_fk",
+ "tableFrom": "segments",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.session": {
+ "name": "session",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ipAddress": {
+ "name": "ipAddress",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userAgent": {
+ "name": "userAgent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "impersonatedBy": {
+ "name": "impersonatedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "activeOrganizationId": {
+ "name": "activeOrganizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "activeTeamId": {
+ "name": "activeTeamId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "session_userId_user_id_fk": {
+ "name": "session_userId_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "session_token_unique": {
+ "name": "session_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.sites": {
+ "name": "sites",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "domain": {
+ "name": "domain",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "public": {
+ "name": "public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "embed_enabled": {
+ "name": "embed_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "saltUserIds": {
+ "name": "saltUserIds",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "blockBots": {
+ "name": "blockBots",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "first_party_proxy": {
+ "name": "first_party_proxy",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "excluded_ips": {
+ "name": "excluded_ips",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_countries": {
+ "name": "excluded_countries",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_paths": {
+ "name": "excluded_paths",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_hostnames": {
+ "name": "excluded_hostnames",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_user_agents": {
+ "name": "excluded_user_agents",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_asns": {
+ "name": "excluded_asns",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_query_params": {
+ "name": "excluded_query_params",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "sessionReplay": {
+ "name": "sessionReplay",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "webVitals": {
+ "name": "webVitals",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackErrors": {
+ "name": "trackErrors",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackOutbound": {
+ "name": "trackOutbound",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackUrlParams": {
+ "name": "trackUrlParams",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackInitialPageView": {
+ "name": "trackInitialPageView",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackSpaNavigation": {
+ "name": "trackSpaNavigation",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackIp": {
+ "name": "trackIp",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackButtonClicks": {
+ "name": "trackButtonClicks",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackCopy": {
+ "name": "trackCopy",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackFormInteractions": {
+ "name": "trackFormInteractions",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "api_key": {
+ "name": "api_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "private_link_key": {
+ "name": "private_link_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tags": {
+ "name": "tags",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "detected_platform": {
+ "name": "detected_platform",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "claim_expires_at": {
+ "name": "claim_expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "sites_created_by_user_id_fk": {
+ "name": "sites_created_by_user_id_fk",
+ "tableFrom": "sites",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "sites_organization_id_organization_id_fk": {
+ "name": "sites_organization_id_organization_id_fk",
+ "tableFrom": "sites",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "sites_type_check": {
+ "name": "sites_type_check",
+ "value": "\"sites\".\"type\" IS NULL OR \"sites\".\"type\" IN ('web', 'mobile')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.team": {
+ "name": "team",
+ "schema": "",
+ "columns": {
+ "memberCount": {
+ "name": "memberCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "team_organizationId_organization_id_fk": {
+ "name": "team_organizationId_organization_id_fk",
+ "tableFrom": "team",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organizationId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.teamMember": {
+ "name": "teamMember",
+ "schema": "",
+ "columns": {
+ "membershipKey": {
+ "name": "membershipKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "teamId": {
+ "name": "teamId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "teamMember_teamId_team_id_fk": {
+ "name": "teamMember_teamId_team_id_fk",
+ "tableFrom": "teamMember",
+ "tableTo": "team",
+ "columnsFrom": [
+ "teamId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "teamMember_userId_user_id_fk": {
+ "name": "teamMember_userId_user_id_fk",
+ "tableFrom": "teamMember",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "teamMember_membershipKey_unique": {
+ "name": "teamMember_membershipKey_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "membershipKey"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.team_site_access": {
+ "name": "team_site_access",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "team_site_access_team_idx": {
+ "name": "team_site_access_team_idx",
+ "columns": [
+ {
+ "expression": "team_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "team_site_access_site_idx": {
+ "name": "team_site_access_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "team_site_access_team_id_team_id_fk": {
+ "name": "team_site_access_team_id_team_id_fk",
+ "tableFrom": "team_site_access",
+ "tableTo": "team",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "team_site_access_site_id_sites_site_id_fk": {
+ "name": "team_site_access_site_id_sites_site_id_fk",
+ "tableFrom": "team_site_access",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "team_site_access_unique": {
+ "name": "team_site_access_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "team_id",
+ "site_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.telemetry": {
+ "name": "telemetry",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "instance_id": {
+ "name": "instance_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "version": {
+ "name": "version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "table_counts": {
+ "name": "table_counts",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clickhouse_size_gb": {
+ "name": "clickhouse_size_gb",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user": {
+ "name": "user",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "username": {
+ "name": "username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "emailVerified": {
+ "name": "emailVerified",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'user'"
+ },
+ "displayUsername": {
+ "name": "displayUsername",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "banned": {
+ "name": "banned",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "banReason": {
+ "name": "banReason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "banExpires": {
+ "name": "banExpires",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "overMonthlyLimit": {
+ "name": "overMonthlyLimit",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "monthlyEventCount": {
+ "name": "monthlyEventCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "sendAutoEmailReports": {
+ "name": "sendAutoEmailReports",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "scheduled_tip_email_ids": {
+ "name": "scheduled_tip_email_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_username_unique": {
+ "name": "user_username_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "username"
+ ]
+ },
+ "user_email_unique": {
+ "name": "user_email_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "email"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_aliases": {
+ "name": "user_aliases",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "anonymous_id": {
+ "name": "anonymous_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_aliases_user_idx": {
+ "name": "user_aliases_user_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_aliases_anon_idx": {
+ "name": "user_aliases_anon_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "anonymous_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_aliases_site_id_sites_site_id_fk": {
+ "name": "user_aliases_site_id_sites_site_id_fk",
+ "tableFrom": "user_aliases",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_aliases_site_anon_unique": {
+ "name": "user_aliases_site_anon_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "site_id",
+ "anonymous_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_profiles": {
+ "name": "user_profiles",
+ "schema": "",
+ "columns": {
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "traits": {
+ "name": "traits",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_profiles_site_idx": {
+ "name": "user_profiles_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_profiles_site_id_sites_site_id_fk": {
+ "name": "user_profiles_site_id_sites_site_id_fk",
+ "tableFrom": "user_profiles",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "user_profiles_site_id_user_id_pk": {
+ "name": "user_profiles_site_id_user_id_pk",
+ "columns": [
+ "site_id",
+ "user_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verification": {
+ "name": "verification",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {
+ "public.import_platform_enum": {
+ "name": "import_platform_enum",
+ "schema": "public",
+ "values": [
+ "umami",
+ "simple_analytics",
+ "plausible"
+ ]
+ }
+ },
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/server/drizzle/meta/_journal.json b/server/drizzle/meta/_journal.json
index 0e2a58b42..8bd607b8c 100644
--- a/server/drizzle/meta/_journal.json
+++ b/server/drizzle/meta/_journal.json
@@ -141,6 +141,13 @@
"when": 1789184125327,
"tag": "0019_invitation_created_at",
"breakpoints": true
+ },
+ {
+ "idx": 20,
+ "version": "7",
+ "when": 1789189000176,
+ "tag": "0020_unclaimed_sites",
+ "breakpoints": true
}
]
-}
+}
\ No newline at end of file
diff --git a/server/src/api/sites/addSite.test.ts b/server/src/api/sites/addSite.test.ts
index 726625e50..a8467e046 100644
--- a/server/src/api/sites/addSite.test.ts
+++ b/server/src/api/sites/addSite.test.ts
@@ -1,3 +1,4 @@
+vi.mock("../../services/lifecycleEmails/platformDetect.js", () => ({ detectPlatform: vi.fn(async () => null) }));
import { beforeEach, describe, expect, it, vi } from "vitest";
const state = vi.hoisted(() => ({
@@ -13,6 +14,10 @@ const mocks = vi.hoisted(() => ({
vi.mock("../../db/postgres/postgres.js", () => ({
db: {
+ execute: vi.fn(async () => []),
+ async transaction<T>(operation: (tx: unknown) => Promise<T>): Promise<T> {
+ return operation(this);
+ },
select: vi.fn(() => ({
from: () => ({
where: async () => Array.from({ length: state.existingSiteCount }, (_, i) => ({ siteId: i + 1 })),
diff --git a/server/src/api/sites/applySiteMove.ts b/server/src/api/sites/applySiteMove.ts
index fbc7cb417..92d9faed6 100644
--- a/server/src/api/sites/applySiteMove.ts
+++ b/server/src/api/sites/applySiteMove.ts
@@ -1,6 +1,7 @@
import { eq } from "drizzle-orm";
import { db } from "../../db/postgres/postgres.js";
import { memberSiteAccess, segments, sites, teamSiteAccess } from "../../db/postgres/schema.js";
+import type { SiteTransaction } from "../../services/sites/withOrganizationSiteLock.js";
import { invalidateSitesAccessCache } from "../../lib/auth-utils.js";
/**
@@ -15,9 +16,10 @@ import { invalidateSitesAccessCache } from "../../lib/auth-utils.js";
export async function applySiteMove(
siteId: number,
sourceOrganizationId: string | null,
- targetOrganizationId: string
+ targetOrganizationId: string,
+ transaction?: SiteTransaction
) {
- await db.transaction(async tx => {
+ const move = async (tx: SiteTransaction) => {
await tx
.update(sites)
.set({ organizationId: targetOrganizationId, updatedAt: new Date().toISOString() })
@@ -29,8 +31,17 @@ export async function applySiteMove(
// hide them from the moved site and let the old org's deletion cascade
// over them. Org-wide segments (null site_id) stay with their org.
await tx.update(segments).set({ organizationId: targetOrganizationId }).where(eq(segments.siteId, siteId));
- });
+ };
+ if (transaction) await move(transaction);
+ else {
+ await db.transaction(move);
+ await invalidateSiteMoveAccess(sourceOrganizationId, targetOrganizationId);
+ }
+}
+// Call after the enclosing transaction commits so no request can repopulate
+// the old access list between invalidation and commit.
+export async function invalidateSiteMoveAccess(sourceOrganizationId: string | null, targetOrganizationId: string) {
const orgIds = sourceOrganizationId ? [sourceOrganizationId, targetOrganizationId] : [targetOrganizationId];
const affectedMembers = await db.query.member.findMany({
where: (m, { inArray }) => inArray(m.organizationId, orgIds),
diff --git a/server/src/api/sites/claimSite.ts b/server/src/api/sites/claimSite.ts
new file mode 100644
index 000000000..ef7d30e77
--- /dev/null
+++ b/server/src/api/sites/claimSite.ts
@@ -0,0 +1,63 @@
+import { FastifyReply, FastifyRequest } from "fastify";
+import { z } from "zod";
+import { getOrgMembership, isOrgAdmin } from "../../lib/access.js";
+import { invalidateSitesAccessCache } from "../../lib/auth-utils.js";
+import { SiteLifecycleError, siteConfigurationLifecycle } from "../../services/sites/siteConfigurationLifecycle.js";
+
+const claimSiteSchema = z.object({
+ privateLinkKey: z.string().regex(/^[a-f0-9]{12}$/i),
+ organizationId: z.string().min(1).max(255),
+});
+
+/**
+ * Moves an unclaimed site into one of the caller's organizations. Requires a
+ * session (route guard), org admin/owner membership, and the site's private
+ * link key as proof the caller had the dashboard open.
+ */
+export async function claimSite(
+ request: FastifyRequest<{
+ Params: { siteId: string };
+ Body: { privateLinkKey?: unknown; organizationId?: unknown };
+ }>,
+ reply: FastifyReply
+) {
+ const userId = request.user?.id;
+ if (!userId) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ const siteId = Number(request.params.siteId);
+ if (!Number.isInteger(siteId) || siteId <= 0) {
+ return reply.status(400).send({ error: "Invalid site ID" });
+ }
+
+ const parsed = claimSiteSchema.safeParse(request.body);
+ if (!parsed.success) {
+ return reply.status(400).send({ error: "privateLinkKey and organizationId are required" });
+ }
+ const { privateLinkKey, organizationId } = parsed.data;
+
+ const membership = await getOrgMembership(userId, organizationId);
+ if (!isOrgAdmin(membership)) {
+ return reply.status(403).send({ error: "You must be an admin of the organization to claim a site into it" });
+ }
+
+ try {
+ const site = await siteConfigurationLifecycle.claim({ siteId, privateLinkKey, organizationId, userId });
+ invalidateSitesAccessCache(userId);
+
+ return reply.status(200).send({
+ id: site.id,
+ siteId: site.siteId,
+ domain: site.domain,
+ organizationId: site.organizationId,
+ });
+ } catch (error) {
+ if (error instanceof SiteLifecycleError) {
+ return reply.status(error.statusCode).send({ error: error.message });
+ }
+
+ request.log.error({ err: error }, "Error claiming site");
+ return reply.status(500).send({ error: "Internal server error" });
+ }
+}
diff --git a/server/src/api/sites/createUnclaimedSite.ts b/server/src/api/sites/createUnclaimedSite.ts
new file mode 100644
index 000000000..13bceb560
--- /dev/null
+++ b/server/src/api/sites/createUnclaimedSite.ts
@@ -0,0 +1,60 @@
+import { claimExpiryIso } from "../../services/sites/claimExpiry.js";
+import { FastifyReply, FastifyRequest, type RouteShorthandOptions } from "fastify";
+import { z } from "zod";
+import { DISABLE_SIGNUP } from "../../lib/const.js";
+import { SiteLifecycleError, siteConfigurationLifecycle } from "../../services/sites/siteConfigurationLifecycle.js";
+
+const createUnclaimedSiteSchema = z.object({
+ domain: z.string().trim().min(1).max(253),
+});
+
+export const unclaimedSiteRouteOptions = {
+ bodyLimit: 1024,
+ config: {
+ rateLimit: {
+ max: 10,
+ timeWindow: "1 hour",
+ skipOnError: false,
+ keyGenerator: (request: FastifyRequest) => request.ip,
+ },
+ },
+} satisfies RouteShorthandOptions;
+
+/**
+ * Public. Creates a site for a domain before the visitor has an account. The
+ * response carries the private link key, which is the only credential for the
+ * new dashboard until the site is claimed. Rate limited per IP at the route.
+ */
+export async function createUnclaimedSite(
+ request: FastifyRequest<{ Body: { domain?: unknown } }>,
+ reply: FastifyReply
+) {
+ if (DISABLE_SIGNUP) {
+ return reply.status(403).send({ error: "Signup is disabled" });
+ }
+
+ const parsed = createUnclaimedSiteSchema.safeParse(request.body);
+ if (!parsed.success) {
+ return reply.status(400).send({ error: "Domain is required" });
+ }
+ const { domain } = parsed.data;
+
+ try {
+ const site = await siteConfigurationLifecycle.createUnclaimed({ domain });
+
+ return reply.status(201).send({
+ id: site.id,
+ siteId: site.siteId,
+ domain: site.domain,
+ privateLinkKey: site.privateLinkKey,
+ claimExpiresAt: claimExpiryIso(site.claimExpiresAt),
+ });
+ } catch (error) {
+ if (error instanceof SiteLifecycleError) {
+ return reply.status(error.statusCode).send({ error: error.message });
+ }
+
+ request.log.error({ err: error }, "Error creating unclaimed site");
+ return reply.status(500).send({ error: "Internal server error" });
+ }
+}
diff --git a/server/src/api/sites/getSite.ts b/server/src/api/sites/getSite.ts
index a44b4390f..abc2256a5 100644
--- a/server/src/api/sites/getSite.ts
+++ b/server/src/api/sites/getSite.ts
@@ -1,3 +1,4 @@
+import { claimExpiryIso } from "../../services/sites/claimExpiry.js";
import { eq } from "drizzle-orm";
import { FastifyReply, FastifyRequest } from "fastify";
import { db } from "../../db/postgres/postgres.js";
@@ -36,6 +37,7 @@ export async function getSite(request: FastifyRequest<GetSiteParams>, reply: Fas
updatedAt: site.updatedAt,
createdBy: site.createdBy,
organizationId: site.organizationId,
+ claimExpiresAt: claimExpiryIso(site.claimExpiresAt),
saltUserIds: site.saltUserIds,
public: site.public,
embedEnabled: site.embedEnabled,
diff --git a/server/src/api/sites/index.ts b/server/src/api/sites/index.ts
index 408c678ea..4688b43f6 100644
--- a/server/src/api/sites/index.ts
+++ b/server/src/api/sites/index.ts
@@ -1,5 +1,7 @@
// Site Management
export { addSite } from "./addSite.js";
+export { claimSite } from "./claimSite.js";
+export { createUnclaimedSite } from "./createUnclaimedSite.js";
export { deleteSite } from "./deleteSite.js";
export { getSite } from "./getSite.js";
export { getSiteHasData } from "./getSiteHasData.js";
diff --git a/server/src/api/sites/moveSite.test.ts b/server/src/api/sites/moveSite.test.ts
index 31fe7e9cc..ce40ca68b 100644
--- a/server/src/api/sites/moveSite.test.ts
+++ b/server/src/api/sites/moveSite.test.ts
@@ -24,6 +24,10 @@ vi.mock("../../lib/access.js", async importOriginal => {
vi.mock("../../db/postgres/postgres.js", () => ({
db: {
+ execute: vi.fn(async () => []),
+ async transaction<T>(operation: (tx: unknown) => Promise<T>): Promise<T> {
+ return operation(this);
+ },
query: {
sites: { findFirst: vi.fn(async () => state.site) },
organization: { findFirst: vi.fn(async () => state.targetOrg) },
@@ -53,6 +57,7 @@ vi.mock("../stripe/getSubscription.js", () => ({
vi.mock("./applySiteMove.js", () => ({
applySiteMove: mocks.applySiteMove,
+ invalidateSiteMoveAccess: vi.fn(async () => {}),
}));
import { moveSite } from "./moveSite.js";
@@ -105,7 +110,7 @@ describe("moveSite — target-organization authorization (sole gate)", () => {
expect(reply.statusCode).toBe(200);
expect(reply.body).toEqual({ success: true, organizationId: "org_target" });
- expect(mocks.applySiteMove).toHaveBeenCalledWith(1, "org_source", "org_target");
+ expect(mocks.applySiteMove).toHaveBeenCalledWith(1, "org_source", "org_target", expect.any(Object));
});
it("moves the site when the caller is an owner of the target org", async () => {
@@ -195,7 +200,7 @@ describe("moveSite — target-organization site limit (cloud)", () => {
expect(reply.statusCode).toBe(200);
expect(mocks.getSubscriptionInner).not.toHaveBeenCalled();
- expect(mocks.applySiteMove).toHaveBeenCalledWith(1, "org_source", "org_target");
+ expect(mocks.applySiteMove).toHaveBeenCalledWith(1, "org_source", "org_target", expect.any(Object));
});
});
diff --git a/server/src/api/sites/moveSite.ts b/server/src/api/sites/moveSite.ts
index c0252e79b..5e8b480cd 100644
--- a/server/src/api/sites/moveSite.ts
+++ b/server/src/api/sites/moveSite.ts
@@ -6,7 +6,8 @@ import { organization, sites } from "../../db/postgres/schema.js";
import { getOrgMembership, isOrgAdmin } from "../../lib/access.js";
import { IS_CLOUD } from "../../lib/const.js";
import { getSubscriptionInner } from "../stripe/getSubscription.js";
-import { applySiteMove } from "./applySiteMove.js";
+import { withOrganizationSiteLock } from "../../services/sites/withOrganizationSiteLock.js";
+import { applySiteMove, invalidateSiteMoveAccess } from "./applySiteMove.js";
const moveSiteSchema = z.object({
organizationId: z.string().min(1),
@@ -71,27 +72,30 @@ export async function moveSite(
return reply.status(404).send({ error: "Target organization not found" });
}
- // Enforce the target organization's site limit on cloud.
- if (IS_CLOUD) {
- const subscription = await getSubscriptionInner(targetOrganizationId);
- const siteLimit = subscription?.siteLimit ?? null;
- if (siteLimit !== null) {
- const existingSites = await db
- .select({ siteId: sites.siteId })
- .from(sites)
- .where(eq(sites.organizationId, targetOrganizationId));
- if (existingSites.length >= siteLimit) {
- return reply.status(403).send({
- error: `The target organization has reached its limit of ${siteLimit} website${
+ const capacityError = await withOrganizationSiteLock(targetOrganizationId, async tx => {
+ // Enforce the target organization's site limit on cloud.
+ if (IS_CLOUD) {
+ const subscription = await getSubscriptionInner(targetOrganizationId);
+ const siteLimit = subscription?.siteLimit ?? null;
+ if (siteLimit !== null) {
+ const existingSites = await tx
+ .select({ siteId: sites.siteId })
+ .from(sites)
+ .where(eq(sites.organizationId, targetOrganizationId));
+ if (existingSites.length >= siteLimit) {
+ return `The target organization has reached its limit of ${siteLimit} website${
siteLimit === 1 ? "" : "s"
- }. Please upgrade it to add more.`,
- });
+ }. Please upgrade it to add more.`;
+ }
}
}
- }
- await applySiteMove(siteId, sourceOrganizationId, targetOrganizationId);
+ await applySiteMove(siteId, sourceOrganizationId, targetOrganizationId, tx);
+ return null;
+ });
+ if (capacityError) return reply.status(403).send({ error: capacityError });
+ await invalidateSiteMoveAccess(sourceOrganizationId, targetOrganizationId);
return reply.status(200).send({ success: true, organizationId: targetOrganizationId });
} catch (error) {
request.log.error({ err: error }, "Error moving site");
diff --git a/server/src/api/sites/unclaimedEndpoints.test.ts b/server/src/api/sites/unclaimedEndpoints.test.ts
new file mode 100644
index 000000000..25df8bc0c
--- /dev/null
+++ b/server/src/api/sites/unclaimedEndpoints.test.ts
@@ -0,0 +1,95 @@
+import Fastify, { type FastifyRequest } from "fastify";
+import rateLimit from "@fastify/rate-limit";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const state = vi.hoisted(() => ({
+ disabled: false,
+ userId: "u1" as string | undefined,
+ role: "admin" as string | null,
+}));
+const mocks = vi.hoisted(() => ({ create: vi.fn(), claim: vi.fn(), invalidate: vi.fn() }));
+vi.mock("../../lib/const.js", () => ({
+ get DISABLE_SIGNUP() {
+ return state.disabled;
+ },
+}));
+vi.mock("../../services/sites/siteConfigurationLifecycle.js", () => ({
+ siteConfigurationLifecycle: { createUnclaimed: mocks.create, claim: mocks.claim },
+ SiteLifecycleError: class extends Error {},
+}));
+vi.mock("../../lib/access.js", () => ({
+ getOrgMembership: vi.fn(async () => (state.role ? { role: state.role } : null)),
+ isOrgAdmin: (member: any) => ["owner", "admin"].includes(member?.role),
+}));
+vi.mock("../../lib/auth-utils.js", () => ({ invalidateSitesAccessCache: mocks.invalidate }));
+import { createUnclaimedSite, unclaimedSiteRouteOptions } from "./createUnclaimedSite.js";
+import { claimSite } from "./claimSite.js";
+
+let app: ReturnType<typeof Fastify>;
+beforeEach(async () => {
+ vi.clearAllMocks();
+ state.disabled = false;
+ state.userId = "u1";
+ state.role = "admin";
+ mocks.create.mockResolvedValue({ siteId: 7, privateLinkKey: "aaaaaaaaaaaa", claimExpiresAt: "2026-09-12 12:00:00" });
+ mocks.claim.mockResolvedValue({ siteId: 7, organizationId: "org_1" });
+ app = Fastify();
+ await app.register(rateLimit, { global: false });
+ app.post("/sites/unclaimed", unclaimedSiteRouteOptions, createUnclaimedSite);
+ app.post(
+ "/sites/:siteId/claim",
+ {
+ preHandler: async (request: FastifyRequest) => {
+ if (state.userId) request.user = { id: state.userId };
+ },
+ },
+ claimSite
+ );
+});
+afterEach(async () => {
+ await app.close();
+});
+const claimBody = { privateLinkKey: "aaaaaaaaaaaa", organizationId: "org_1" };
+describe("unclaimed site endpoints", () => {
+ it("blocks public creation when signup is disabled", async () => {
+ state.disabled = true;
+ const response = await app.inject({ method: "POST", url: "/sites/unclaimed", payload: { domain: "acme.dev" } });
+ expect(response.statusCode).toBe(403);
+ expect(mocks.create).not.toHaveBeenCalled();
+ });
+ it("limits one IP to ten creations per hour", async () => {
+ for (let i = 0; i < 10; i++) {
+ const response = await app.inject({ method: "POST", url: "/sites/unclaimed", payload: { domain: "acme.dev" } });
+ expect(response.statusCode).toBe(201);
+ expect(response.json().claimExpiresAt).toBe("2026-09-12T12:00:00.000Z");
+ }
+ const response = await app.inject({ method: "POST", url: "/sites/unclaimed", payload: { domain: "acme.dev" } });
+ expect(response.statusCode).toBe(429);
+ expect(mocks.create).toHaveBeenCalledTimes(10);
+ expect(unclaimedSiteRouteOptions.config.rateLimit.skipOnError).toBe(false);
+ });
+ it.each([null, {}, { domain: 5 }, { domain: " " }, { domain: "a".repeat(254) }])(
+ "rejects invalid creation input %j",
+ async payload => {
+ const response = await app.inject({ method: "POST", url: "/sites/unclaimed", payload: payload ?? undefined });
+ expect(response.statusCode).toBe(400);
+ expect(mocks.create).not.toHaveBeenCalled();
+ }
+ );
+ it("rejects unauthenticated claims", async () => {
+ state.userId = undefined;
+ expect((await app.inject({ method: "POST", url: "/sites/7/claim", payload: claimBody })).statusCode).toBe(401);
+ expect(mocks.claim).not.toHaveBeenCalled();
+ });
+ it.each([null, "member"])("rejects claims without target org admin rights (%s)", async role => {
+ state.role = role;
+ expect((await app.inject({ method: "POST", url: "/sites/7/claim", payload: claimBody })).statusCode).toBe(403);
+ expect(mocks.claim).not.toHaveBeenCalled();
+ });
+ it("lets existing admins claim even when new signup is disabled", async () => {
+ state.disabled = true;
+ expect((await app.inject({ method: "POST", url: "/sites/7/claim", payload: claimBody })).statusCode).toBe(200);
+ expect(mocks.claim).toHaveBeenCalledWith({ siteId: 7, userId: "u1", ...claimBody });
+ expect(mocks.invalidate).toHaveBeenCalledWith("u1");
+ });
+});
diff --git a/server/src/cluster.ts b/server/src/cluster.ts
index 2516351e3..f053cfbf7 100644
--- a/server/src/cluster.ts
+++ b/server/src/cluster.ts
@@ -6,6 +6,7 @@ import { createServiceLogger } from "./lib/logger/logger.js";
import { lifecycleEmailService } from "./services/lifecycleEmails/lifecycleEmailService.js";
import { sessionsService } from "./services/sessions/sessionsService.js";
import { telemetryService } from "./services/telemetryService.js";
+import { unclaimedSiteCleanupService } from "./services/sites/unclaimedSiteCleanupService.js";
import { usageService } from "./services/usageService.js";
import { weeklyReportService } from "./services/weekyReports/weeklyReportService.js";
@@ -45,6 +46,7 @@ if (workerCount === 0) {
// Start cron jobs on the primary process only
telemetryService.startTelemetryCron();
usageService.startUsageCheckCron();
+ unclaimedSiteCleanupService.startCleanupCron();
if (IS_CLOUD && process.env.NODE_ENV !== "development") {
weeklyReportService.startWeeklyReportCron();
lifecycleEmailService.startLifecycleCron();
@@ -115,6 +117,7 @@ if (workerCount === 0) {
// Stop cron jobs
usageService.stopUsageCheckCron();
+ unclaimedSiteCleanupService.stopCleanupCron();
void sessionsService.close();
telemetryService.stopTelemetryCron();
if (IS_CLOUD) {
diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.ts
index d71035e35..68bb2d2a6 100644
--- a/server/src/db/postgres/schema.ts
+++ b/server/src/db/postgres/schema.ts
@@ -107,6 +107,10 @@ export const sites = pgTable(
// Platform fingerprinted from the site's homepage at creation time (e.g. "wordpress",
// "next-js"); used to link the right install guide in lifecycle emails
detectedPlatform: text("detected_platform"),
+ // Set on sites created from the landing-page domain input before the visitor
+ // has an account (organizationId is null). The site is reachable only via its
+ // privateLinkKey until it is claimed; the cleanup cron deletes it after this.
+ claimExpiresAt: timestamp("claim_expires_at", { mode: "string" }),
},
table => [check("sites_type_check", sql`${table.type} IS NULL OR ${table.type} IN ('web', 'mobile')`)]
);
diff --git a/server/src/index.ts b/server/src/index.ts
index f88bd01eb..806f8ca80 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -129,6 +129,8 @@ import {
import {
addSite,
batchImportEvents,
+ claimSite,
+ createUnclaimedSite,
createSiteImport,
deleteSite,
deleteSiteImport,
@@ -178,6 +180,7 @@ import {
} from "./api/user/index.js";
import { validateHttpTimeParams } from "./api/analytics/utils/query-validation.js";
import { initializeClickhouse } from "./db/clickhouse/clickhouse.js";
+import { unclaimedSiteRouteOptions } from "./api/sites/createUnclaimedSite.js";
import { apiRateLimitRedis } from "./db/redis/redis.js";
import { initPostgres } from "./db/postgres/initPostgres.js";
import {
@@ -208,6 +211,7 @@ import { handleIdentify } from "./services/tracker/identifyService.js";
import { trackEvent } from "./services/tracker/trackEvent.js";
import { startSiteBaselineRefresh } from "./services/tracker/botBlocking/siteBaseline.js";
import { usageService } from "./services/usageService.js";
+import { unclaimedSiteCleanupService } from "./services/sites/unclaimedSiteCleanupService.js";
import { weeklyReportService } from "./services/weekyReports/weeklyReportService.js";
import { handleAppSumoWebhook, activateAppSumoLicense } from "./api/as/index.js";
@@ -567,6 +571,10 @@ async function organizationsRoutes(fastify: FastifyInstance) {
fastify.get("/organizations", getMyOrganizations);
fastify.get("/organizations/:organizationId/sites", orgOrgRead, getSitesFromOrg);
fastify.post("/organizations/:organizationId/sites", orgAdminSitesWrite, addSite);
+ // Landing-page domain input: creates an owner-less site reachable only by
+ // its private link key. Public, so cap creations per IP.
+ fastify.post("/sites/unclaimed", unclaimedSiteRouteOptions, createUnclaimedSite);
+ fastify.post("/sites/:siteId/claim", { ...authOnlyScoped("sites", "write"), bodyLimit: 1024 }, claimSite);
fastify.get("/organizations/:organizationId/members", orgOrgRead, listOrganizationMembers);
fastify.post("/organizations/:organizationId/members", authOrgWrite, addUserToOrganization);
fastify.post("/organizations/:organizationId/users", authOrgWrite, createUserInOrganization);
@@ -678,6 +686,7 @@ const start = async () => {
if (!cluster.isWorker) {
telemetryService.startTelemetryCron();
usageService.startUsageCheckCron();
+ unclaimedSiteCleanupService.startCleanupCron();
if (IS_CLOUD && process.env.NODE_ENV !== "development") {
weeklyReportService.startWeeklyReportCron();
lifecycleEmailService.startLifecycleCron();
@@ -727,6 +736,7 @@ const shutdown = async (signal: string) => {
}, 10000); // 10 second timeout
try {
+ unclaimedSiteCleanupService.stopCleanupCron();
// Stop accepting new connections
await server.close();
server.log.info("Server closed");
diff --git a/server/src/lib/auth-utils.test.ts b/server/src/lib/auth-utils.test.ts
index 2d3cbf16f..e5b9a43b1 100644
--- a/server/src/lib/auth-utils.test.ts
+++ b/server/src/lib/auth-utils.test.ts
@@ -142,7 +142,8 @@ CREATE TABLE "sites" (
"api_key" text,
"private_link_key" text,
"tags" jsonb DEFAULT '[]',
- "detected_platform" text
+ "detected_platform" text,
+ "claim_expires_at" timestamp
);
`;
@@ -164,9 +165,7 @@ beforeAll(async () => {
});
beforeEach(async () => {
- await (sql as any).exec(
- `TRUNCATE "member", "member_site_access", "team", "teamMember", "team_site_access", "sites"`
- );
+ await (sql as any).exec(`TRUNCATE "member", "member_site_access", "team", "teamMember", "team_site_access", "sites"`);
// Org with 13 sites:
// 1-11 gated by team "bbc", 12 gated by team "other", 13 not team-gated
@@ -183,10 +182,12 @@ beforeEach(async () => {
{ id: "team_bbc", name: "BBC", organizationId: ORG, createdAt: NOW },
{ id: "team_other", name: "Other", organizationId: ORG, createdAt: NOW },
]);
- await db.insert(teamSiteAccess).values([
- ...Array.from({ length: 11 }, (_, i) => ({ teamId: "team_bbc", siteId: i + 1 })),
- { teamId: "team_other", siteId: 12 },
- ]);
+ await db
+ .insert(teamSiteAccess)
+ .values([
+ ...Array.from({ length: 11 }, (_, i) => ({ teamId: "team_bbc", siteId: i + 1 })),
+ { teamId: "team_other", siteId: 12 },
+ ]);
// Peer: member role, on team BBC
await db.insert(member).values({
@@ -674,3 +675,32 @@ describe("getSitesUserHasAccessTo — organization-owned keys", () => {
});
});
+it("does not expose unclaimed sites through organization membership", async () => {
+ await db.insert(sites).values({
+ id: "unclaimedhex",
+ siteId: 99,
+ name: "Unclaimed",
+ domain: "unclaimed.dev",
+ organizationId: null,
+ privateLinkKey: "aaaaaaaaaaaa",
+ claimExpiresAt: "2100-01-01T00:00:00Z",
+ });
+ expect(await siteIdsFor("user_owner")).not.toContain(99);
+ expect(await siteIdsFor("user_peer")).not.toContain(99);
+ expect(await getOrgMembership("user_owner", null)).toBeNull();
+});
+
+it("refreshes cached session access after another worker claims a site", async () => {
+ invalidateSitesAccessCache("user_owner");
+ await getSitesUserHasAccessTo(reqFor("user_owner"));
+ await getSitesUserHasAccessTo(reqFor("user_owner"), true);
+ await db.insert(sites).values({
+ id: "claimedhex",
+ siteId: 99,
+ name: "Claimed",
+ domain: "claimed.dev",
+ organizationId: ORG,
+ });
+ expect(await getUserHasAccessToSite(reqFor("user_owner"), 99)).toBe(true);
+ expect(await getUserHasAdminAccessToSite(reqFor("user_owner"), 99)).toBe(true);
+});
diff --git a/server/src/lib/auth-utils.ts b/server/src/lib/auth-utils.ts
index 48e38957f..b056d41e8 100644
--- a/server/src/lib/auth-utils.ts
+++ b/server/src/lib/auth-utils.ts
@@ -3,12 +3,7 @@ import { FastifyRequest } from "fastify";
import NodeCache from "node-cache";
import { db } from "../db/postgres/postgres.js";
import { member, sites, user } from "../db/postgres/schema.js";
-import {
- getOrgMembership,
- memberCanAccessSite,
- resolveMemberSiteGrants,
- restrictedMemberSiteIds,
-} from "./access.js";
+import { getOrgMembership, memberCanAccessSite, resolveMemberSiteGrants, restrictedMemberSiteIds } from "./access.js";
import type { RateLimitDecision } from "./apiRateLimit.js";
import { consumeRateLimitForIdentity } from "./apiRateLimitPolicy.js";
import { auth } from "./auth.js";
@@ -219,9 +214,7 @@ export async function getSitesUserHasAccessTo(req: FastifyRequest, adminOnly = f
}
const memberOrgIds = Array.from(memberRowByOrgId.keys());
- const restrictedMembers = Array.from(memberRowByOrgId.values()).filter(
- record => record.hasRestrictedSiteAccess
- );
+ const restrictedMembers = Array.from(memberRowByOrgId.values()).filter(record => record.hasRestrictedSiteAccess);
const restrictedOrgIds = restrictedMembers.map(record => record.organizationId);
// A restricted membership reaches a closed set of sites, so its
@@ -471,10 +464,12 @@ export async function getUserHasAccessToSitePublic(
siteId: string | number,
requiredScope?: ScopeRequirement
) {
- const [userSites, config] = await Promise.all([getSitesUserHasAccessTo(req), siteConfig.getConfig(siteId)]);
+ const [hasDirectAccess, config] = await Promise.all([
+ getUserHasAccessToSite(req, siteId),
+ siteConfig.getConfig(siteId),
+ ]);
// Check if user has direct access to the site
- const hasDirectAccess = userSites.some(site => site.siteId === Number(siteId));
if (hasDirectAccess) {
return true;
}
@@ -487,7 +482,8 @@ export async function getUserHasAccessToSitePublic(
// Check if a valid private key was provided in the header
const privateKey = req.headers["x-private-key"];
if (privateKey && typeof privateKey === "string" && config?.privateLinkKey === privateKey) {
- return true;
+ const fresh = await siteConfig.reload(siteId);
+ return fresh?.privateLinkKey === privateKey;
}
// Bearer-credential fallback. Scopes apply here too — without this check a
@@ -500,14 +496,24 @@ export async function getUserHasAccessToSitePublic(
return false;
}
+async function hasSiteAccess(req: FastifyRequest, siteId: string | number, adminOnly: boolean): Promise<boolean> {
+ const matches = (accessible: { siteId: number }[]) => accessible.some(site => site.siteId === Number(siteId));
+ if (matches(await getSitesUserHasAccessTo(req, adminOnly))) return true;
+
+ // A claim may have committed in another worker while this one still holds
+ // the user's pre-claim site list. Never let a cached miss deny a new grant.
+ const userId = req.user?.id ?? (await getSessionFromReq(req))?.user.id;
+ if (!userId) return false;
+ invalidateSitesAccessCache(userId);
+ return matches(await getSitesUserHasAccessTo(req, adminOnly));
+}
+
export async function getUserHasAccessToSite(req: FastifyRequest, siteId: string | number) {
- const sites = await getSitesUserHasAccessTo(req);
- return sites.some(site => site.siteId === Number(siteId));
+ return hasSiteAccess(req, siteId, false);
}
export async function getUserHasAdminAccessToSite(req: FastifyRequest, siteId: string | number) {
- const sites = await getSitesUserHasAccessTo(req, true);
- return sites.some(site => site.siteId === Number(siteId));
+ return hasSiteAccess(req, siteId, true);
}
export async function getUserIsInOrg(req: FastifyRequest, organizationId: string): Promise<boolean> {
diff --git a/server/src/lib/privateLinkAccess.test.ts b/server/src/lib/privateLinkAccess.test.ts
new file mode 100644
index 000000000..e782dbfec
--- /dev/null
+++ b/server/src/lib/privateLinkAccess.test.ts
@@ -0,0 +1,29 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({ getConfig: vi.fn(), reload: vi.fn() }));
+vi.mock("./siteConfig.js", () => ({ siteConfig: mocks }));
+vi.mock("./auth.js", () => ({ auth: { api: { getSession: vi.fn(async () => null) } } }));
+vi.mock("./apiRateLimitPolicy.js", () => ({ consumeRateLimitForIdentity: vi.fn() }));
+vi.mock("../db/postgres/postgres.js", () => ({ db: {} }));
+import { getUserHasAccessToSitePublic } from "./auth-utils.js";
+
+beforeEach(() => vi.resetAllMocks());
+const request = () => ({ headers: { "x-private-key": "aaaaaaaaaaaa" } }) as any;
+describe("private-link revocation across workers", () => {
+ it("rejects a revoked key even if this worker still caches it", async () => {
+ mocks.getConfig.mockResolvedValue({ siteId: 7, privateLinkKey: "aaaaaaaaaaaa", public: false });
+ mocks.reload.mockResolvedValue({ siteId: 7, privateLinkKey: null, public: false });
+ expect(await getUserHasAccessToSitePublic(request(), 7)).toBe(false);
+ });
+ it("accepts a key that is still present in Postgres", async () => {
+ const config = { siteId: 7, privateLinkKey: "aaaaaaaaaaaa", public: false };
+ mocks.getConfig.mockResolvedValue(config);
+ mocks.reload.mockResolvedValue(config);
+ expect(await getUserHasAccessToSitePublic(request(), 7)).toBe(true);
+ });
+ it("rejects a deleted site while its key is cached", async () => {
+ mocks.getConfig.mockResolvedValue({ siteId: 7, privateLinkKey: "aaaaaaaaaaaa", public: false });
+ mocks.reload.mockResolvedValue(undefined);
+ expect(await getUserHasAccessToSitePublic(request(), 7)).toBe(false);
+ });
+});
diff --git a/server/src/lib/siteConfig.test.ts b/server/src/lib/siteConfig.test.ts
index 006056bc7..75a7dd94c 100644
--- a/server/src/lib/siteConfig.test.ts
+++ b/server/src/lib/siteConfig.test.ts
@@ -15,6 +15,8 @@ type SiteRow = {
excludedHostnames: unknown;
excludedUserAgents: unknown;
privateLinkKey: string | null;
+ claimExpiresAt?: string | null;
+ organizationId: string | null;
sessionReplay: boolean | null;
webVitals: boolean | null;
trackErrors: boolean | null;
@@ -64,6 +66,7 @@ function createSiteRow(overrides: Partial<SiteRow>): SiteRow {
excludedHostnames: [],
excludedUserAgents: [],
privateLinkKey: null,
+ organizationId: "org_1",
sessionReplay: false,
webVitals: false,
trackErrors: false,
@@ -326,3 +329,24 @@ describe("siteConfig.resolveSiteId", () => {
expect(dbMock.queries).toHaveLength(queriesAfterResolve);
});
});
+
+describe("unclaimed site expiry", () => {
+ it("stops serving tracking config when an unclaimed site expires", async () => {
+ dbMock.rows = [createSiteRow({ organizationId: null, claimExpiresAt: "2000-01-01 00:00:00" })];
+ expect(await siteConfig.getConfig(123)).toBeUndefined();
+ });
+ it("refreshes an expired cached config in case another worker claimed the site", async () => {
+ const expiry = new Date(Date.now() + 10_000).toISOString();
+ dbMock.rows = [createSiteRow({ organizationId: null, claimExpiresAt: expiry })];
+ await siteConfig.getConfig(123);
+ const cached = getCache().get("number:123")!;
+ (cached.data as { claimExpiresAt: string }).claimExpiresAt = "2000-01-01T00:00:00Z";
+ dbMock.rows = [createSiteRow({ claimExpiresAt: null })];
+ expect(await siteConfig.getConfig(123)).toMatchObject({ siteId: 123, claimExpiresAt: null });
+ });
+});
+
+it("does not expire an owned site transferred through the system-admin move path", async () => {
+ dbMock.rows = [createSiteRow({ organizationId: "org_1", claimExpiresAt: "2000-01-01 00:00:00" })];
+ expect(await siteConfig.getConfig(123)).toMatchObject({ siteId: 123, claimExpiresAt: null });
+});
diff --git a/server/src/lib/siteConfig.ts b/server/src/lib/siteConfig.ts
index 8b251a7d6..0e9296324 100644
--- a/server/src/lib/siteConfig.ts
+++ b/server/src/lib/siteConfig.ts
@@ -1,6 +1,7 @@
import { eq, type SQL } from "drizzle-orm";
import { db } from "../db/postgres/postgres.js";
import { sites } from "../db/postgres/schema.js";
+import { claimExpiryIso } from "../services/sites/claimExpiry.js";
import { logger } from "./logger/logger.js";
// Site configuration interface
@@ -22,6 +23,7 @@ export interface SiteConfigData {
excludedASNs: string[];
excludedQueryParams: string[];
privateLinkKey?: string | null;
+ claimExpiresAt?: string | null;
sessionReplay: boolean;
webVitals: boolean;
trackErrors: boolean;
@@ -118,6 +120,7 @@ class SiteConfig {
excludedASNs: Array.isArray(site.excludedASNs) ? site.excludedASNs : [],
excludedQueryParams: Array.isArray(site.excludedQueryParams) ? site.excludedQueryParams : [],
privateLinkKey: site.privateLinkKey,
+ claimExpiresAt: site.organizationId === null ? claimExpiryIso(site.claimExpiresAt ?? null) : null,
sessionReplay: site.sessionReplay || false,
webVitals: site.webVitals || false,
trackErrors: site.trackErrors || false,
@@ -187,7 +190,13 @@ class SiteConfig {
if (!siteIdOrId) return undefined;
try {
- return await this.getSiteByAnyId(siteIdOrId);
+ let config = await this.getSiteByAnyId(siteIdOrId);
+ if (config?.claimExpiresAt && Date.parse(config.claimExpiresAt) <= Date.now()) {
+ // A different worker may have claimed it since this cache was filled.
+ config = await this.reload(siteIdOrId);
+ if (config?.claimExpiresAt && Date.parse(config.claimExpiresAt) <= Date.now()) return undefined;
+ }
+ return config;
} catch (error) {
logger.error(error as Error, `Error fetching site configuration for ${siteIdOrId}`);
return undefined;
diff --git a/server/src/services/sites/claimExpiry.ts b/server/src/services/sites/claimExpiry.ts
new file mode 100644
index 000000000..a04857ea4
--- /dev/null
+++ b/server/src/services/sites/claimExpiry.ts
@@ -0,0 +1,6 @@
+// Postgres timestamp (without time zone) strings represent UTC here. Include
+// the offset on the wire so browser/server local time zones cannot shift TTLs.
+export function claimExpiryIso(value: string | null): string | null {
+ if (!value) return null;
+ return new Date(/(?:Z|[+-]\d{2}:?\d{2})$/i.test(value) ? value : `${value}Z`).toISOString();
+}
diff --git a/server/src/services/sites/siteConfigurationLifecycle.ts b/server/src/services/sites/siteConfigurationLifecycle.ts
index fbb9e68cc..ba3760fdf 100644
--- a/server/src/services/sites/siteConfigurationLifecycle.ts
+++ b/server/src/services/sites/siteConfigurationLifecycle.ts
@@ -1,5 +1,5 @@
import { randomBytes } from "node:crypto";
-import { eq } from "drizzle-orm";
+import { and, eq, gt, isNull, lt, sql } from "drizzle-orm";
import { getSubscriptionInner } from "../../api/stripe/getSubscription.js";
import { clickhouse } from "../../db/clickhouse/clickhouse.js";
import { db } from "../../db/postgres/postgres.js";
@@ -9,6 +9,9 @@ import { validateIPPattern } from "../../lib/ipUtils.js";
import { detectPlatform } from "../lifecycleEmails/platformDetect.js";
import { siteConfig, type SiteConfigData } from "../../lib/siteConfig.js";
+import { claimExpiryIso } from "./claimExpiry.js";
+import { withOrganizationSiteLock } from "./withOrganizationSiteLock.js";
+
type SiteRow = typeof sites.$inferSelect;
type SiteInsert = typeof sites.$inferInsert;
type SiteType = "web" | "mobile";
@@ -80,12 +83,15 @@ export type SiteLifecycleErrorCode =
| "site_not_found"
| "invalid_ip_patterns"
| "empty_update"
- | "domain_conflict";
+ | "domain_conflict"
+ | "site_already_claimed"
+ | "invalid_claim_key"
+ | "site_expired";
export class SiteLifecycleError extends Error {
constructor(
readonly code: SiteLifecycleErrorCode,
- readonly statusCode: 400 | 403 | 404 | 409,
+ readonly statusCode: 400 | 403 | 404 | 409 | 410,
message: string,
readonly details?: unknown
) {
@@ -131,6 +137,19 @@ const DIRECT_UPDATE_FIELDS = [
"trackFormInteractions",
] as const satisfies ReadonlyArray<keyof UpdateSiteConfigurationInput>;
+/**
+ * How long a site created from the landing-page domain input survives without
+ * an owner. The cleanup cron deletes unclaimed sites past this age.
+ */
+export const UNCLAIMED_SITE_TTL_MS = 24 * 60 * 60 * 1000;
+
+export type ClaimSiteInput = {
+ siteId: number;
+ privateLinkKey: string;
+ organizationId: string;
+ userId: string;
+};
+
function normalizeSiteType(type: SiteType | null | undefined): SiteType {
return type === "mobile" ? "mobile" : "web";
}
@@ -202,97 +221,214 @@ class SiteConfigurationLifecycle {
validateSiteIdentity(siteType, domain);
validateMobileFeatures(siteType, input);
- if (IS_CLOUD) {
- const subscription = await getSubscriptionInner(input.organizationId);
+ const createdSite = await withOrganizationSiteLock(input.organizationId, async tx => {
+ if (IS_CLOUD) {
+ const subscription = await getSubscriptionInner(input.organizationId);
+
+ if (!subscription) {
+ throw new SiteLifecycleError("organization_not_found", 404, "Organization not found");
+ }
+
+ if (input.sessionReplay && !subscription.includesReplay) {
+ throw new SiteLifecycleError("replay_not_entitled", 403, "Session replay requires a Pro subscription");
+ }
+
+ const requestedStandardFeatures = STANDARD_FEATURES.filter(feature => input[feature]);
+ const hasActiveSubscription = subscription.status === "active" || subscription.status === "trialing";
+ if (requestedStandardFeatures.length > 0 && !hasActiveSubscription) {
+ throw new SiteLifecycleError(
+ "standard_features_not_entitled",
+ 403,
+ `The following features require an active subscription: ${requestedStandardFeatures.join(", ")}`
+ );
+ }
- if (!subscription) {
- throw new SiteLifecycleError("organization_not_found", 404, "Organization not found");
+ const siteLimit = subscription.siteLimit ?? null;
+ if (siteLimit !== null) {
+ const existingSites = await tx
+ .select({ siteId: sites.siteId })
+ .from(sites)
+ .where(eq(sites.organizationId, input.organizationId));
+
+ if (existingSites.length >= siteLimit) {
+ throw new SiteLifecycleError(
+ "site_limit_reached",
+ 403,
+ `You have reached the limit of ${siteLimit} website${siteLimit === 1 ? "" : "s"} for your plan. Please upgrade to add more.`
+ );
+ }
+ }
}
- if (input.sessionReplay && !subscription.includesReplay) {
- throw new SiteLifecycleError("replay_not_entitled", 403, "Session replay requires a Pro subscription");
+ try {
+ const [createdSite] = await tx
+ .insert(sites)
+ .values({
+ id: randomBytes(6).toString("hex"),
+ type: siteType === "web" ? null : siteType,
+ domain,
+ name: input.name,
+ createdBy: input.createdBy,
+ organizationId: input.organizationId,
+ public: input.public ?? false,
+ saltUserIds: input.saltUserIds ?? false,
+ blockBots: input.blockBots ?? true,
+ ...(input.excludedIPs !== undefined && { excludedIPs: input.excludedIPs }),
+ ...(input.excludedCountries !== undefined && { excludedCountries: input.excludedCountries }),
+ ...(input.sessionReplay !== undefined && { sessionReplay: input.sessionReplay }),
+ ...(input.webVitals !== undefined && { webVitals: input.webVitals }),
+ ...(input.trackErrors !== undefined && { trackErrors: input.trackErrors }),
+ ...(input.trackOutbound !== undefined && { trackOutbound: input.trackOutbound }),
+ ...(input.trackUrlParams !== undefined && { trackUrlParams: input.trackUrlParams }),
+ ...(input.trackInitialPageView !== undefined && { trackInitialPageView: input.trackInitialPageView }),
+ ...(input.trackSpaNavigation !== undefined && { trackSpaNavigation: input.trackSpaNavigation }),
+ ...(input.trackIp !== undefined && { trackIp: input.trackIp }),
+ ...(input.trackButtonClicks !== undefined && { trackButtonClicks: input.trackButtonClicks }),
+ ...(input.trackCopy !== undefined && { trackCopy: input.trackCopy }),
+ ...(input.trackFormInteractions !== undefined && { trackFormInteractions: input.trackFormInteractions }),
+ ...(input.tags !== undefined && { tags: input.tags }),
+ })
+ .returning();
+
+ if (!createdSite) {
+ throw new Error("Site insert returned no row");
+ }
+
+ return createdSite;
+ } catch (error) {
+ if (isUniqueConstraintViolation(error)) {
+ throw new SiteLifecycleError("domain_conflict", 409, "Domain already in use");
+ }
+ throw error;
}
+ });
+ if (siteType === "web") this.detectSitePlatform(createdSite);
+ return createdSite;
+ }
+
+ /**
+ * A site with no organization, created from the landing page before the
+ * visitor has an account. It is reachable only through its private link key
+ * and is deleted by the cleanup cron unless claimed within UNCLAIMED_SITE_TTL_MS.
+ */
+ async createUnclaimed(input: { domain: string }): Promise<SiteRow> {
+ const domain = normalizeDomain(input.domain.trim().toLowerCase())
+ .replace(/^www\./, "")
+ .split(/[/?#]/)[0];
+
+ validateSiteIdentity("web", domain);
+
+ const [createdSite] = await db
+ .insert(sites)
+ .values({
+ id: randomBytes(6).toString("hex"),
+ type: null,
+ domain,
+ name: domain,
+ createdBy: null,
+ organizationId: null,
+ privateLinkKey: randomBytes(6).toString("hex"),
+ claimExpiresAt: new Date(Date.now() + UNCLAIMED_SITE_TTL_MS).toISOString(),
+ })
+ .returning();
+
+ if (!createdSite) {
+ throw new Error("Site insert returned no row");
+ }
+
+ return createdSite;
+ }
- const requestedStandardFeatures = STANDARD_FEATURES.filter(feature => input[feature]);
- const hasActiveSubscription = subscription.status === "active" || subscription.status === "trialing";
- if (requestedStandardFeatures.length > 0 && !hasActiveSubscription) {
- throw new SiteLifecycleError(
- "standard_features_not_entitled",
- 403,
- `The following features require an active subscription: ${requestedStandardFeatures.join(", ")}`
- );
+ /**
+ * Re-parent an unclaimed site into an organization. The private link key is
+ * the proof of possession (it is the only way anyone could have reached the
+ * dashboard), and it is cleared on claim so the anonymous URL stops working.
+ */
+ async claim(input: ClaimSiteInput): Promise<SiteRow> {
+ validateSiteId(input.siteId);
+ const claimedSite = await withOrganizationSiteLock(input.organizationId, async tx => {
+ const site = await tx.query.sites.findFirst({ where: eq(sites.siteId, input.siteId) });
+ if (!site) {
+ throw new SiteLifecycleError("site_not_found", 404, "Site not found");
}
- const siteLimit = subscription.siteLimit ?? null;
- if (siteLimit !== null) {
- const existingSites = await db
- .select({ siteId: sites.siteId })
- .from(sites)
- .where(eq(sites.organizationId, input.organizationId));
+ if (site.organizationId !== null || !site.claimExpiresAt) {
+ throw new SiteLifecycleError("site_already_claimed", 409, "This site has already been claimed");
+ }
- if (existingSites.length >= siteLimit) {
- throw new SiteLifecycleError(
- "site_limit_reached",
- 403,
- `You have reached the limit of ${siteLimit} website${siteLimit === 1 ? "" : "s"} for your plan. Please upgrade to add more.`
- );
+ if (!site.privateLinkKey || site.privateLinkKey !== input.privateLinkKey) {
+ throw new SiteLifecycleError("invalid_claim_key", 403, "Invalid claim link for this site");
+ }
+
+ if (new Date(claimExpiryIso(site.claimExpiresAt)!).getTime() <= Date.now()) {
+ throw new SiteLifecycleError("site_expired", 410, "This site expired before it was claimed");
+ }
+
+ if (IS_CLOUD) {
+ const subscription = await getSubscriptionInner(input.organizationId);
+
+ if (!subscription) {
+ throw new SiteLifecycleError("organization_not_found", 404, "Organization not found");
+ }
+
+ const siteLimit = subscription.siteLimit ?? null;
+ if (siteLimit !== null) {
+ const existingSites = await tx
+ .select({ siteId: sites.siteId })
+ .from(sites)
+ .where(eq(sites.organizationId, input.organizationId));
+
+ if (existingSites.length >= siteLimit) {
+ throw new SiteLifecycleError(
+ "site_limit_reached",
+ 403,
+ `You have reached the limit of ${siteLimit} website${siteLimit === 1 ? "" : "s"} for your plan. Please upgrade to add more.`
+ );
+ }
}
}
- }
- try {
- const [createdSite] = await db
- .insert(sites)
- .values({
- id: randomBytes(6).toString("hex"),
- type: siteType === "web" ? null : siteType,
- domain,
- name: input.name,
- createdBy: input.createdBy,
+ const [claimedSite] = await tx
+ .update(sites)
+ .set({
organizationId: input.organizationId,
- public: input.public ?? false,
- saltUserIds: input.saltUserIds ?? false,
- blockBots: input.blockBots ?? true,
- ...(input.excludedIPs !== undefined && { excludedIPs: input.excludedIPs }),
- ...(input.excludedCountries !== undefined && { excludedCountries: input.excludedCountries }),
- ...(input.sessionReplay !== undefined && { sessionReplay: input.sessionReplay }),
- ...(input.webVitals !== undefined && { webVitals: input.webVitals }),
- ...(input.trackErrors !== undefined && { trackErrors: input.trackErrors }),
- ...(input.trackOutbound !== undefined && { trackOutbound: input.trackOutbound }),
- ...(input.trackUrlParams !== undefined && { trackUrlParams: input.trackUrlParams }),
- ...(input.trackInitialPageView !== undefined && { trackInitialPageView: input.trackInitialPageView }),
- ...(input.trackSpaNavigation !== undefined && { trackSpaNavigation: input.trackSpaNavigation }),
- ...(input.trackIp !== undefined && { trackIp: input.trackIp }),
- ...(input.trackButtonClicks !== undefined && { trackButtonClicks: input.trackButtonClicks }),
- ...(input.trackCopy !== undefined && { trackCopy: input.trackCopy }),
- ...(input.trackFormInteractions !== undefined && { trackFormInteractions: input.trackFormInteractions }),
- ...(input.tags !== undefined && { tags: input.tags }),
+ createdBy: input.userId,
+ claimExpiresAt: null,
+ privateLinkKey: null,
+ updatedAt: new Date().toISOString(),
})
+ .where(
+ and(
+ eq(sites.siteId, input.siteId),
+ isNull(sites.organizationId),
+ eq(sites.privateLinkKey, input.privateLinkKey),
+ gt(sites.claimExpiresAt, sql`(clock_timestamp() AT TIME ZONE 'UTC')`)
+ )
+ )
.returning();
- if (!createdSite) {
- throw new Error("Site insert returned no row");
+ if (!claimedSite) {
+ throw new SiteLifecycleError("site_already_claimed", 409, "This site is no longer available to claim");
}
- // Fingerprint the site's platform in the background so the lifecycle
- // install email can link the right guide. Best-effort only.
- if (siteType === "web") {
- void detectPlatform(domain)
- .then(platform =>
- platform
- ? db.update(sites).set({ detectedPlatform: platform.key }).where(eq(sites.siteId, createdSite.siteId))
- : undefined
- )
- .catch(() => {});
- }
+ return claimedSite;
+ });
- return createdSite;
- } catch (error) {
- if (isUniqueConstraintViolation(error)) {
- throw new SiteLifecycleError("domain_conflict", 409, "Domain already in use");
- }
- throw error;
- }
+ siteConfig.invalidate(claimedSite);
+ this.detectSitePlatform(claimedSite);
+ return claimedSite;
+ }
+
+ private detectSitePlatform(site: SiteRow): void {
+ // Inspect only after authenticated ownership has committed. Public
+ // creation must never fetch a caller-supplied domain.
+ void detectPlatform(site.domain)
+ .then(platform =>
+ platform
+ ? db.update(sites).set({ detectedPlatform: platform.key }).where(eq(sites.siteId, site.siteId))
+ : undefined
+ )
+ .catch(() => {});
}
async update(siteId: number, input: UpdateSiteConfigurationInput): Promise<SiteConfigData> {
@@ -379,9 +515,23 @@ class SiteConfigurationLifecycle {
return privateLinkKey;
}
- async delete(siteId: number): Promise<void> {
- const site = await this.findSite(siteId);
+ async deleteExpired(siteId: number, before: string): Promise<boolean> {
+ return db.transaction(async tx => {
+ const [site] = await tx
+ .select()
+ .from(sites)
+ .where(and(eq(sites.siteId, siteId), isNull(sites.organizationId), lt(sites.claimExpiresAt, before)))
+ .for("update");
+ if (!site) return false;
+
+ await this.deleteReplayData(siteId);
+ await tx.delete(sites).where(eq(sites.siteId, siteId));
+ siteConfig.invalidate(site);
+ return true;
+ });
+ }
+ private async deleteReplayData(siteId: number): Promise<void> {
await Promise.all([
clickhouse.command({
query: "DELETE FROM session_replay_events WHERE site_id = {id:UInt32}",
@@ -392,7 +542,11 @@ class SiteConfigurationLifecycle {
query_params: { id: siteId },
}),
]);
+ }
+ async delete(siteId: number): Promise<void> {
+ const site = await this.findSite(siteId);
+ await this.deleteReplayData(siteId);
await db.delete(sites).where(eq(sites.siteId, siteId));
siteConfig.invalidate(site);
}
diff --git a/server/src/services/sites/unclaimedSiteCleanupService.ts b/server/src/services/sites/unclaimedSiteCleanupService.ts
new file mode 100644
index 000000000..936315b15
--- /dev/null
+++ b/server/src/services/sites/unclaimedSiteCleanupService.ts
@@ -0,0 +1,65 @@
+import { and, isNull, lt } from "drizzle-orm";
+import * as cron from "node-cron";
+import { db } from "../../db/postgres/postgres.js";
+import { sites } from "../../db/postgres/schema.js";
+import { createServiceLogger } from "../../lib/logger/logger.js";
+import { siteConfigurationLifecycle } from "./siteConfigurationLifecycle.js";
+
+/**
+ * Deletes sites created from the landing-page domain input that were never
+ * claimed. A site is unclaimed while organizationId is null; claimExpiresAt is
+ * set at creation and cleared on claim, so `organizationId IS NULL AND
+ * claim_expires_at < now()` is exactly the expired set.
+ */
+class UnclaimedSiteCleanupService {
+ private logger = createServiceLogger("unclaimed-site-cleanup");
+ private task: cron.ScheduledTask | null = null;
+
+ public startCleanupCron() {
+ if (this.task) return;
+
+ this.task = cron.schedule(
+ "*/10 * * * *",
+ async () => {
+ try {
+ await this.deleteExpiredSites();
+ } catch (error) {
+ this.logger.error({ err: error }, "Error deleting expired unclaimed sites");
+ }
+ },
+ { timezone: "UTC", noOverlap: true }
+ );
+
+ this.logger.info("Unclaimed site cleanup cron initialized (runs every 10 minutes)");
+ }
+
+ public stopCleanupCron() {
+ this.task?.stop();
+ this.task = null;
+ }
+
+ public async deleteExpiredSites(): Promise<number> {
+ const before = new Date().toISOString();
+ const expired = await db
+ .select({ siteId: sites.siteId, domain: sites.domain })
+ .from(sites)
+ .where(and(isNull(sites.organizationId), lt(sites.claimExpiresAt, before)));
+
+ let deleted = 0;
+ for (const site of expired) {
+ try {
+ if (await siteConfigurationLifecycle.deleteExpired(site.siteId, before)) deleted++;
+ } catch (error) {
+ this.logger.error({ err: error, siteId: site.siteId }, "Failed to delete expired unclaimed site");
+ }
+ }
+
+ if (deleted > 0) {
+ this.logger.info({ deleted }, "Deleted expired unclaimed sites");
+ }
+
+ return deleted;
+ }
+}
+
+export const unclaimedSiteCleanupService = new UnclaimedSiteCleanupService();
diff --git a/server/src/services/sites/unclaimedSites.test.ts b/server/src/services/sites/unclaimedSites.test.ts
new file mode 100644
index 000000000..441a9fdb8
--- /dev/null
+++ b/server/src/services/sites/unclaimedSites.test.ts
@@ -0,0 +1,224 @@
+import { and, eq, isNull } from "drizzle-orm";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+const state = vi.hoisted(() => ({ isCloud: false }));
+const mocks = vi.hoisted(() => ({
+ getSubscriptionInner: vi.fn(),
+ invalidate: vi.fn(),
+ clickhouseCommand: vi.fn(async () => undefined),
+ detectPlatform: vi.fn(async () => null),
+}));
+vi.mock("../../db/postgres/postgres.js", async () => {
+ const { PGlite } = await import("@electric-sql/pglite");
+ const { drizzle } = await import("drizzle-orm/pglite");
+ const schema = await import("../../db/postgres/schema.js");
+ const client = new PGlite();
+ return { db: drizzle(client, { schema }), sql: client };
+});
+vi.mock("../../db/clickhouse/clickhouse.js", () => ({ clickhouse: { command: mocks.clickhouseCommand } }));
+vi.mock("../../lib/siteConfig.js", () => ({ siteConfig: { invalidate: mocks.invalidate } }));
+vi.mock("../../api/stripe/getSubscription.js", () => ({ getSubscriptionInner: mocks.getSubscriptionInner }));
+vi.mock("../lifecycleEmails/platformDetect.js", () => ({ detectPlatform: mocks.detectPlatform }));
+vi.mock("../../lib/const.js", async importOriginal => ({
+ ...(await importOriginal<typeof import("../../lib/const.js")>()),
+ get IS_CLOUD() {
+ return state.isCloud;
+ },
+}));
+
+import { db, sql as client } from "../../db/postgres/postgres.js";
+import { sites } from "../../db/postgres/schema.js";
+import { claimExpiryIso } from "./claimExpiry.js";
+import { siteConfigurationLifecycle as lifecycle, UNCLAIMED_SITE_TTL_MS } from "./siteConfigurationLifecycle.js";
+import { unclaimedSiteCleanupService as cleanup } from "./unclaimedSiteCleanupService.js";
+
+// Test-only DDL in an in-memory database. No application migrations/connections.
+beforeAll(async () => {
+ await (client as any).exec(`
+CREATE TABLE organization (id text PRIMARY KEY);
+INSERT INTO organization VALUES ('org_1'), ('org_2');
+CREATE TABLE sites (
+ "id" text,
+ "site_id" serial PRIMARY KEY,
+ "name" text NOT NULL,
+ "type" text,
+ "domain" text NOT NULL,
+ "created_at" timestamp DEFAULT now(),
+ "updated_at" timestamp DEFAULT now(),
+ "created_by" text,
+ "organization_id" text,
+ "public" boolean DEFAULT false,
+ "embed_enabled" boolean DEFAULT false,
+ "saltUserIds" boolean DEFAULT false,
+ "blockBots" boolean NOT NULL DEFAULT true,
+ "first_party_proxy" boolean DEFAULT false,
+ "excluded_ips" jsonb DEFAULT '[]'::jsonb,
+ "excluded_countries" jsonb DEFAULT '[]'::jsonb,
+ "excluded_paths" jsonb DEFAULT '[]'::jsonb,
+ "excluded_hostnames" jsonb DEFAULT '[]'::jsonb,
+ "excluded_user_agents" jsonb DEFAULT '[]'::jsonb,
+ "excluded_asns" jsonb DEFAULT '[]'::jsonb,
+ "excluded_query_params" jsonb DEFAULT '[]'::jsonb,
+ "sessionReplay" boolean DEFAULT false,
+ "webVitals" boolean DEFAULT false,
+ "trackErrors" boolean DEFAULT false,
+ "trackOutbound" boolean DEFAULT true,
+ "trackUrlParams" boolean DEFAULT true,
+ "trackInitialPageView" boolean DEFAULT true,
+ "trackSpaNavigation" boolean DEFAULT true,
+ "trackIp" boolean DEFAULT false,
+ "trackButtonClicks" boolean DEFAULT false,
+ "trackCopy" boolean DEFAULT false,
+ "trackFormInteractions" boolean DEFAULT false,
+ "api_key" text,
+ "private_link_key" text,
+ "tags" jsonb DEFAULT '[]'::jsonb,
+ "detected_platform" text,
+ "claim_expires_at" timestamp
+);
+`);
+});
+afterAll(async () => {
+ await (client as any).close();
+});
+beforeEach(async () => {
+ vi.clearAllMocks();
+ state.isCloud = false;
+ mocks.getSubscriptionInner.mockResolvedValue({ siteLimit: 1 });
+ await (client as any).exec("TRUNCATE sites RESTART IDENTITY");
+});
+
+async function unclaimed() {
+ return lifecycle.createUnclaimed({ domain: "acme.dev" });
+}
+function claimInput(site: { siteId: number; privateLinkKey: string | null }, organizationId = "org_1") {
+ return { siteId: site.siteId, privateLinkKey: site.privateLinkKey!, organizationId, userId: "user_1" };
+}
+async function readSite(siteId: number) {
+ return db.query.sites.findFirst({ where: eq(sites.siteId, siteId) });
+}
+
+it("creates a private org-less site with a UTC 24-hour expiry and no outbound fetch", async () => {
+ const start = Date.now();
+ const site = await lifecycle.createUnclaimed({ domain: " HTTPS://www.Acme.dev/pricing?x=1 " });
+ expect(site).toMatchObject({
+ domain: "acme.dev",
+ name: "acme.dev",
+ organizationId: null,
+ createdBy: null,
+ public: false,
+ sessionReplay: false,
+ });
+ expect(site.privateLinkKey).toMatch(/^[a-f0-9]{12}$/);
+ expect(Date.parse(claimExpiryIso(site.claimExpiresAt)!)).toBeGreaterThanOrEqual(start + UNCLAIMED_SITE_TTL_MS);
+ expect(mocks.detectPlatform).not.toHaveBeenCalled();
+});
+it("rejects invalid domains without inserting a site", async () => {
+ await expect(lifecycle.createUnclaimed({ domain: "not a domain" })).rejects.toMatchObject({
+ code: "invalid_web_domain",
+ statusCode: 400,
+ });
+ expect(await db.select().from(sites)).toEqual([]);
+});
+it("interprets timezone-less Postgres expiries as UTC", () => {
+ expect(claimExpiryIso("2026-09-12 12:30:00")).toBe("2026-09-12T12:30:00.000Z");
+});
+
+describe("claim", () => {
+ it("moves the site and revokes the anonymous credential", async () => {
+ const site = await unclaimed();
+ await lifecycle.claim(claimInput(site));
+ expect(await readSite(site.siteId)).toMatchObject({
+ organizationId: "org_1",
+ createdBy: "user_1",
+ privateLinkKey: null,
+ claimExpiresAt: null,
+ });
+ expect(mocks.invalidate).toHaveBeenCalledWith(expect.objectContaining({ siteId: site.siteId }));
+ });
+ it("rejects a wrong key and a second claim", async () => {
+ const site = await unclaimed();
+ await expect(lifecycle.claim({ ...claimInput(site), privateLinkKey: "wrong" })).rejects.toMatchObject({
+ statusCode: 403,
+ });
+ await lifecycle.claim(claimInput(site));
+ await expect(lifecycle.claim(claimInput(site, "org_2"))).rejects.toMatchObject({ statusCode: 409 });
+ expect((await readSite(site.siteId))?.organizationId).toBe("org_1");
+ });
+ it("rejects expired sites", async () => {
+ const site = await unclaimed();
+ await db.update(sites).set({ claimExpiresAt: "2000-01-01T00:00:00.000Z" }).where(eq(sites.siteId, site.siteId));
+ await expect(lifecycle.claim(claimInput(site))).rejects.toMatchObject({ statusCode: 410 });
+ });
+ it("allows only one of two concurrent claims to different organizations", async () => {
+ const site = await unclaimed();
+ const results = await Promise.allSettled([
+ lifecycle.claim(claimInput(site)),
+ lifecycle.claim(claimInput(site, "org_2")),
+ ]);
+ expect(results.filter(r => r.status === "fulfilled")).toHaveLength(1);
+ expect(results.filter(r => r.status === "rejected")).toHaveLength(1);
+ });
+ it("does not oversubscribe an organization through concurrent claims", async () => {
+ state.isCloud = true;
+ const first = await unclaimed();
+ const second = await unclaimed();
+ const results = await Promise.allSettled([lifecycle.claim(claimInput(first)), lifecycle.claim(claimInput(second))]);
+ expect(results.filter(r => r.status === "fulfilled")).toHaveLength(1);
+ expect(await db.select().from(sites).where(eq(sites.organizationId, "org_1"))).toHaveLength(1);
+ });
+ it("shares the capacity lock with normal site creation", async () => {
+ state.isCloud = true;
+ const site = await unclaimed();
+ const results = await Promise.allSettled([
+ lifecycle.claim(claimInput(site)),
+ lifecycle.create({ organizationId: "org_1", domain: "other.dev", name: "Other" }),
+ ]);
+ expect(results.filter(r => r.status === "fulfilled")).toHaveLength(1);
+ expect(await db.select().from(sites).where(eq(sites.organizationId, "org_1"))).toHaveLength(1);
+ });
+ it("allows unlimited plans and self-hosted organizations", async () => {
+ state.isCloud = true;
+ mocks.getSubscriptionInner.mockResolvedValue({ siteLimit: null });
+ await lifecycle.claim(claimInput(await unclaimed()));
+ await lifecycle.claim(claimInput(await unclaimed()));
+ expect(await db.select().from(sites).where(eq(sites.organizationId, "org_1"))).toHaveLength(2);
+ });
+});
+
+describe("cleanup", () => {
+ it("deletes only expired unclaimed sites, keeping legacy org-less and claimed sites", async () => {
+ const expired = await unclaimed();
+ const fresh = await unclaimed();
+ const legacy = await unclaimed();
+ const claimed = await unclaimed();
+ await db.update(sites).set({ claimExpiresAt: "2000-01-01T00:00:00Z" }).where(eq(sites.siteId, expired.siteId));
+ await db.update(sites).set({ claimExpiresAt: null }).where(eq(sites.siteId, legacy.siteId));
+ await lifecycle.claim(claimInput(claimed));
+ expect(await cleanup.deleteExpiredSites()).toBe(1);
+ expect(await readSite(expired.siteId)).toBeUndefined();
+ expect(await readSite(fresh.siteId)).toBeDefined();
+ expect(await readSite(legacy.siteId)).toBeDefined();
+ expect(await readSite(claimed.siteId)).toBeDefined();
+ expect(mocks.clickhouseCommand).toHaveBeenCalledTimes(2);
+ });
+ it("rechecks a stale candidate before deletion and side effects", async () => {
+ const site = await unclaimed();
+ await lifecycle.claim(claimInput(site));
+ expect(await lifecycle.deleteExpired(site.siteId, "2100-01-01T00:00:00Z")).toBe(false);
+ expect(await readSite(site.siteId)).toBeDefined();
+ expect(mocks.clickhouseCommand).not.toHaveBeenCalled();
+ });
+ it("keeps the row for retry if replay cleanup fails", async () => {
+ const site = await unclaimed();
+ await db.update(sites).set({ claimExpiresAt: "2000-01-01T00:00:00Z" }).where(eq(sites.siteId, site.siteId));
+ mocks.clickhouseCommand.mockRejectedValueOnce(new Error("ClickHouse unavailable"));
+ expect(await cleanup.deleteExpiredSites()).toBe(0);
+ expect(await readSite(site.siteId)).toBeDefined();
+ expect(await cleanup.deleteExpiredSites()).toBe(1);
+ });
+ it("does nothing when there are no expired sites", async () => {
+ expect(await cleanup.deleteExpiredSites()).toBe(0);
+ expect(mocks.clickhouseCommand).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/src/services/sites/withOrganizationSiteLock.ts b/server/src/services/sites/withOrganizationSiteLock.ts
new file mode 100644
index 000000000..f9a37e4d8
--- /dev/null
+++ b/server/src/services/sites/withOrganizationSiteLock.ts
@@ -0,0 +1,13 @@
+import { sql } from "drizzle-orm";
+import { db } from "../../db/postgres/postgres.js";
+
+export type SiteTransaction = Parameters<Parameters<typeof db.transaction>[0]>[0];
+
+// All paths that add a site to an organization must hold the same lock while
+// checking capacity and writing, including normal creation, claims, and moves.
+export function withOrganizationSiteLock<T>(organizationId: string, operation: (tx: SiteTransaction) => Promise<T>) {
+ return db.transaction(async tx => {
+ await tx.execute(sql`SELECT id FROM organization WHERE id = ${organizationId} FOR UPDATE`);
+ return operation(tx);
+ });
+}