πΈ Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
organizational api keys (#1052)
Goldflagb7a8f86c4144
diff --git a/client/Dockerfile b/client/Dockerfileindex 1eba67dd5..b8b677445 100644--- a/client/Dockerfile+++ b/client/Dockerfile@@ -40,6 +40,17 @@ ENV NEXT_PUBLIC_DEPLOYMENT=${NEXT_PUBLIC_DEPLOYMENT}ENV NEXT_PUBLIC_LITE_DASHBOARD=${NEXT_PUBLIC_LITE_DASHBOARD}WORKDIR /app/client++# npm installs the file:../shared dependency as a relative symlink+# (node_modules/@rybbit/shared -> ../../../shared). Turbopack treats+# /app/client as the project root and won't resolve packages through a symlink+# that escapes it, and Next's standalone output tracing re-homes node_modules+# at runtime. Materialize the package into a real directory instead β same fix+# as the server image (commit 00a52750).+RUN rm -rf node_modules/@rybbit/shared \+ && mkdir -p node_modules/@rybbit/shared \+ && cp -r /app/shared/package.json /app/shared/dist node_modules/@rybbit/shared/+RUN npm run build# Production image, copy all the files and run nextdiff --git a/client/src/api/admin/hooks/useOrgApiKeys.ts b/client/src/api/admin/hooks/useOrgApiKeys.tsnew file mode 100644index 000000000..ed66d57dc--- /dev/null+++ b/client/src/api/admin/hooks/useOrgApiKeys.ts@@ -0,0 +1,60 @@+import { ORG_API_KEY_CONFIG_ID } from "@rybbit/shared";+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { authClient } from "../../../lib/auth";+import { authedFetch } from "../../utils";++// List an organization's API keys (better-auth returns only keys the caller+// may read: org admins/owners)+export const useListOrgApiKeys = (organizationId?: string) => {+ return useQuery({+ queryKey: ["orgApiKeys", organizationId],+ queryFn: async () => {+ const response = await authClient.apiKey.list({ query: { organizationId: organizationId! } });+ if (response.error) {+ throw new Error(response.error.message);+ }+ return response.data;+ },+ enabled: !!organizationId,+ });+};++// Create an organization-owned API key (custom endpoint for plan-based rate+// limits and key-count limits)+export const useCreateOrgApiKey = (organizationId?: string) => {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: async (data: { name: string; expiresIn?: number; permissions?: Record<string, string[]> }) => {+ return authedFetch<{ key: string; id: string }>(`/organizations/${organizationId}/api-keys`, undefined, {+ method: "POST",+ data,+ });+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ["orgApiKeys", organizationId] });+ },+ });+};++// Delete an organization API key. configId routes better-auth to the org key+// configuration, which authorizes via the caller's org role.+export const useDeleteOrgApiKey = (organizationId?: string) => {+ const queryClient = useQueryClient();++ return useMutation({+ mutationFn: async (keyId: string) => {+ const response = await authClient.apiKey.delete({+ keyId,+ configId: ORG_API_KEY_CONFIG_ID,+ });+ if (response.error) {+ throw new Error(response.error.message);+ }+ return response.data;+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ["orgApiKeys", organizationId] });+ },+ });+};diff --git a/client/src/api/admin/hooks/useUserApiKeys.ts b/client/src/api/admin/hooks/useUserApiKeys.tsindex 461cd3f35..2e72aa13d 100644--- a/client/src/api/admin/hooks/useUserApiKeys.ts+++ b/client/src/api/admin/hooks/useUserApiKeys.ts@@ -3,7 +3,7 @@ import { authClient } from "../../../lib/auth";import { authedFetch } from "../../utils";// List all API keys for the current user-export const useListApiKeys = () => {+export const useListApiKeys = (enabled = true) => {return useQuery({queryKey: ["userApiKeys"],queryFn: async () => {@@ -13,6 +13,7 @@ export const useListApiKeys = () => {}return response.data;},+ enabled,});};diff --git a/client/src/app/settings/account/components/ApiKeyManager.tsx b/client/src/app/settings/account/components/ApiKeyManager.tsxindex a418fcd63..3f3841987 100644--- a/client/src/app/settings/account/components/ApiKeyManager.tsx+++ b/client/src/app/settings/account/components/ApiKeyManager.tsx@@ -6,6 +6,7 @@ import Link from "next/link";import { useExtracted } from "next-intl";import { useState } from "react";import { toast } from "@/components/ui/sonner";+import { useCreateOrgApiKey, useDeleteOrgApiKey, useListOrgApiKeys } from "../../../../api/admin/hooks/useOrgApiKeys";import { useCreateApiKey, useDeleteApiKey, useListApiKeys } from "../../../../api/admin/hooks/useUserApiKeys";import {AlertDialog,@@ -60,7 +61,11 @@ function PermissionsBadge({ permissions }: { permissions: Record<string, string[);}-export function ApiKeyManager() {+/**+ * Manages API keys for the current user, or β when `organizationId` is set β+ * organization-owned keys (org-wide access, survive member departures).+ */+export function ApiKeyManager({ organizationId }: { organizationId?: string }) {const t = useExtracted();const [apiKeyName, setApiKeyName] = useState("");const [showApiKeyDialog, setShowApiKeyDialog] = useState(false);@@ -71,15 +76,29 @@ export function ApiKeyManager() {const [pendingDelete, setPendingDelete] = useState<{ id: string; name: string | null } | null>(null);const { data: subscription } = useStripeSubscription();- const { data: apiKeysData, isLoading: isLoadingApiKeys, isError, error, refetch } = useListApiKeys();+ // Both hooks are called unconditionally (rules of hooks); the unused one is+ // disabled via its enabled flag.+ const userKeysQuery = useListApiKeys(!organizationId);+ const orgKeysQuery = useListOrgApiKeys(organizationId);+ const {+ data: apiKeysData,+ isLoading: isLoadingApiKeys,+ isError,+ error,+ refetch,+ } = organizationId ? orgKeysQuery : userKeysQuery;const planName = subscription?.planName || "free";const isFreePlan = planName === "free" || planName.includes("basic");const isPlanGated = IS_CLOUD && isFreePlan;const apiKeys = apiKeysData?.apiKeys;- const createApiKey = useCreateApiKey();- const deleteApiKey = useDeleteApiKey();+ const createUserApiKey = useCreateApiKey();+ const deleteUserApiKey = useDeleteApiKey();+ const createOrgApiKey = useCreateOrgApiKey(organizationId);+ const deleteOrgApiKey = useDeleteOrgApiKey(organizationId);+ const createApiKey = organizationId ? createOrgApiKey : createUserApiKey;+ const deleteApiKey = organizationId ? deleteOrgApiKey : deleteUserApiKey;const handleCreateApiKey = async () => {if (!apiKeyName.trim()) {@@ -134,14 +153,34 @@ export function ApiKeyManager() {<><Card className="p-2"><CardHeader>- <CardTitle className="text-xl">{t("API Keys")}</CardTitle>+ <CardTitle className="text-xl">+ {organizationId ? t("Organization API Keys") : t("Personal API Keys")}+ </CardTitle></CardHeader><CardContent className="space-y-6"><div className="space-y-2"><h4 className="text-sm font-medium">{t("Create API Key")}</h4><p className="text-xs text-neutral-500">- {t("Generate API keys to access analytics endpoints from your applications")}+ {organizationId+ ? t(+ "An organization key is the organization's own credential: it can access all of this organization's sites and keeps working when members leave. Use it for production integrations."+ )+ : t(+ "A personal key acts as you, with exactly your access β for personal scripts and connecting MCP clients."+ )}</p>+ {!organizationId && (+ <p className="text-xs text-neutral-500">+ {t("Building a production integration?")}{" "}+ <Link+ href="/settings/organization"+ className="font-medium text-neutral-900 underline underline-offset-2 hover:text-neutral-700 dark:text-neutral-100 dark:hover:text-neutral-300"+ >+ {t("Use an organization API key instead")}+ </Link>{" "}+ {t("β it keeps working when team members change (admins and owners only).")}+ </p>+ )}{isPlanGated ? (<div className="rounded-lg bg-neutral-50 dark:bg-neutral-900 p-3 border border-neutral-100 dark:border-neutral-800"><p className="text-xs text-neutral-600 dark:text-neutral-400">@@ -204,7 +243,9 @@ export function ApiKeyManager() {</div><div className="space-y-2">- <h4 className="text-sm font-medium">{t("Your API Keys")}</h4>+ <h4 className="text-sm font-medium">+ {organizationId ? t("This organization's API keys") : t("Your personal API keys")}+ </h4>{isLoadingApiKeys ? (<div className="space-y-2" aria-hidden="true"><Skeleton className="h-8 w-full" />diff --git a/client/src/app/settings/organization/page.tsx b/client/src/app/settings/organization/page.tsxindex 81526bee6..8a5405b7c 100644--- a/client/src/app/settings/organization/page.tsx+++ b/client/src/app/settings/organization/page.tsx@@ -10,6 +10,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "../../../components/uiimport { Input } from "../../../components/ui/input";import { useSetPageTitle } from "../../../hooks/useSetPageTitle";import { authClient } from "../../../lib/auth";+import { ApiKeyManager } from "../account/components/ApiKeyManager";import { DeleteOrganizationDialog } from "./components/DeleteOrganizationDialog";import { Invitations } from "./components/Invitations";import { MembersTable } from "./components/MembersTable";@@ -138,6 +139,8 @@ function Organization({/><Invitations organizationId={org.id} isOwner={isOwner} />++ {isAdmin && <ApiKeyManager organizationId={org.id} />}</>);}diff --git a/docs/content/docs/api/getting-started.mdx b/docs/content/docs/api/getting-started.mdxindex 37e19a863..1ace95294 100644--- a/docs/content/docs/api/getting-started.mdx+++ b/docs/content/docs/api/getting-started.mdx@@ -56,13 +56,26 @@ Query parameters expose API keys in server logs and browser history. Use only fo## Generating API Keys-API keys are user-scoped and grant organization-level access:+Rybbit has two kinds of API keys:++- **Organization API keys** (recommended for integrations) β the organization's own credential. They can access every site in the organization and keep working when team members leave. Only organization admins and owners can create and manage them.+- **Personal API keys** β act as you, with exactly your access, including any site restrictions, across every organization you belong to. Best for personal scripts and for connecting MCP clients.++### Organization keys++1. Navigate to **Settings β Organization** in your Rybbit dashboard+2. Scroll to the **Organization API Keys** section (visible to admins and owners)+3. Enter a name for the key and click **Create**+4. Copy the key immediately (it won't be shown again)++### Personal keys1. Navigate to **Settings β Account** in your Rybbit dashboard-2. Scroll to the **API Keys** section-3. Enter a name for your API key-4. Click **Create**-5. Copy the key immediately (it won't be shown again)+2. Scroll to the **Personal API Keys** section+3. Enter a name for the key and click **Create**+4. Copy the key immediately (it won't be shown again)++Both kinds support restricting a key to specific permissions when you create it β leave restrictions off for a full-access key.### Rate Limits (Cloud Only)@@ -76,8 +89,6 @@ API key rate limits depend on your plan:Self-hosted instances have no rate limits.-Keys are tied to your user account and grant access to all sites in your organization(s).----## Common Parametersdiff --git a/server/drizzle/0011_neat_starhawk.sql b/server/drizzle/0011_neat_starhawk.sqlnew file mode 100644index 000000000..8cc98d923--- /dev/null+++ b/server/drizzle/0011_neat_starhawk.sql@@ -0,0 +1 @@+ALTER TABLE "apikey" DROP CONSTRAINT IF EXISTS "apikey_referenceId_user_id_fk";diff --git a/server/drizzle/meta/0011_snapshot.json b/server/drizzle/meta/0011_snapshot.jsonnew file mode 100644index 000000000..ecfa33be3--- /dev/null+++ b/server/drizzle/meta/0011_snapshot.json@@ -0,0 +1,3663 @@+{+ "id": "d0522e1d-0351-47ae-803f-49b09b121a2d",+ "prevId": "8d6bb1b0-9d59-4de0-9dc1-b072e6950ce9",+ "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.agent_regions": {+ "name": "agent_regions",+ "schema": "",+ "columns": {+ "code": {+ "name": "code",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "endpoint_url": {+ "name": "endpoint_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "last_health_check": {+ "name": "last_health_check",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "is_healthy": {+ "name": "is_healthy",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "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.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.notification_channels": {+ "name": "notification_channels",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "config": {+ "name": "config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "monitor_ids": {+ "name": "monitor_ids",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "trigger_events": {+ "name": "trigger_events",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[\"down\",\"recovery\"]'::jsonb"+ },+ "cooldown_minutes": {+ "name": "cooldown_minutes",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 5+ },+ "last_notified_at": {+ "name": "last_notified_at",+ "type": "timestamp",+ "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()"+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "notification_channels_organization_id_organization_id_fk": {+ "name": "notification_channels_organization_id_organization_id_fk",+ "tableFrom": "notification_channels",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "notification_channels_created_by_user_id_fk": {+ "name": "notification_channels_created_by_user_id_fk",+ "tableFrom": "notification_channels",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "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.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.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.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.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+ },+ "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"+ },+ "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"+ }+ },+ "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": {+ "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": {+ "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": {},+ "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.uptime_alert_history": {+ "name": "uptime_alert_history",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "alert_id": {+ "name": "alert_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "triggered_at": {+ "name": "triggered_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ },+ "resolved_at": {+ "name": "resolved_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "alert_data": {+ "name": "alert_data",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "uptime_alert_history_alert_id_uptime_alerts_id_fk": {+ "name": "uptime_alert_history_alert_id_uptime_alerts_id_fk",+ "tableFrom": "uptime_alert_history",+ "tableTo": "uptime_alerts",+ "columnsFrom": [+ "alert_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "uptime_alert_history_monitor_id_uptime_monitors_id_fk": {+ "name": "uptime_alert_history_monitor_id_uptime_monitors_id_fk",+ "tableFrom": "uptime_alert_history",+ "tableTo": "uptime_monitors",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.uptime_alerts": {+ "name": "uptime_alerts",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "alert_type": {+ "name": "alert_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "alert_config": {+ "name": "alert_config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "conditions": {+ "name": "conditions",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "uptime_alerts_monitor_id_uptime_monitors_id_fk": {+ "name": "uptime_alerts_monitor_id_uptime_monitors_id_fk",+ "tableFrom": "uptime_alerts",+ "tableTo": "uptime_monitors",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.uptime_incidents": {+ "name": "uptime_incidents",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "region": {+ "name": "region",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start_time": {+ "name": "start_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "end_time": {+ "name": "end_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'active'"+ },+ "acknowledged_by": {+ "name": "acknowledged_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "acknowledged_at": {+ "name": "acknowledged_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "resolved_by": {+ "name": "resolved_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resolved_at": {+ "name": "resolved_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "last_error_type": {+ "name": "last_error_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "failure_count": {+ "name": "failure_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 1+ },+ "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": {+ "uptime_incidents_organization_id_organization_id_fk": {+ "name": "uptime_incidents_organization_id_organization_id_fk",+ "tableFrom": "uptime_incidents",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "uptime_incidents_monitor_id_uptime_monitors_id_fk": {+ "name": "uptime_incidents_monitor_id_uptime_monitors_id_fk",+ "tableFrom": "uptime_incidents",+ "tableTo": "uptime_monitors",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "uptime_incidents_acknowledged_by_user_id_fk": {+ "name": "uptime_incidents_acknowledged_by_user_id_fk",+ "tableFrom": "uptime_incidents",+ "tableTo": "user",+ "columnsFrom": [+ "acknowledged_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ },+ "uptime_incidents_resolved_by_user_id_fk": {+ "name": "uptime_incidents_resolved_by_user_id_fk",+ "tableFrom": "uptime_incidents",+ "tableTo": "user",+ "columnsFrom": [+ "resolved_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.uptime_monitor_status": {+ "name": "uptime_monitor_status",+ "schema": "",+ "columns": {+ "monitor_id": {+ "name": "monitor_id",+ "type": "integer",+ "primaryKey": true,+ "notNull": true+ },+ "last_checked_at": {+ "name": "last_checked_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "next_check_at": {+ "name": "next_check_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "current_status": {+ "name": "current_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": "'unknown'"+ },+ "consecutive_failures": {+ "name": "consecutive_failures",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "consecutive_successes": {+ "name": "consecutive_successes",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "uptime_percentage_24h": {+ "name": "uptime_percentage_24h",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "uptime_percentage_7d": {+ "name": "uptime_percentage_7d",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "uptime_percentage_30d": {+ "name": "uptime_percentage_30d",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "average_response_time_24h": {+ "name": "average_response_time_24h",+ "type": "real",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false,+ "default": "now()"+ }+ },+ "indexes": {+ "uptime_monitor_status_updated_at_idx": {+ "name": "uptime_monitor_status_updated_at_idx",+ "columns": [+ {+ "expression": "updated_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "uptime_monitor_status_monitor_id_uptime_monitors_id_fk": {+ "name": "uptime_monitor_status_monitor_id_uptime_monitors_id_fk",+ "tableFrom": "uptime_monitor_status",+ "tableTo": "uptime_monitors",+ "columnsFrom": [+ "monitor_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "uptime_monitor_status_current_status_check": {+ "name": "uptime_monitor_status_current_status_check",+ "value": "current_status IN ('up', 'down', 'unknown')"+ },+ "uptime_monitor_status_uptime_24h_check": {+ "name": "uptime_monitor_status_uptime_24h_check",+ "value": "uptime_percentage_24h >= 0 AND uptime_percentage_24h <= 100"+ },+ "uptime_monitor_status_uptime_7d_check": {+ "name": "uptime_monitor_status_uptime_7d_check",+ "value": "uptime_percentage_7d >= 0 AND uptime_percentage_7d <= 100"+ },+ "uptime_monitor_status_uptime_30d_check": {+ "name": "uptime_monitor_status_uptime_30d_check",+ "value": "uptime_percentage_30d >= 0 AND uptime_percentage_30d <= 100"+ }+ },+ "isRLSEnabled": false+ },+ "public.uptime_monitors": {+ "name": "uptime_monitors",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "serial",+ "primaryKey": true,+ "notNull": true+ },+ "organization_id": {+ "name": "organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "monitor_type": {+ "name": "monitor_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "interval_seconds": {+ "name": "interval_seconds",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "http_config": {+ "name": "http_config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "tcp_config": {+ "name": "tcp_config",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },+ "validation_rules": {+ "name": "validation_rules",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "monitoring_type": {+ "name": "monitoring_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": "'local'"+ },+ "selected_regions": {+ "name": "selected_regions",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false,+ "default": "'[\"local\"]'::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()"+ },+ "created_by": {+ "name": "created_by",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "uptime_monitors_organization_id_organization_id_fk": {+ "name": "uptime_monitors_organization_id_organization_id_fk",+ "tableFrom": "uptime_monitors",+ "tableTo": "organization",+ "columnsFrom": [+ "organization_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "uptime_monitors_created_by_user_id_fk": {+ "name": "uptime_monitors_created_by_user_id_fk",+ "tableFrom": "uptime_monitors",+ "tableTo": "user",+ "columnsFrom": [+ "created_by"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "set null",+ "onUpdate": "no action"+ }+ },+ "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 filediff --git a/server/drizzle/meta/_journal.json b/server/drizzle/meta/_journal.jsonindex 63e20296a..7672fdba6 100644--- a/server/drizzle/meta/_journal.json+++ b/server/drizzle/meta/_journal.json@@ -78,6 +78,13 @@"when": 1784070943021,"tag": "0010_tiny_diamondback","breakpoints": true+ },+ {+ "idx": 11,+ "version": "7",+ "when": 1784173607652,+ "tag": "0011_neat_starhawk",+ "breakpoints": true}]}\ No newline at end of filediff --git a/server/src/api/user/createApiKey.test.ts b/server/src/api/user/createApiKey.test.tsindex ca6a6ad1c..00824411f 100644--- a/server/src/api/user/createApiKey.test.ts+++ b/server/src/api/user/createApiKey.test.ts@@ -9,6 +9,13 @@ const mocks = vi.hoisted(() => ({vi.mock("../../lib/auth.js", () => ({ auth: { api: { createApiKey: mocks.createApiKey } } }));vi.mock("../../lib/auth-utils.js", () => ({ getSessionFromReq: mocks.getSessionFromReq }));vi.mock("../stripe/getSubscription.js", () => ({ getSubscriptionInner: vi.fn(async () => null) }));+vi.mock("../../lib/apiKeyLimits.js", () => ({+ apiKeyLimitForPlan: vi.fn(() => 50),+ createApiKeyWithinLimit: vi.fn(async (_ref: string, _limit: number, create: () => Promise<unknown>) => ({+ allowed: true,+ result: await create(),+ })),+}));vi.mock("../../lib/const.js", () => ({IS_CLOUD: false,API_RATE_LIMIT_WINDOW: 60_000,diff --git a/server/src/api/user/createApiKey.ts b/server/src/api/user/createApiKey.tsindex d1a97c8e9..48c807c61 100644--- a/server/src/api/user/createApiKey.ts+++ b/server/src/api/user/createApiKey.ts@@ -1,5 +1,6 @@import { FastifyReply, FastifyRequest } from "fastify";import { z } from "zod";+import { apiKeyLimitForPlan, createApiKeyWithinLimit } from "../../lib/apiKeyLimits.js";import { auth } from "../../lib/auth.js";import { getSessionFromReq } from "../../lib/auth-utils.js";import { apiKeyPermissionsSchema } from "../../lib/scopes.js";@@ -39,6 +40,7 @@ export async function createUserApiKey(}const { name, expiresIn, permissions } = parsed.data;+ let planName: string | null = null;let rateLimitEnabled = false;let rateLimitMax: number | undefined;let rateLimitTimeWindow: number | undefined;@@ -50,7 +52,7 @@ export async function createUserApiKey(}const subscription = await getSubscriptionInner(activeOrgId);- const planName = subscription?.planName || "free";+ planName = subscription?.planName || "free";if (planName === "free" || planName.includes("basic")) {return reply.status(403).send({@@ -66,21 +68,38 @@ export async function createUserApiKey(: STANDARD_API_RATE_LIMIT;}+ const keyLimit = apiKeyLimitForPlan(planName);+try {- const result = await auth.api.createApiKey({- body: {- name,- expiresIn: expiresIn ?? undefined,- rateLimitEnabled,- rateLimitTimeWindow,- rateLimitMax,- userId: session.user.id,- ...(permissions ? { permissions: permissions as Record<string, string[]> } : {}),- },- });+ const outcome = await createApiKeyWithinLimit(session.user.id, keyLimit, () =>+ auth.api.createApiKey({+ body: {+ name,+ expiresIn: expiresIn ?? undefined,+ rateLimitEnabled,+ rateLimitTimeWindow,+ rateLimitMax,+ userId: session.user.id,+ ...(permissions ? { permissions: permissions as Record<string, string[]> } : {}),+ },+ })+ );++ if (!outcome.allowed) {+ return reply.status(403).send({+ error: `You have reached your limit of ${keyLimit} API keys. Delete an unused key or upgrade your plan.`,+ });+ }- return reply.send(result);- } catch (error: any) {- return reply.status(500).send({ error: error.message || "Failed to create API key" });+ return reply.send(outcome.result);+ } catch (error: unknown) {+ // Surface better-auth's own 4xx rejections by message; anything else stays+ // a generic 500 so internal error detail never reaches the client.+ const err = error as { name?: string; statusCode?: unknown; message?: string };+ if (err?.name === "APIError" && typeof err.statusCode === "number" && err.statusCode >= 400 && err.statusCode < 500) {+ return reply.status(err.statusCode).send({ error: err.message || "Failed to create API key" });+ }+ console.error("Error creating API key:", error);+ return reply.status(500).send({ error: "Failed to create API key" });}}diff --git a/server/src/api/user/createOrgApiKey.test.ts b/server/src/api/user/createOrgApiKey.test.tsnew file mode 100644index 000000000..a8a1dab8d--- /dev/null+++ b/server/src/api/user/createOrgApiKey.test.ts@@ -0,0 +1,165 @@+import Fastify, { type FastifyInstance } from "fastify";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ createApiKey: vi.fn(async () => ({ id: "key_1", key: "rb_org_new" })),+ apiKeyLimitForPlan: vi.fn(() => 50),+ createApiKeyWithinLimit: vi.fn(+ async (+ _ref: string,+ _limit: number,+ create: () => Promise<unknown>+ ): Promise<{ allowed: boolean; result?: unknown }> => ({+ allowed: true,+ result: await create(),+ })+ ),+}));++vi.mock("../../lib/auth.js", () => ({ auth: { api: { createApiKey: mocks.createApiKey } } }));+vi.mock("../stripe/getSubscription.js", () => ({ getSubscriptionInner: vi.fn(async () => null) }));+vi.mock("../../lib/apiKeyLimits.js", () => ({+ apiKeyLimitForPlan: mocks.apiKeyLimitForPlan,+ createApiKeyWithinLimit: mocks.createApiKeyWithinLimit,+}));+vi.mock("../../lib/const.js", () => ({+ IS_CLOUD: false,+ API_RATE_LIMIT_WINDOW: 60_000,+ PRO_API_RATE_LIMIT: 100,+ STANDARD_API_RATE_LIMIT: 10,+}));++import { createOrgApiKey } from "./createOrgApiKey.js";++describe("createOrgApiKey", () => {+ let app: FastifyInstance;+ // What the route guard would have attached: a session or user-API-key user.+ let currentUser: { id: string } | null;++ beforeEach(async () => {+ vi.clearAllMocks();+ mocks.createApiKey.mockResolvedValue({ id: "key_1", key: "rb_org_new" });+ mocks.apiKeyLimitForPlan.mockReturnValue(50);+ mocks.createApiKeyWithinLimit.mockImplementation(async (_ref, _limit, create) => ({+ allowed: true,+ result: await create(),+ }));+ currentUser = { id: "user_1" };+ app = Fastify();+ app.addHook("preHandler", async req => {+ if (currentUser) (req as any).user = currentUser;+ });+ app.post("/organizations/:organizationId/api-keys", createOrgApiKey as any);+ await app.ready();+ });++ afterEach(async () => {+ await app.close();+ });++ it("creates an org-owned key: org config, acting user, createdBy metadata", async () => {+ const response = await app.inject({+ method: "POST",+ url: "/organizations/org_1/api-keys",+ payload: { name: "ci-deploys", permissions: { analytics: ["read"] } },+ });++ expect(response.statusCode).toBe(200);+ expect(mocks.createApiKey).toHaveBeenCalledWith({+ body: expect.objectContaining({+ name: "ci-deploys",+ configId: "org",+ organizationId: "org_1",+ userId: "user_1",+ metadata: { createdBy: "user_1" },+ permissions: { analytics: ["read"] },+ }),+ });+ });++ it("rejects creation without a signed-in user (org keys cannot mint keys)", async () => {+ currentUser = null;++ const response = await app.inject({+ method: "POST",+ url: "/organizations/org_1/api-keys",+ payload: { name: "nope" },+ });++ expect(response.statusCode).toBe(401);+ expect(mocks.createApiKey).not.toHaveBeenCalled();+ });++ it("enforces the org's key-count limit through the atomic reservation", async () => {+ mocks.apiKeyLimitForPlan.mockReturnValue(5);+ mocks.createApiKeyWithinLimit.mockResolvedValue({ allowed: false });++ const response = await app.inject({+ method: "POST",+ url: "/organizations/org_1/api-keys",+ payload: { name: "one-too-many" },+ });++ expect(response.statusCode).toBe(403);+ expect(response.json().error).toContain("limit of 5 API keys");+ expect(mocks.createApiKeyWithinLimit).toHaveBeenCalledWith("org_1", 5, expect.any(Function));+ expect(mocks.createApiKey).not.toHaveBeenCalled();+ });++ it("surfaces better-auth 4xx rejections with their status and message", async () => {+ mocks.createApiKey.mockRejectedValue(+ Object.assign(new Error("You are not a member of the organization that owns this API key."), {+ name: "APIError",+ statusCode: 403,+ })+ );++ const response = await app.inject({+ method: "POST",+ url: "/organizations/org_1/api-keys",+ payload: { name: "outsider" },+ });++ expect(response.statusCode).toBe(403);+ expect(response.json().error).toContain("not a member");+ });++ it("never forwards arbitrary error internals to the client", async () => {+ mocks.createApiKey.mockRejectedValue(+ Object.assign(new Error("connect ECONNREFUSED 10.0.0.5:5432 (password=hunter2)"), { statusCode: 500 })+ );++ const response = await app.inject({+ method: "POST",+ url: "/organizations/org_1/api-keys",+ payload: { name: "boom" },+ });++ expect(response.statusCode).toBe(500);+ expect(response.json().error).toBe("Failed to create API key");+ });++ it("does not trust a 4xx statusCode on non-APIError exceptions", async () => {+ mocks.createApiKey.mockRejectedValue(Object.assign(new Error("internal detail"), { statusCode: 402 }));++ const response = await app.inject({+ method: "POST",+ url: "/organizations/org_1/api-keys",+ payload: { name: "boom" },+ });++ expect(response.statusCode).toBe(500);+ expect(response.json().error).toBe("Failed to create API key");+ });++ it("rejects invalid permissions", async () => {+ const response = await app.inject({+ method: "POST",+ url: "/organizations/org_1/api-keys",+ payload: { name: "bad", permissions: { bogus: ["read"] } },+ });++ expect(response.statusCode).toBe(400);+ expect(mocks.createApiKey).not.toHaveBeenCalled();+ });+});diff --git a/server/src/api/user/createOrgApiKey.ts b/server/src/api/user/createOrgApiKey.tsnew file mode 100644index 000000000..ae1c20d3e--- /dev/null+++ b/server/src/api/user/createOrgApiKey.ts@@ -0,0 +1,115 @@+import { FastifyReply, FastifyRequest } from "fastify";+import { z } from "zod";+import { apiKeyLimitForPlan, createApiKeyWithinLimit } from "../../lib/apiKeyLimits.js";+import { auth } from "../../lib/auth.js";+import { ORG_API_KEY_CONFIG_ID } from "../../lib/bearerAuth.js";+import {+ API_RATE_LIMIT_WINDOW,+ IS_CLOUD,+ PRO_API_RATE_LIMIT,+ STANDARD_API_RATE_LIMIT,+} from "../../lib/const.js";+import { apiKeyPermissionsSchema } from "../../lib/scopes.js";+import { getSubscriptionInner } from "../stripe/getSubscription.js";++const createOrgApiKeyBodySchema = z.object({+ name: z.string().trim().min(1, "Name is required"),+ expiresIn: z.number().int().positive().optional(),+ // Scope the key to specific resource:action pairs (see lib/scopes.ts).+ // Omit entirely for a full-access key.+ permissions: apiKeyPermissionsSchema.optional(),+});++/**+ * Creates an organization-owned API key: the key authenticates as the+ * organization itself (org-admin authority over its sites), so it survives+ * member departures. Plan gating, rate limits, and the key-count limit all+ * follow the owning org's subscription β unlike user keys, which follow the+ * creator's active org. The route guard requires org admin/owner; better-auth+ * re-checks via the organization access control's apiKey resource.+ */+export async function createOrgApiKey(+ request: FastifyRequest<{+ Params: { organizationId: string };+ Body: { name: string; expiresIn?: number; permissions?: Record<string, string[]> };+ }>,+ reply: FastifyReply+) {+ const { organizationId } = request.params;++ // Org keys must be minted by a person β better-auth validates that user's+ // org role, and the key records them as createdBy. The guard+ // (requireOrgAdminFromParams, deny-scoped) attaches request.user for every+ // credential it lets through: sessions and unrestricted user API keys. Org+ // keys carry no user and are rejected at the guard, so they can't mint keys.+ const userId = request.user?.id;+ if (!userId) {+ return reply.status(401).send({ error: "Organization API keys must be created by a signed-in user" });+ }++ const parsed = createOrgApiKeyBodySchema.safeParse(request.body);+ if (!parsed.success) {+ return reply.status(400).send({ error: parsed.error.errors[0]?.message ?? "Invalid request body" });+ }+ const { name, expiresIn, permissions } = parsed.data;++ let planName: string | null = null;+ let rateLimitEnabled = false;+ let rateLimitMax: number | undefined;+ let rateLimitTimeWindow: number | undefined;++ if (IS_CLOUD) {+ const subscription = await getSubscriptionInner(organizationId);+ planName = subscription?.planName || "free";++ if (planName === "free" || planName.includes("basic")) {+ return reply.status(403).send({+ error: "API keys require a Standard or Pro plan. Please upgrade to create API keys.",+ });+ }++ rateLimitEnabled = true;+ rateLimitTimeWindow = API_RATE_LIMIT_WINDOW;+ rateLimitMax =+ planName.includes("pro") || planName === "custom" ? PRO_API_RATE_LIMIT : STANDARD_API_RATE_LIMIT;+ }++ const keyLimit = apiKeyLimitForPlan(planName);++ try {+ const outcome = await createApiKeyWithinLimit(organizationId, keyLimit, () =>+ auth.api.createApiKey({+ body: {+ name,+ expiresIn: expiresIn ?? undefined,+ configId: ORG_API_KEY_CONFIG_ID,+ organizationId,+ userId,+ metadata: { createdBy: userId },+ rateLimitEnabled,+ rateLimitTimeWindow,+ rateLimitMax,+ ...(permissions ? { permissions: permissions as Record<string, string[]> } : {}),+ },+ })+ );++ if (!outcome.allowed) {+ return reply.status(403).send({+ error: `This organization has reached its limit of ${keyLimit} API keys. Delete an unused key or upgrade your plan.`,+ });+ }++ return reply.send(outcome.result);+ } catch (error: unknown) {+ // Surface better-auth's own 4xx rejections (membership, permission,+ // validation) by message; anything else stays a generic 500 so internal+ // error detail never reaches the client.+ const err = error as { name?: string; statusCode?: unknown; message?: string };+ if (err?.name === "APIError" && typeof err.statusCode === "number" && err.statusCode >= 400 && err.statusCode < 500) {+ return reply.status(err.statusCode).send({ error: err.message || "Failed to create API key" });+ }+ console.error("Error creating organization API key:", error);+ return reply.status(500).send({ error: "Failed to create API key" });+ }+}diff --git a/server/src/api/user/index.ts b/server/src/api/user/index.tsindex 081436082..94be35394 100644--- a/server/src/api/user/index.ts+++ b/server/src/api/user/index.ts@@ -11,4 +11,5 @@ export { unsubscribeMarketing, oneClickUnsubscribeMarketing } from "./unsubscrib// API Keysexport { createUserApiKey } from "./createApiKey.js";+export { createOrgApiKey } from "./createOrgApiKey.js";diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.tsindex 6a521ec05..5f99bf9c4 100644--- a/server/src/db/postgres/schema.ts+++ b/server/src/db/postgres/schema.ts@@ -293,9 +293,10 @@ export const apiKey = pgTable("apikey", {start: text(),prefix: text(),key: text().notNull(),- referenceId: text()- .notNull()- .references(() => user.id, { onDelete: "cascade" }),+ // A user id (configId NULL/"default") or an organization id (configId+ // "org") β polymorphic, so no FK. Cleanup happens in auth.ts's+ // deleteUser.afterDelete and afterDeleteOrganization hooks.+ referenceId: text().notNull(),refillInterval: integer(),refillAmount: integer(),lastRefillAt: timestamp({ mode: "string" }),diff --git a/server/src/index.ts b/server/src/index.tsindex 5902fa3c8..9d41827a1 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -144,6 +144,7 @@ import {} from "./api/stripe/index.js";import {addUserToOrganization,+ createOrgApiKey,createUserApiKey,createUserInOrganization,getMyOrganizations,@@ -254,6 +255,7 @@ const authOrgWrite = authOnlyScoped("org", "write");// on surfaces with no taxonomy resource (account settings, billing).const adminOnly = { preHandler: [requireAdmin] as any };const authOnlyNoScopedKeys = { preHandler: [requireAuth("deny-scoped")] as any };+const orgAdminNoScopedKeys = { preHandler: [requireOrgAdminFromParams("deny-scoped")] as any };const __filename = fileURLToPath(import.meta.url);const __dirname = dirname(__filename);@@ -506,6 +508,7 @@ async function userRoutes(fastify: FastifyInstance) {fastify.get("/user/unsubscribe-marketing-oneclick", oneClickUnsubscribeMarketing); // Public - for link clicksfastify.post("/user/unsubscribe-marketing-oneclick", oneClickUnsubscribeMarketing); // Public - for List-Unsubscribe headerfastify.post("/user/api-keys", authOnlyNoScopedKeys, createUserApiKey);+ fastify.post("/organizations/:organizationId/api-keys", orgAdminNoScopedKeys, createOrgApiKey);}async function gscRoutes(fastify: FastifyInstance) {@@ -666,5 +669,7 @@ process.on("SIGINT", () => shutdown("SIGINT"));declare module "fastify" {interface FastifyRequest {user?: any; // Or define a more specific user type+ /** Set by the auth guards when the bearer credential is an org-owned API key. */+ apiKeyOrganizationId?: string;}}diff --git a/server/src/lib/apiKeyLimits.test.ts b/server/src/lib/apiKeyLimits.test.tsnew file mode 100644index 000000000..855ba6cab--- /dev/null+++ b/server/src/lib/apiKeyLimits.test.ts@@ -0,0 +1,113 @@+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";++// Real drizzle queries against an in-memory PGlite database (same pattern as+// auth-utils.test.ts) β advisory locks and hashtextextended are plain Postgres.+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();+ const db = drizzle(client, { schema });+ return { db, sql: client };+});++import { db, sql } from "../db/postgres/postgres.js";+import { apiKey } from "../db/postgres/schema.js";+import { countApiKeysForReference, createApiKeyWithinLimit } from "./apiKeyLimits.js";++const DDL = `+CREATE TABLE "apikey" (+ "id" text PRIMARY KEY,+ "name" text,+ "start" text,+ "prefix" text,+ "key" text NOT NULL,+ "referenceId" text NOT NULL,+ "refillInterval" integer,+ "refillAmount" integer,+ "lastRefillAt" timestamp,+ "enabled" boolean NOT NULL DEFAULT true,+ "rateLimitEnabled" boolean NOT NULL DEFAULT false,+ "rateLimitTimeWindow" integer,+ "rateLimitMax" integer,+ "requestCount" integer NOT NULL DEFAULT 0,+ "remaining" integer,+ "lastRequest" timestamp,+ "expiresAt" timestamp,+ "createdAt" timestamp NOT NULL,+ "updatedAt" timestamp NOT NULL,+ "configId" text,+ "permissions" text,+ "metadata" jsonb+);+`;++const NOW = "2026-01-01 00:00:00";+const PAST = "2020-01-01 00:00:00";+const FUTURE = "2099-01-01 00:00:00";++let seq = 0;+function keyRow(referenceId: string, overrides: Partial<typeof apiKey.$inferInsert> = {}) {+ seq += 1;+ return {+ id: `k_${seq}`,+ key: `hash_${seq}`,+ referenceId,+ createdAt: NOW,+ updatedAt: NOW,+ ...overrides,+ };+}++beforeAll(async () => {+ await (sql as any).exec(DDL);+});++beforeEach(async () => {+ await (sql as any).exec(`TRUNCATE "apikey"`);+});++describe("countApiKeysForReference", () => {+ it("counts only enabled, unexpired keys", async () => {+ await db.insert(apiKey).values([+ keyRow("ref_1"),+ keyRow("ref_1", { enabled: false }),+ keyRow("ref_1", { expiresAt: PAST }),+ keyRow("ref_1", { expiresAt: FUTURE }),+ keyRow("ref_other"),+ ]);++ expect(await countApiKeysForReference("ref_1")).toBe(2);+ });+});++describe("createApiKeyWithinLimit", () => {+ it("runs create under the limit and returns its result", async () => {+ await db.insert(apiKey).values([keyRow("ref_1")]);++ // create must not touch `db` here: PGlite is single-connection, so a+ // nested db call would deadlock the wrapping transaction. In production+ // better-auth inserts on its own pool.+ const outcome = await createApiKeyWithinLimit("ref_1", 2, async () => "created");++ expect(outcome).toEqual({ allowed: true, result: "created" });+ });++ it("blocks at the limit without invoking create", async () => {+ await db.insert(apiKey).values([keyRow("ref_1"), keyRow("ref_1")]);+ const create = vi.fn(async () => "nope");++ const outcome = await createApiKeyWithinLimit("ref_1", 2, create);++ expect(outcome).toEqual({ allowed: false });+ expect(create).not.toHaveBeenCalled();+ });++ it("expired and disabled keys don't consume slots", async () => {+ await db.insert(apiKey).values([keyRow("ref_1", { enabled: false }), keyRow("ref_1", { expiresAt: PAST })]);++ const outcome = await createApiKeyWithinLimit("ref_1", 1, async () => "created");++ expect(outcome).toEqual({ allowed: true, result: "created" });+ });+});diff --git a/server/src/lib/apiKeyLimits.ts b/server/src/lib/apiKeyLimits.tsnew file mode 100644index 000000000..2032c5088--- /dev/null+++ b/server/src/lib/apiKeyLimits.ts@@ -0,0 +1,64 @@+import { and, count, eq, gt, isNull, or, sql } from "drizzle-orm";+import { db } from "../db/postgres/postgres.js";+import { apiKey } from "../db/postgres/schema.js";++type DbLike = Pick<typeof db, "select">;+import {+ IS_CLOUD,+ PRO_API_KEY_LIMIT,+ SELF_HOSTED_API_KEY_LIMIT,+ STANDARD_API_KEY_LIMIT,+} from "./const.js";++/**+ * Maximum number of API keys an owner (a user or an organization) may hold.+ * Cloud limits follow the billing org's plan; self-hosted gets a flat cap.+ */+export function apiKeyLimitForPlan(planName: string | null | undefined): number {+ if (!IS_CLOUD) {+ return SELF_HOSTED_API_KEY_LIMIT;+ }+ const plan = planName || "free";+ return plan.includes("pro") || plan === "custom" ? PRO_API_KEY_LIMIT : STANDARD_API_KEY_LIMIT;+}++/**+ * Number of usable keys currently held by a user or organization: expired+ * keys (which linger until better-auth's lazy purge) and disabled keys don't+ * block the cap. User and org ids live in disjoint id spaces, so counting by+ * referenceId alone is exact.+ */+export async function countApiKeysForReference(referenceId: string, executor: DbLike = db): Promise<number> {+ const [row] = await executor+ .select({ value: count() })+ .from(apiKey)+ .where(+ and(+ eq(apiKey.referenceId, referenceId),+ eq(apiKey.enabled, true),+ or(isNull(apiKey.expiresAt), gt(apiKey.expiresAt, new Date().toISOString()))+ )+ );+ return row?.value ?? 0;+}++/**+ * Runs `create` only if the owner still has a free key slot. Check-and-create+ * is serialized per owner with a Postgres transaction advisory lock, so+ * concurrent requests β across server instances β cannot overshoot the limit:+ * the next holder counts only after `create` has committed (better-auth+ * commits on its own connection before this transaction releases the lock).+ */+export async function createApiKeyWithinLimit<T>(+ referenceId: string,+ limit: number,+ create: () => Promise<T>+): Promise<{ allowed: true; result: T } | { allowed: false }> {+ return db.transaction(async tx => {+ await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${referenceId}, 0))`);+ if ((await countApiKeysForReference(referenceId, tx)) >= limit) {+ return { allowed: false as const };+ }+ return { allowed: true as const, result: await create() };+ });+}diff --git a/server/src/lib/auth-middleware.ts b/server/src/lib/auth-middleware.tsindex e0e656a6b..b0f9712d3 100644--- a/server/src/lib/auth-middleware.ts+++ b/server/src/lib/auth-middleware.ts@@ -23,14 +23,15 @@ type AuthMiddleware = (request: FastifyRequest, reply: FastifyReply) => Promise<* legacy/unrestricted credentials always pass; write implies read).* - "deny-scoped": scoped credentials are rejected outright; unrestricted* credentials and sessions pass. For surfaces with no taxonomy resource- * (account settings, billing).+ * (account settings, billing). Organization-owned keys are also rejected+ * here β these surfaces are inherently user-centric.* - undefined: route is scope-exempt; any valid bearer credential passes.*/export type RouteScope = ScopeRequirement | "deny-scoped";const bearerScopeOk = (result: BearerAuthResult, scope?: RouteScope): boolean => {if (!scope) return true;- if (scope === "deny-scoped") return result.statements === null;+ if (scope === "deny-scoped") return result.statements === null && !result.organizationId;return hasScope(result.statements, scope);};@@ -50,9 +51,15 @@ const getOrganizationIdFromParams = (request: FastifyRequest): string | undefinereturn params?.organizationId;};+// Attach the authenticated bearer principal. User keys become request.user+// like a session; org keys have no user (handlers that attribute a creator+// record null) β they set apiKeyOrganizationId instead, which the site-access+// resolver (getSitesUserHasAccessTo) maps to the org's full site set.const attachApiKeyUser = (request: FastifyRequest, apiKeyResult: BearerAuthResult) => {if (apiKeyResult.userId) {request.user = { id: apiKeyResult.userId };+ } else if (apiKeyResult.organizationId) {+ request.apiKeyOrganizationId = apiKeyResult.organizationId;}};diff --git a/server/src/lib/auth-utils.test.ts b/server/src/lib/auth-utils.test.tsindex c0a909159..dada2f2ce 100644--- a/server/src/lib/auth-utils.test.ts+++ b/server/src/lib/auth-utils.test.ts@@ -27,7 +27,14 @@ vi.mock("../db/postgres/postgres.js", async () => {import { db, sql } from "../db/postgres/postgres.js";import { member, memberSiteAccess, sites, team, teamMember, teamSiteAccess } from "../db/postgres/schema.js";import { auth } from "./auth.js";-import { checkApiKey, getSitesUserHasAccessTo, invalidateSitesAccessCache } from "./auth-utils.js";+import {+ checkApiKey,+ getSitesUserHasAccessTo,+ getUserHasAccessToSite,+ getUserHasAdminAccessToSite,+ getUserIdFromRequest,+ invalidateSitesAccessCache,+} from "./auth-utils.js";import { INTERNAL_BEARER_HANDOFF_HEADER, registerBearerHandoff, releaseBearerHandoff } from "./bearerAuth.js";import { filterSitesByMemberAccess } from "./siteAccess.js";@@ -341,3 +348,146 @@ describe("checkApiKey β scope carrying", () => {releaseBearerHandoff(nonce);});});++describe("checkApiKey β organization-owned keys", () => {+ const request = (token = "rb_org_key") => ({ headers: { authorization: `Bearer ${token}` }, query: {} }) as any;++ // A key minted by the "org" configuration: referenceId is an org id.+ const orgKeyVerification = (referenceId: string, permissions: unknown = null) =>+ ({ valid: true, key: { referenceId, permissions, configId: "org" } }) as any;++ beforeEach(async () => {+ vi.mocked(auth.api.verifyApiKey).mockReset();+ vi.mocked(auth.api.getMcpSession as any).mockReset();+ vi.mocked(auth.api.getMcpSession as any).mockResolvedValue(null);+ await db.insert(sites).values([+ { id: "hex_org_a", siteId: 501, name: "org-a-site", domain: "a.example.com", organizationId: "org_a" },+ { id: "hex_org_b", siteId: 502, name: "org-b-site", domain: "b.example.com", organizationId: "org_b" },+ ]);+ });++ it("acts as org admin against its own organization", async () => {+ vi.mocked(auth.api.verifyApiKey).mockResolvedValue(orgKeyVerification("org_a"));++ const result = await checkApiKey(request(), { organizationId: "org_a" });++ expect(result.valid).toBe(true);+ expect(result.role).toBe("admin");+ expect(result.organizationId).toBe("org_a");+ expect(result.userId).toBeUndefined();+ expect(result.statements).toBeNull();+ });++ it("grants access to a site belonging to its organization", async () => {+ vi.mocked(auth.api.verifyApiKey).mockResolvedValue(orgKeyVerification("org_a"));++ const result = await checkApiKey(request(), { siteId: 501 });++ expect(result.valid).toBe(true);+ expect(result.role).toBe("admin");+ });++ it("rejects a different organization", async () => {+ vi.mocked(auth.api.verifyApiKey).mockResolvedValue(orgKeyVerification("org_a"));++ const result = await checkApiKey(request(), { organizationId: "org_b" });++ expect(result.valid).toBe(false);+ expect(result.role).toBeNull();+ });++ it("rejects a site belonging to a different organization", async () => {+ vi.mocked(auth.api.verifyApiKey).mockResolvedValue(orgKeyVerification("org_a"));++ const result = await checkApiKey(request(), { siteId: 502 });++ expect(result.valid).toBe(false);+ });++ it("rejects requests with no org or site context", async () => {+ vi.mocked(auth.api.verifyApiKey).mockResolvedValue(orgKeyVerification("org_a"));++ const result = await checkApiKey(request(), {});++ expect(result.valid).toBe(false);+ });++ it("carries scoped permissions as statements", async () => {+ vi.mocked(auth.api.verifyApiKey).mockResolvedValue(orgKeyVerification("org_a", { analytics: ["read"] }));++ const result = await checkApiKey(request(), { organizationId: "org_a" });++ expect(result.valid).toBe(true);+ expect(result.statements).toEqual({ analytics: ["read"] });+ });++ it("never resolves to a user id", async () => {+ vi.mocked(auth.api.verifyApiKey).mockResolvedValue(orgKeyVerification("org_a"));++ expect(await getUserIdFromRequest(request())).toBeNull();+ });++ it("keys from the default configuration still resolve through user membership", async () => {+ await db.delete(member).where(eq(member.organizationId, "org_a"));+ await db+ .insert(member)+ .values({ id: "m_default", organizationId: "org_a", userId: "user_default", role: "member", createdAt: NOW });+ vi.mocked(auth.api.verifyApiKey).mockResolvedValue({+ valid: true,+ key: { referenceId: "user_default", permissions: null, configId: "default" },+ } as any);++ const result = await checkApiKey(request("rb_user_key"), { organizationId: "org_a" });++ expect(result.valid).toBe(true);+ expect(result.role).toBe("member");+ expect(result.userId).toBe("user_default");+ expect(result.organizationId).toBeUndefined();+ });+});++// Handlers re-check access internally through getSitesUserHasAccessTo (goals,+// funnels, gsc, custom SQL). The guards attach apiKeyOrganizationId for org+// keys; the resolver must map it to the org's full site set or every such+// handler 403s after the guard passed.+describe("getSitesUserHasAccessTo β organization-owned keys", () => {+ const orgKeyRequest = (organizationId: string) =>+ ({ headers: {}, query: {}, apiKeyOrganizationId: organizationId }) as any;++ const ALL_ORG_SITES = Array.from({ length: 13 }, (_, i) => i + 1);++ it("returns every site of the key's organization, ignoring team gating", async () => {+ const result = await getSitesUserHasAccessTo(orgKeyRequest(ORG));+ expect(result.map((s: { siteId: number }) => s.siteId).sort((a: number, b: number) => a - b)).toEqual(+ ALL_ORG_SITES+ );+ });++ it("passes internal re-checks for the org's sites and only those", async () => {+ await db.insert(sites).values({+ id: "hex_foreign",+ siteId: 601,+ name: "foreign-site",+ domain: "foreign.example.com",+ organizationId: "org_foreign",+ });++ expect(await getUserHasAccessToSite(orgKeyRequest(ORG), 1)).toBe(true);+ expect(await getUserHasAccessToSite(orgKeyRequest(ORG), 601)).toBe(false);+ });++ it("passes admin-level re-checks (org keys act as org admin)", async () => {+ expect(await getUserHasAdminAccessToSite(orgKeyRequest(ORG), 1)).toBe(true);+ });++ it("an attached user takes precedence over a stray org marker", async () => {+ const req = { user: { id: "user_peer" }, headers: {}, query: {}, apiKeyOrganizationId: "org_foreign" } as any;+ invalidateSitesAccessCache("user_peer");+ const result = await getSitesUserHasAccessTo(req);+ // user_peer is team-gated: sees BBC sites + non-gated site 13, not org_foreign's.+ expect(result.map((s: { siteId: number }) => s.siteId).sort((a: number, b: number) => a - b)).toEqual([+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13,+ ]);+ });+});+diff --git a/server/src/lib/auth-utils.ts b/server/src/lib/auth-utils.tsindex 7a0da4c66..112702b81 100644--- a/server/src/lib/auth-utils.ts+++ b/server/src/lib/auth-utils.ts@@ -66,7 +66,38 @@ const sitesAccessCache = new NodeCache({useClones: false, // Don't clone objects for better performance with promises});+// All sites of an organization, for org-owned API keys. Cached under an+// "org:"-prefixed key (org and user ids never collide, the prefix is hygiene).+async function getSitesForOrganization(organizationId: string) {+ const cacheKey = `org:${organizationId}`;++ const cached = sitesAccessCache.get<Promise<any[]>>(cacheKey);+ if (cached) {+ return cached;+ }++ const promise = (async () => {+ try {+ return await db.select().from(sites).where(eq(sites.organizationId, organizationId));+ } catch (error) {+ console.error("Error getting sites for organization:", error);+ sitesAccessCache.del(cacheKey);+ return [];+ }+ })();++ sitesAccessCache.set(cacheKey, promise);+ return promise;+}+export async function getSitesUserHasAccessTo(req: FastifyRequest, adminOnly = false) {+ // Organization-owned API key (attached by the auth guards): org-admin+ // authority over exactly its organization's sites, so member/team+ // restrictions and the adminOnly flag don't apply.+ if (!req.user?.id && req.apiKeyOrganizationId) {+ return getSitesForOrganization(req.apiKeyOrganizationId);+ }+const session = req.user?.id ? null : await getSessionFromReq(req);const userId = req.user?.id ?? session?.user.id;@@ -271,18 +302,18 @@ export function invalidateSitesAccessCache(userId: string) {}/**- * Resolve the org membership role for a bearer-authenticated user, scoped to- * either an explicit organization or the organization owning a site.+ * Resolve the organization a request is targeting: an explicit organization+ * param, or the organization owning the site param.*/-async function resolveBearerUserOrgRole(- userId: string,- options: { organizationId?: string; siteId?: string | number }-): Promise<{ valid: boolean; role: string | null; userId?: string }> {- // Determine the organization ID - either directly provided or looked up from site- let organizationId = options.organizationId;+async function resolveTargetOrganizationId(options: {+ organizationId?: string;+ siteId?: string | number;+}): Promise<string | null> {+ if (options.organizationId) {+ return options.organizationId;+ }- if (!organizationId && options.siteId) {- // Get the site's organization+ if (options.siteId) {const siteRecords = await db.select({organizationId: sites.organizationId,@@ -292,10 +323,23 @@ async function resolveBearerUserOrgRole(.limit(1);if (siteRecords.length > 0 && siteRecords[0].organizationId) {- organizationId = siteRecords[0].organizationId;+ return siteRecords[0].organizationId;}}+ return null;+}++/**+ * Resolve the org membership role for a bearer-authenticated user, scoped to+ * either an explicit organization or the organization owning a site.+ */+async function resolveBearerUserOrgRole(+ userId: string,+ options: { organizationId?: string; siteId?: string | number }+): Promise<{ valid: boolean; role: string | null; userId?: string }> {+ const organizationId = await resolveTargetOrganizationId(options);+if (organizationId) {// Check if the bearer credential's user is a member of the organizationconst userMembership = await db@@ -315,6 +359,8 @@ export interface BearerAuthResult {valid: boolean;role: string | null;userId?: string;+ /** Set instead of userId when the credential is an organization-owned key. */+ organizationId?: string;rateLimited?: boolean;/*** Scope statements carried by the credential. null = unrestricted (legacy@@ -347,6 +393,21 @@ export async function checkApiKey(if (identity.status === "rate_limited") {return { valid: false, role: null, rateLimited: true, statements: null };}+ if (identity.status === "valid" && identity.organizationId) {+ // Organization-owned key: valid only against its own organization (or a+ // site belonging to it). It acts with org-admin authority β creation is+ // restricted to org admins/owners, and scopes narrow it further.+ const targetOrganizationId = await resolveTargetOrganizationId(options);+ if (targetOrganizationId && targetOrganizationId === identity.organizationId) {+ return {+ valid: true,+ role: "admin",+ organizationId: identity.organizationId,+ statements: identity.statements,+ };+ }+ return { valid: false, role: null, statements: null };+ }if (identity.status === "valid" && identity.userId) {const membership = await resolveBearerUserOrgRole(identity.userId, options);return { ...membership, statements: identity.statements };diff --git a/server/src/lib/auth.ts b/server/src/lib/auth.tsindex 82ceafdda..f447033f0 100644--- a/server/src/lib/auth.ts+++ b/server/src/lib/auth.ts@@ -1,6 +1,8 @@import { betterAuth } from "better-auth";-import { APIError, createAuthMiddleware } from "better-auth/api";+import { APIError, createAuthMiddleware, getSessionFromCtx } from "better-auth/api";import { admin, captcha, emailOTP, mcp, organization } from "better-auth/plugins";+import { createAccessControl } from "better-auth/plugins/access";+import { adminAc, defaultStatements, memberAc, ownerAc } from "better-auth/plugins/organization/access";import { ALL_SCOPE_STRINGS, OIDC_STANDARD_SCOPES } from "./scopes.js";import dotenv from "dotenv";import { and, asc, eq, inArray } from "drizzle-orm";@@ -11,7 +13,9 @@ import { apiKey } from "@better-auth/api-key"import { db } from "../db/postgres/postgres.js";import * as schema from "../db/postgres/schema.js";import { invitation, member, memberSiteAccess, sites, user } from "../db/postgres/schema.js";+import { apiKeyLimitForPlan, countApiKeysForReference } from "./apiKeyLimits.js";import { invalidateSitesAccessCache } from "./auth-utils.js";+import { ORG_API_KEY_CONFIG_ID } from "./bearerAuth.js";import { API_RATE_LIMIT_WINDOW, DISABLE_SIGNUP, IS_CLOUD, STANDARD_API_RATE_LIMIT } from "./const.js";import {addContactToAudience,@@ -29,6 +33,30 @@ dotenv.config();const authLogger = createServiceLogger("better-auth");+// The organization plugin's default access control, extended with an `apiKey`+// resource. The @better-auth/api-key plugin consults it (via hasPermission)+// for every operation on organization-owned keys: owners and admins manage+// them, members can't see them.+const ORG_API_KEY_ACTIONS = ["create", "read", "update", "delete"] as const;+const orgAccessControl = createAccessControl({+ ...defaultStatements,+ apiKey: [...ORG_API_KEY_ACTIONS],+});+const orgRoles = {+ owner: orgAccessControl.newRole({ ...ownerAc.statements, apiKey: [...ORG_API_KEY_ACTIONS] }),+ admin: orgAccessControl.newRole({ ...adminAc.statements, apiKey: [...ORG_API_KEY_ACTIONS] }),+ member: orgAccessControl.newRole({ ...memberAc.statements }),+};++// Default per-key rate limits; the create endpoints override them per plan.+const apiKeyRateLimit = IS_CLOUD+ ? {+ enabled: true,+ timeWindow: API_RATE_LIMIT_WINDOW,+ maxRequests: STANDARD_API_RATE_LIMIT,+ }+ : { maxRequests: 10000, timeWindow: 86400000 };+const pluginList = [admin(),// OAuth provider for MCP clients (RFC 8414/9728 discovery, dynamic client@@ -51,25 +79,46 @@ const pluginList = [},},}),- apiKey({- ...(IS_CLOUD- ? {- rateLimit: {- enabled: true,- timeWindow: API_RATE_LIMIT_WINDOW,- maxRequests: STANDARD_API_RATE_LIMIT,- },- }- : { rateLimit: { maxRequests: 10000, timeWindow: 86400000 } }),- }),+ apiKey([+ {+ // User-owned keys. Pre-existing rows (NULL configId) resolve here.+ configId: "default",+ rateLimit: apiKeyRateLimit,+ },+ {+ // Organization-owned keys: referenceId is an organization id and the+ // key authenticates as the org itself (bearerAuth.ts branches on this+ // configId). Management is authorized through orgRoles' apiKey resource.+ configId: ORG_API_KEY_CONFIG_ID,+ references: "organization",+ defaultPrefix: "rb_org_",+ // Org keys store { createdBy } so actions stay attributable to the+ // admin who minted the key.+ enableMetadata: true,+ rateLimit: apiKeyRateLimit,+ },+ ]),dash(),organization({allowUserToCreateOrganization: true,creatorRole: "owner",+ ac: orgAccessControl,+ roles: orgRoles,teams: {enabled: true,},organizationHooks: {+ beforeDeleteOrganization: async ({ organization: org }) => {+ // apikey.referenceId has no FK (it holds user OR org ids), so+ // org-owned keys are purged explicitly. Runs BEFORE the deletion and+ // lets failures propagate: a failed purge aborts the deletion instead+ // of leaving live credentials for a dead organization. If the purge+ // succeeds but the deletion then fails, keys are gone while the org+ // survives β the safe direction (admins can mint new ones).+ await db+ .delete(schema.apiKey)+ .where(and(eq(schema.apiKey.referenceId, org.id), eq(schema.apiKey.configId, ORG_API_KEY_CONFIG_ID)));+ },beforeCreateInvitation: async ({ invitation: newInvitation }) => {const invite = newInvitation as typeof newInvitation & {hasRestrictedSiteAccess?: boolean;@@ -263,6 +312,17 @@ export const auth = betterAuth({},deleteUser: {enabled: true,+ // apikey.referenceId no longer has a cascading FK to user.id (it holds+ // user OR org ids), so the user's keys are purged explicitly. Keys of a+ // user removed through other paths are unusable anyway β bearer auth+ // requires a live org membership β this is hygiene, not security.+ afterDelete: async deletedUser => {+ try {+ await db.delete(schema.apiKey).where(eq(schema.apiKey.referenceId, deletedUser.id));+ } catch (error) {+ console.error("Error deleting API keys for removed user:", error);+ }+ },},changeEmail: {enabled: true,@@ -340,6 +400,75 @@ export const auth = betterAuth({},hooks: {before: createAuthMiddleware(async (ctx) => {+ // Gate API key creation on better-auth's own /api-key/create route. This+ // is the only choke point that covers direct client calls β the Fastify+ // endpoints (createUserApiKey / createOrgApiKey) do richer plan checks+ // before calling in server-side (no ctx.request), so they gate there.+ if (ctx.path === "/api-key/create" && ctx.request) {+ const body = (ctx.body ?? {}) as { configId?: string; organizationId?: string };+ const isOrgKey = body.configId === ORG_API_KEY_CONFIG_ID;+ const session = await getSessionFromCtx(ctx);++ // The key's owner: the org for org keys, the session user otherwise.+ const referenceId = isOrgKey ? body.organizationId : session?.user?.id;+ if (!referenceId) return; // the api-key plugin rejects these itself++ // Don't reveal an org's plan tier or key quota to non-members: skip+ // the gate and let the plugin's own membership/permission check+ // produce its canonical rejection.+ if (isOrgKey) {+ const userId = session?.user?.id;+ if (!userId) return;+ const membership = await db+ .select({ id: member.id })+ .from(member)+ .where(and(eq(member.userId, userId), eq(member.organizationId, referenceId)))+ .limit(1);+ if (membership.length === 0) return;++ // createdBy must identify the session user who minted the key β+ // never caller-supplied metadata. The Fastify endpoint sets it+ // server-side; this covers direct /api-key/create calls. In-place+ // mutation is effective: better-auth hands this same body object to+ // the endpoint.+ const orgKeyBody = ctx.body as { metadata?: Record<string, unknown> };+ orgKeyBody.metadata = { ...orgKeyBody.metadata, createdBy: userId };+ }++ let planName: string | null = null;+ if (IS_CLOUD) {+ // Billing org: the owning org for org keys, the active org for user keys.+ const billingOrgId = isOrgKey+ ? body.organizationId+ : ((session?.session as any)?.activeOrganizationId as string | undefined);+ if (!billingOrgId) {+ throw new APIError("BAD_REQUEST", { message: "No active organization" });+ }+ const { getSubscriptionInner } = await import("../api/stripe/getSubscription.js");+ const subscription = await getSubscriptionInner(billingOrgId);+ planName = subscription?.planName || "free";+ if (planName === "free" || planName.includes("basic")) {+ throw new APIError("FORBIDDEN", {+ message: "API keys require a Standard or Pro plan. Please upgrade to create API keys.",+ });+ }+ }++ // Best-effort pre-check: the insert happens inside the plugin after+ // this hook returns, so no lock can span check-and-create here.+ // Concurrent direct calls can overshoot the cap slightly β it's an+ // advisory quota on the caller's own plan, not a security boundary.+ // The Fastify endpoints (the documented path) enforce it atomically+ // via createApiKeyWithinLimit.+ const limit = apiKeyLimitForPlan(planName);+ const existing = await countApiKeysForReference(referenceId);+ if (existing >= limit) {+ throw new APIError("FORBIDDEN", {+ message: `You have reached the limit of ${limit} API keys. Delete an unused key or upgrade your plan.`,+ });+ }+ }+if (IS_CLOUD && ctx.path === "/organization/invite-member") {const body = ctx.body as { organizationId?: string } | undefined;const organizationId = body?.organizationId;diff --git a/server/src/lib/bearerAuth.ts b/server/src/lib/bearerAuth.tsindex 50d9b1515..fb34f6573 100644--- a/server/src/lib/bearerAuth.ts+++ b/server/src/lib/bearerAuth.ts@@ -22,9 +22,12 @@ export function extractBearerToken(authorization: string | string[] | undefined)return authorization.substring(7) || null;}+export { ORG_API_KEY_CONFIG_ID } from "@rybbit/shared";+import { ORG_API_KEY_CONFIG_ID } from "@rybbit/shared";+export interface ApiKeyVerification {valid: boolean;- key?: { referenceId?: string | null; permissions?: unknown } | null;+ key?: { referenceId?: string | null; permissions?: unknown; configId?: string | null } | null;error?: { code?: string } | null;}@@ -43,7 +46,11 @@ export type BearerIdentityStatus = "valid" | "invalid" | "rate_limited" | "verifexport interface BearerIdentity {status: BearerIdentityStatus;+ /** Set when the credential resolves to a person: user API key or OAuth token. */userId?: string;+ /** Set when the credential is an organization-owned API key. Exactly one of+ * userId/organizationId is set on a valid identity. */+ organizationId?: string;/** null = unrestricted (legacy key / full OAuth grant); enforced by callers. */statements: ScopeStatements | null;}@@ -72,11 +79,13 @@ export async function resolveBearerIdentity(token: string, deps: BearerResolverD}if (verification?.valid && verification.key?.referenceId) {- return {- status: "valid",- userId: verification.key.referenceId,- statements: statementsFromApiKeyPermissions(verification.key.permissions),- };+ const statements = statementsFromApiKeyPermissions(verification.key.permissions);+ // referenceId is a user id or an organization id depending on which key+ // configuration minted the key (legacy keys have a NULL configId = user).+ if (verification.key.configId === ORG_API_KEY_CONFIG_ID) {+ return { status: "valid", organizationId: verification.key.referenceId, statements };+ }+ return { status: "valid", userId: verification.key.referenceId, statements };}if (verification?.error?.code === "RATE_LIMITED") {diff --git a/server/src/lib/const.ts b/server/src/lib/const.tsindex 010392bb2..e7f1147ad 100644--- a/server/src/lib/const.ts+++ b/server/src/lib/const.ts@@ -42,6 +42,11 @@ export const API_RATE_LIMIT_WINDOW = 60_000; // 1 minuteexport const STANDARD_API_RATE_LIMIT = 20; // 20 req/minexport const PRO_API_RATE_LIMIT = 200; // 200 req/min+// Maximum number of API keys per owner (a user or an organization)+export const STANDARD_API_KEY_LIMIT = 5;+export const PRO_API_KEY_LIMIT = 20;+export const SELF_HOSTED_API_KEY_LIMIT = 50;+export const APPSUMO_SITE_LIMITS: Record<string, number | null> = {"1": 3,"2": 10,diff --git a/server/src/mcp/auth.ts b/server/src/mcp/auth.tsindex b556c4a36..0353304f5 100644--- a/server/src/mcp/auth.ts+++ b/server/src/mcp/auth.ts@@ -11,7 +11,10 @@ export { extractBearerToken };export type McpAuthenticatorDependencies = BearerResolverDeps;export interface McpAuthContext {- userId: string;+ /** Set for user API keys and OAuth tokens. */+ userId?: string;+ /** Set for organization-owned API keys. Exactly one of the two is set. */+ organizationId?: string;/** null = unrestricted credential (legacy key / full OAuth grant). */scopes: ScopeStatements | null;/** The resolved identity, so the endpoint can register a proxy handoff. */@@ -54,7 +57,7 @@ export function createMcpAuthenticator(dependencies: McpAuthenticatorDependencieconst bearerToken = extractBearerToken(request.headers.authorization);if (!bearerToken) {throw new McpAuthenticationError(- "Unauthorized: send a Rybbit API key as 'Authorization: Bearer <key>' (Settings > Account > API Keys), or connect with an OAuth-capable MCP client.",+ "Unauthorized: send a Rybbit API key as 'Authorization: Bearer <key>' (Settings > Account > Personal API Keys), or connect with an OAuth-capable MCP client.",401);}@@ -62,7 +65,12 @@ export function createMcpAuthenticator(dependencies: McpAuthenticatorDependencieconst identity = await resolveBearerIdentity(bearerToken, dependencies);switch (identity.status) {case "valid":- return { userId: identity.userId!, scopes: identity.statements, identity };+ return {+ userId: identity.userId,+ organizationId: identity.organizationId,+ scopes: identity.statements,+ identity,+ };case "rate_limited":throw new McpAuthenticationError("API key rate limit exceeded", 429);case "verify_error":diff --git a/server/src/mcp/tools/shared.ts b/server/src/mcp/tools/shared.tsindex 101cba466..ae333b9c4 100644--- a/server/src/mcp/tools/shared.ts+++ b/server/src/mcp/tools/shared.ts@@ -66,7 +66,7 @@ export function fail(message: string): ToolResult {}const ERROR_HINTS: Record<number, string> = {- 401: "The API key is missing or invalid. Create one under Settings > Account > API Keys and send it as 'Authorization: Bearer <key>'.",+ 401: "The API key is missing or invalid. Create one under Settings > Account > Personal API Keys and send it as 'Authorization: Bearer <key>'.",403: "The API key's user does not have access to this site or organization, or the tool requires an org admin/owner role for the key's user. Check the site_id with list_sites; its role field shows the key's role per organization. If the message says 'Insufficient scope', the credential was created without the scope this tool needs β use a key or OAuth grant that has it.",429: "Rate limited. Wait before retrying, and prefer fewer, more aggregated queries.",};diff --git a/shared/src/scopes.ts b/shared/src/scopes.tsindex ab269d5ac..1403ad7fc 100644--- a/shared/src/scopes.ts+++ b/shared/src/scopes.ts@@ -2,6 +2,12 @@// Pure data β no runtime dependencies β so both the server (enforcement,// zod validation) and the client (scope picker) can share one source of truth.+// better-auth configId of the organization-owned API key configuration. Keys+// from this config authenticate as the organization itself; keys from any+// other config (including legacy NULL configIds) are user-owned. The server+// (bearerAuth, auth.ts) and the client (org key management) must agree on it.+export const ORG_API_KEY_CONFIG_ID = "org";+export const SCOPE_MATRIX = {analytics: ["read"],sessions: ["read"],