Skip to content

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

Roles and permissions: editor/viewer roles, per-site roles, and transferring a site to someone else (#1275)

Goldflagfd99474ecd96
diff --git a/client/messages/en.json b/client/messages/en.json
index c8fac8b68..0416fe01f 100644
--- a/client/messages/en.json
+++ b/client/messages/en.json
@@ -23,6 +23,7 @@
"+bk3BW": "Subscription failed: {message}",
"+fPt67": "{count, plural, one {# resource} other {# resources}} selected",
"+g7iCc": "Clicked",
+ "+i+ipM": "Owners and admins automatically have access to all sites.",
"+i6kfV": "Select a role",
"+iTxhU": "Annotation updated",
"+kHMr5": "Invite a new member",
@@ -69,6 +70,7 @@
"08hqOd": "Journeys",
"0CPz5V": "Failed to load journey data. Please try again.",
"0E9k6Y": "Connect your Google Search Console account to view search performance data including top keywords and pages.",
+ "0FxPH5": "Raises their role on the selected sites only.",
"0G/U2g": "Only CSV files are accepted",
"0Ikmuq": "You have an active subscription. Please cancel your subscription before deleting your account.",
"0Q1jqR": "Install the React Native package and initialize it in your app entry point",
@@ -144,6 +146,7 @@
"2tOWr2": "Contains",
"34eVnl": "e.g., Sign Up Completion",
"34g6zC": "Edit Traits",
+ "35/z+1": "Full access, including billing and deleting the organization",
"36pzMD": "Site-specific values such as paths may not mean the same thing on every site.",
"39AHJm": "Sign Up",
"39T2UN": "Food & Drink",
@@ -160,6 +163,7 @@
"3kuvZk": "Top {option}",
"3kwz2Z": "No unused multivariate flags are available. Create a new flag for this experiment.",
"3mAri8": "First-party proxy mode enabled",
+ "3mixeG": "Transfer to someone else",
"3mvL2Q": "and",
"3tP/PN": "User trait",
"3vvIQA": "Landing page",
@@ -196,6 +200,7 @@
"4l6vz1": "Copy",
"4nfQk6": "Capture JavaScript errors and exceptions from your site",
"4v7I1t": "Path Exclusions",
+ "4zTRnw": "Read-only access to analytics",
"5/6deG": "There was a problem fetching the funnels. Please try again later.",
"52UMW3": "All Time",
"54Ob9x": "Yes, move site",
@@ -203,6 +208,7 @@
"56nzII": "Week {value}",
"5BuYtq": "{site} isn't collecting data",
"5CbP3g": "Experiment name",
+ "5PmWQ/": "Failed to load the transfer",
"5QYdPU": "Start Time",
"5QiCvx": "Select at least one permission, or turn off restrictions for a full-access key",
"5U2wOH": "Add variant",
@@ -219,13 +225,16 @@
"5yUsUe": "Replay",
"5yu28t": "You are on the Free plan with up to {limit} pageviews per month.",
"5zGub0": "Error Tracking",
+ "62AhmP": "This link is no longer valid",
"62nsdy": "Retry",
"65uDP/": "Traffic from known bots and crawlers will not be tracked",
"66kGA0": "Runtime",
"68djwb": "No teams yet",
"69jzMr": "Domain updated successfully",
+ "6CDWvN": "{sender} is transferring this site to you from {organization}.",
"6DPLaX": "Preset plan",
"6ErXbc": "is null",
+ "6INEHC": "You don't have permission to add sites to this organization",
"6Lp70G": "Move \"{siteName}\" to another organization. Team and restricted member access for this site will be reset.",
"6MkXA0": "Failed to update experiment",
"6NIu/x": "Failed to generate private link",
@@ -238,6 +247,7 @@
"6VzeBI": "No sessions converted to this goal in the selected time period.",
"6WqHWi": "Applies to",
"6Z97iS": "Cannot delete organization",
+ "6Zx+76": "The recipient gets an email and accepts the site into an organization they manage. It moves with all its data, except its Search Console connection.",
"6aOD8o": "Unlimited sites, session replays",
"6bhRx4": "Select a flag",
"6bxWvN": "Password Reset Successful",
@@ -287,6 +297,8 @@
"7ufubd": "Measures interactivity. INP assesses responsiveness by measuring the time from user interaction to the next paint.",
"7x+EYZ": "{count} events/month",
"81yKPX": "Based on your current usage pattern",
+ "82Y7Sa": "Sending...",
+ "82vxP+": "Transfer cancelled",
"83pc9G": "Search emoji",
"87ZCAe": "Entries",
"89T/ze": "Invalid",
@@ -314,6 +326,8 @@
"8vQTcP": "Google Search Console connected successfully",
"8vp0rB": "No journey data found for the selected criteria.",
"8w+u7S": "Path filter",
+ "9+M4PY": "This transfer was sent to {recipientEmail}. Sign in with that address.",
+ "90evMz": "Cancelling...",
"91BT4j": "Manage this member's account and organization access directly.",
"93jr/b": "Goal name",
"93oVTh": "Copied to clipboard",
@@ -346,6 +360,7 @@
"9iSdEj": "{count} session",
"9j3hXO": "To",
"9jjWs7": "Install the SDK below, then launch your app. This page updates on its own once data arrives.",
+ "9nhYZi": "Send transfer",
"9qBH5R": "No feature flags found",
"9tjZ7S": "Failed to create user",
"9uKBh7": "Remote config",
@@ -442,6 +457,7 @@
"DRXWXB": "404",
"DSOKGF": "Experiment created",
"DWxa2O": "+{count} more traits",
+ "DY5wyp": "Role on these sites",
"DZY1mp": "Everything you need to get started as a small business",
"DcNXmv": "Maximum 100 hostname exclusions allowed",
"Dfc9/a": "Remember your password?",
@@ -453,6 +469,7 @@
"DoskyC": "All Teams",
"DrP6Y6": "Display a bar chart of users over the selected time window.",
"DswPK3": "Failed to create team",
+ "Duls6u": "Decline transfer",
"Dxi6lc": "The site owner has not shared any segments on this dashboard.",
"E/3uwL": "Copy key",
"E/9k/a": "The hypothesis is internal context for your team. It does not change assignment or tracking.",
@@ -591,6 +608,7 @@
"I5k4g/": "Use existing",
"I7l2wK": "The domain used for tracking",
"IAEaaA": "Save segment",
+ "IAqayC": "Viewer",
"IBa7Wa": "Please enter a name for the API key",
"ICdFJO": "Run a query",
"ICwzfm": "There was a problem fetching the pages. Please try again later.",
@@ -602,7 +620,9 @@
"IJ3j5z": "Activity Calendar",
"IP4n+n": "Widget Embeds",
"IPKuA0": "Subscription override updated",
+ "IPvPs7": "Send verification email",
"IQ5tZg": "Submitted form",
+ "IVfFNq": "Accept a site transfer",
"IWDW+q": "Delete annotation",
"IWfwim": "Team deleted successfully",
"IX0C9y": "Feature flag changes saved",
@@ -617,6 +637,7 @@
"IuPATc": "Showing assigned visitors. Call rybbit.flag(\"{flagKey}\") where the variant renders to measure visitors actually exposed to it.",
"IvPFG7": "Failed to update system role",
"Ix3wt3": "Learn more about teams",
+ "IxWjRw": "Ask a site admin to enable it.",
"IxrHg4": "Filter {count} items...",
"J+At6e": "Last Submitted",
"J+DDdr": "Edit site settings",
@@ -683,6 +704,7 @@
"KiXNvz": "Run",
"KjXPXZ": "{count} sessions",
"KkOM4O": "Maximum 100 path exclusions allowed",
+ "Ks3Z/P": "Move it into",
"KsWJL5": "Country Exclusions",
"KtC97P": "Exit Pages",
"KzO2sB": "Initial page view tracking enabled",
@@ -694,6 +716,7 @@
"L8DzHm": "Team name is required",
"LAwI3R": "Name cannot be empty",
"LB/Amg": "Your free trial has expired. Subscribe to a plan to continue tracking visits again.",
+ "LB5N0I": "Failed to cancel the transfer",
"LB7mg3": "s",
"LHF3Za": "Existing",
"LICoyV": "Flag description",
@@ -710,6 +733,7 @@
"LlmkZl": "Time to First Byte",
"LovNd5": "Last Copied",
"Lp3DO2": "Title is required",
+ "Ls2RQA": "Decline this transfer?",
"Lu6+QS": "Edit experiment",
"LuNBqj": "Password should be at least 8 characters",
"LvPqO3": "{count} user",
@@ -773,6 +797,7 @@
"NZ9+vv": "Control",
"NaaXKP": "Create your first conversion goal to start tracking important user actions.",
"NdE4Ps": "Browsers",
+ "NdO+zh": "Organization name",
"Njru+i": "Measures server response time. TTFB is the time from request start to when the first byte is received.",
"NlQXI6": "Generating PDF...",
"NuhCPH": "Learn how to track events",
@@ -797,6 +822,7 @@
"OXolHX": "No organization found.",
"OZ7LR+": "URL pattern (optional)",
"OZJsCo": "Funnel cloned successfully",
+ "Oeu69m": "Go to dashboard",
"OfmST8": "Accept Invitation",
"Oh4usQ": "Select metric",
"OhDId7": "Enter your domain and choose a plan. Your site will be ready to install as soon as checkout is done.",
@@ -897,11 +923,13 @@
"Rp+Vr1": "Condition name",
"RpEtgF": "Start your 7-day free trial",
"Rqzsq/": "Add Filter",
+ "Rs1CKV": "Signed in as {email}",
"RsY5rI": "Converted Sessions",
"RumeRz": "Regions",
"Rw7iI7": "Disable",
"RwzAp9": "Event Types",
"RzSw2z": "Button Text (optional)",
+ "S/8fPk": "The site moves there with all its data.",
"S1utKH": "Lon",
"S4u7Gc": "Get your API key",
"S4zxrU": "Count sessions where your app fires a named event.",
@@ -956,10 +984,12 @@
"Tvhne9": "Waiting for the first pageview from {name}",
"TwyMau": "Account",
"TxjoW4": "Page {current} of {total}",
+ "TzPAuM": "{organization} is transferring this site to you.",
"U01dmA": "Edit Team",
"U0AIkl": "Add User Agent",
"U1H5v0": "Need help? Check out our resources:",
"U2stty": "billed annually at ${annualPrice}",
+ "U3LDpY": "Views analytics and builds reports: goals, funnels, dashboards, their own segments and annotations",
"U3UQfB": "A full split should add up to 100 percent unless you intentionally want unassigned traffic.",
"U3dHSt": "Please type {name} to confirm.",
"U5hCuK": "Each condition returns its own payload. The first match wins.",
@@ -982,9 +1012,12 @@
"UQkHdC": "Initialize it once in your app entry point:",
"URL784": "Neutral",
"UVkKe5": "Sending code...",
+ "UXBrwu": "Verify your email to accept this transfer",
+ "UYFBN2": "Failed to decline the transfer",
"Ube5So": "Monthly event limit exceeded:",
"UcHF+A": "Private link generated",
"Udsmo2": "Imported",
+ "UduzuB": "Create an organization",
"Ue9DHy": "Region:",
"UgH9Vn": "Copied Text",
"UgYEE0": "Navigation Day",
@@ -1039,6 +1072,7 @@
"WDs9bj": "Google Search Console",
"WFlQVv": "Tracking Script",
"WNF1J6": "Choose how the embedded dashboard is displayed.",
+ "WW63pm": "Site role: {role}",
"WXyeBJ": "When disabled, the member can access every site in this organization.",
"WYzHAI": "Skip for now",
"WZTXKm": "Trend",
@@ -1065,11 +1099,13 @@
"XHHR08": "Data",
"XHLYdJ": "Goals",
"XLMjkP": "An error occurred during login",
+ "XMLYH4": "You don't manage an organization yet. The site moves into this new one.",
"XNeN37": "Error loading session details. Please try again.",
"XPX/Qj": "Assignment",
"XQ/KBk": "Winner: {variant}",
"XQDKiY": "Copy owner emails",
"XQSLMK": "Path pattern",
+ "XVClQF": "Configures sites (tracking, feature flags, experiments, imports, Search Console), but not members",
"XWcjJb": "No users found",
"XXrCqV": "React Native SDK docs",
"XYTxH5": "Are you sure you want to delete this goal?",
@@ -1140,8 +1176,10 @@
"aWjWtn": "Create Funnel",
"aXtFak": "Google Search Console data has a 2-3 day delay. Try selecting a wider date range.",
"aY/v+a": "e.g., Sign Up",
+ "aZavAr": "Transfer sent to {email}",
"acSKKr": "Member updated successfully",
"acrOoz": "Continue",
+ "aeNk7f": "Verification email sent. Check your inbox.",
"akF0Ly": "Views",
"alA913": "is not",
"as+uxZ": "Upgrade your plan",
@@ -1228,11 +1266,14 @@
"dSrAoR": "Variant keys must be unique",
"dZAp5K": "Only the main dashboard page can be viewed from this embed.",
"dcLGy5": "Display the top 5 countries visiting your site.",
+ "df6Mb3": "Accept transfer",
"dhBlBV": "replays",
"dhMkG9": "Regex Examples:",
"djNL6D": "Read-only",
"djZCU5": "Skipped",
+ "dkFM+G": "The transfer may have expired, been cancelled, or already been accepted.",
"dmW5bt": "Open the private dashboard embed URL in a new tab.",
+ "dnivPL": "Accept {domain}",
"do7jF6": "Add custom properties to this user. Values can be text, numbers, booleans, or JSON.",
"dpse/L": "pages",
"du1laW": "Never",
@@ -1252,6 +1293,7 @@
"eQnbde": "Disconnect Google Search Console?",
"eYX7hS": "Update your email address for account notifications",
"ebEqgQ": "You have an active subscription. Please cancel your subscription before deleting your organization.",
+ "eetmtV": "Their organization role",
"ekXood": "Unlimited",
"ekfOaV": "Go Back",
"enuxmm": "Copy tracking disabled",
@@ -1263,6 +1305,7 @@
"f3ocee": "Exclude traffic from specific countries. Events from these countries will not be tracked in your analytics.",
"f3v0b6": "Web Vitals Collection is Disabled",
"f5efCD": "Pick the outcome",
+ "f7dn8W": "Raises members' role on these sites; never lowers it.",
"f7uwif": "Organize sites into teams to control which members can access them.",
"fB09El": "Paths starting with /blog/",
"fDjNLX": "You're about to import a large file ({size}). This may take several minutes to process. Are you sure you want to continue?",
@@ -1274,6 +1317,7 @@
"fOVatJ": "Embed widget disabled",
"fQsGgo": "Identify User",
"fTWodj": "Organization Name",
+ "fWKwFM": "Editor",
"fWblDI": "Initial Page View",
"fXdkiI": "is",
"fZgP9x": "Remove this member?",
@@ -1339,6 +1383,7 @@
"hLeBOD": "Failed to disable dashboard embed",
"hO42EP": "Daily Events",
"hPFnGJ": "Failed to update embed setting",
+ "hPG7kH": "Pending transfer to {email} Β· expires {date}",
"hPQ9ZV": "not equals",
"hQLBM5": "{count} total",
"hQZhn8": "Impersonate",
@@ -1456,11 +1501,13 @@
"kWMpjI": "Available on",
"kYpf9a": "Search or add value",
"kZki3s": "Earn 50% recurring commission by referring Rybbit.",
+ "kc9gzx": "Couldn't send the email. Try again in a moment.",
"kdqPM0": "You have a custom plan with up to {limit} pageviews per month.",
"kehGIT": "URL parameters tracking enabled",
"kgLyso": "Total Time",
"kil8JO": "Edit Member",
"kk4TVW": "Icon",
+ "knAuaJ": "Couldn't copy the link. Select it and copy it manually.",
"kscC4K": "Move Site",
"ktXibd": "Need more than 20M events? Contact us for a custom plan.",
"kzaYlD": "Screen",
@@ -1484,12 +1531,14 @@
"lXZjmr": "Invite a new member to this organization.",
"lYB+ft": "Last {count, plural, one {# day} other {# days}}",
"lYB8jy": "{count} users",
+ "lbr3Lq": "Copy link",
"lg/l37": "Session %",
"lmjFSA": "Select Google Search Console Property",
"lnIbba": "IP address tracking disabled",
"lnaWo/": "Region",
"lp7ltY": "Loading hostname exclusions...",
"lqNsts": "New Property",
+ "lsmblc": "You can view these settings, but your role can't change them.",
"lu/vDB": "Multiple variants",
"luhCIe": "IP:",
"lxHUeO": "Allow error events sent by the React Native SDK",
@@ -1531,6 +1580,7 @@
"nGQuNF": "Pages per Session",
"nIXcfs": "Couldn't copy to clipboard. Select the key and copy it manually.",
"nIe+Wv": "Create a new user",
+ "nJLq3g": "Failed to send the transfer",
"nJuUfX": "Search by name, slug, domain, or member email...",
"nL6Jl0": "Retention",
"nVYMBG": "Create User",
@@ -1541,6 +1591,7 @@
"nhaiN+": "Add your first website to start tracking analytics",
"ni0MP6": "You are approaching your monthly event limit. Please contact support if you need more capacity.",
"niC6Ub": "Choose a plan",
+ "njW0hf": "{domain} stays with {organization}, and this link stops working.",
"nnuMWB": "Paths containing /blog/ followed by anything",
"noZdV2": "Deleting...",
"npZO3g": "Right-clicked",
@@ -1571,8 +1622,10 @@
"odXlk8": "Log in",
"odrmaG": "Password changed successfully",
"oemoXC": "You don't have permission to view subscription settings.",
+ "oetC4L": "Cancel transfer",
"ogKEiU": "Outbound Links",
"oiqC46": "Good FCP scores are 1.8 seconds or faster.",
+ "oj0aXj": "Signing out...",
"olRt2f": "Filter by tags...",
"olraZu": "Browser:",
"onG0m+": "This action cannot be undone. This will permanently delete the organization and remove all associated data.",
@@ -1610,6 +1663,7 @@
"puODkp": "City:",
"puhcpn": "Funnels",
"pvJm0l": "Test API endpoints and view code examples in multiple languages.",
+ "pvtgR2": "Decline",
"q0NdNV": "Show top countries",
"q2ZLFN": "Feature flag deleted",
"q4S4cE": "Console log",
@@ -1652,6 +1706,7 @@
"rDEYPT": "Select the organization to remove {email} from. They will lose access to all resources in that organization.",
"rHJwM0": "Edit feature flag {key}",
"rIc2Hm": "Update Funnel",
+ "rNoUmU": "Manages members, sites and settings, but not billing",
"rOpS8J": "Rybbit v{latest} is available (you're on v{current})",
"rRjjyk": "Consider upgrading to avoid interruptions.",
"rSgoeV": "Use * for single segment wildcard, ** for multi-segment wildcard",
@@ -1734,10 +1789,12 @@
"uDXLhQ": "No rows returned",
"uHJ/7A": "Install the SDK package:",
"uHnMYi": "New segment",
+ "uL30u3": "Your role can't delete sites",
"uMhpKe": "Color",
"uPDgth": "Hostname",
"uWRAQk": "Choose your plan",
"uWWCBy": "First-Party Proxy",
+ "uXnWVV": "{count} sites Β· {role}",
"uYI322": "Event limit",
"ucusZJ": "Search timezones",
"ueH42Q": "Get started with Rybbit",
@@ -1756,12 +1813,14 @@
"uuJSCu": "No goals found",
"uxcVP6": "Enter value...",
"uy2A1H": "No error events found",
+ "uzMCu5": "Sign in with the email address the transfer was sent to.",
"v+BwPW": "Add to Organization",
"v1UL8D": "Auto Capture",
"v4/yBh": "{application} is requesting access to your Rybbit account.",
"v5+mtG": "No sites found",
"v5ykbS": "Are you absolutely sure?",
"v7Bl2J": "Creating account...",
+ "vAYj83": "Role on the team's sites",
"vCL+NV": "Please select at least one site or disable site restrictions",
"vCqX8Z": "Embed widget enabled",
"vDpLV2": "Changed {type}input",
@@ -1787,6 +1846,7 @@
"vx0nkZ": "Privacy Policy",
"vyB/q1": "Remove this user from this organization without deleting their account.",
"w2drfr": "Your 14-day free trial has expired. Subscribe to continue tracking visits again.",
+ "w8Cipb": "We'll send a link to {email}. Open it, then come back to this page.",
"wBSk/Y": "Bounce",
"wC1tEM": "Failed to connect property",
"wDjYR2": "This member has access to sites granted through their teams ({teams}), plus any site not assigned to a team.",
@@ -1848,6 +1908,7 @@
"xrcdXO": "Manage your personal account settings",
"xrk6zg": "Updated",
"xvsXfo": "with custom properties.",
+ "y/S0vE": "Each member's own role",
"y1WhQk": "Your new password",
"y1Z3or": "Language",
"y3qXTf": "Copies",
@@ -1888,11 +1949,13 @@
"zLaWRs": "Select at least one site or disable site restrictions",
"zOY+qa": "{count} key events",
"zPWjZY": "Behavior",
+ "zPqL85": "Recipient email",
"zQvVDJ": "All",
"zSOvI0": "Filters",
"zUJjPA": "No team",
"zWgbGg": "Today",
"zWkvNO": "Timeline",
+ "zXzUuE": "This link expires {date}.",
"zY8xSk": "Enter the domain of the website you want to track",
"zZE+e+": "Experiments use multivariate feature flags to assign each visitor to one stable variant.",
"znwd1N": "Delete Funnel",
diff --git a/client/src/api/admin/endpoints/adminOrganizations.ts b/client/src/api/admin/endpoints/adminOrganizations.ts
index dd814fad1..809545dd1 100644
--- a/client/src/api/admin/endpoints/adminOrganizations.ts
+++ b/client/src/api/admin/endpoints/adminOrganizations.ts
@@ -1,3 +1,4 @@
+import type { OrgRole } from "@rybbit/shared";
import { authedFetch } from "../../utils";
export interface AdminOrganizationData {
@@ -95,7 +96,7 @@ export interface AdminOrganizationMemberDetail {
};
membership: {
id: string;
- role: "owner" | "admin" | "member";
+ role: OrgRole;
hasRestrictedSiteAccess: boolean;
siteIds: number[];
};
@@ -107,7 +108,7 @@ export function getAdminOrganizationMember(organizationId: string, memberId: str
}
export interface UpdateAdminOrganizationMemberInput {
- role: "owner" | "admin" | "member";
+ role: OrgRole;
hasRestrictedSiteAccess: boolean;
siteIds: number[];
}
diff --git a/client/src/api/admin/endpoints/auth.ts b/client/src/api/admin/endpoints/auth.ts
index d45604bbf..d56ab58fa 100644
--- a/client/src/api/admin/endpoints/auth.ts
+++ b/client/src/api/admin/endpoints/auth.ts
@@ -1,3 +1,4 @@
+import type { SiteGrantRole } from "@rybbit/shared";
import { authedFetch } from "../../utils";
export type GetOrganizationMembersResponse = {
@@ -15,6 +16,8 @@ export type GetOrganizationMembersResponse = {
siteAccess: {
hasRestrictedSiteAccess: boolean;
siteIds: number[];
+ /** The role all the member's site grants carry; null when they carry none (their organization role applies) or differ. */
+ siteRole: SiteGrantRole | null;
};
teams: {
id: string;
@@ -47,14 +50,15 @@ export function getOrgApiUsage(organizationId: string) {
export function updateMemberSiteAccess(
organizationId: string,
memberId: string,
- data: { hasRestrictedSiteAccess: boolean; siteIds: number[] }
+ data: {
+ hasRestrictedSiteAccess: boolean;
+ siteIds: number[];
+ /** Raises the member's role on those sites; null leaves their organization role. */
+ siteRole?: SiteGrantRole | null;
+ }
) {
- return authedFetch(
- `/organizations/${organizationId}/members/${memberId}/sites`,
- undefined,
- {
- method: "PUT",
- data,
- }
- );
+ return authedFetch(`/organizations/${organizationId}/members/${memberId}/sites`, undefined, {
+ method: "PUT",
+ data,
+ });
}
diff --git a/client/src/api/admin/endpoints/index.ts b/client/src/api/admin/endpoints/index.ts
index d51fbd4a2..28f3c224b 100644
--- a/client/src/api/admin/endpoints/index.ts
+++ b/client/src/api/admin/endpoints/index.ts
@@ -14,6 +14,17 @@ export {
} from "./sites";
export type { SiteResponse, GetSitesFromOrgResponse, SiteUsageResponse, UnclaimedSiteResponse } from "./sites";
+// Site transfer endpoints
+export {
+ acceptSiteTransfer,
+ cancelSiteTransfer,
+ createSiteTransfer,
+ declineSiteTransfer,
+ fetchIncomingSiteTransfer,
+ fetchSiteTransfer,
+} from "./siteTransfers";
+export type { IncomingSiteTransfer, SiteTransfer } from "./siteTransfers";
+
// Organizations endpoints
export {
getUserOrganizations,
diff --git a/client/src/api/admin/endpoints/organizations.ts b/client/src/api/admin/endpoints/organizations.ts
index f91116634..057fd9854 100644
--- a/client/src/api/admin/endpoints/organizations.ts
+++ b/client/src/api/admin/endpoints/organizations.ts
@@ -1,3 +1,4 @@
+import type { OrgRole, Permission } from "@rybbit/shared";
import { authedFetch } from "../../utils";
export type UserOrganization = {
@@ -7,7 +8,11 @@ export type UserOrganization = {
logo: string | null;
createdAt: string;
metadata: string | null;
- role: string;
+ role: OrgRole;
+ /** What that role allows in the organization. Read through useOrgPermissions, not directly. */
+ permissions: Permission[];
+ /** Roles the user may give when inviting or editing members, highest first. */
+ assignableRoles: OrgRole[];
};
export const USER_ORGANIZATIONS_QUERY_KEY = "userOrganizations";
diff --git a/client/src/api/admin/endpoints/siteTransfers.ts b/client/src/api/admin/endpoints/siteTransfers.ts
new file mode 100644
index 000000000..c994b80fe
--- /dev/null
+++ b/client/src/api/admin/endpoints/siteTransfers.ts
@@ -0,0 +1,66 @@
+import { authedFetch } from "../../utils";
+
+// Handing a site to someone outside its organization. The sender names a
+// recipient by email; the recipient opens the emailed link (/transfer/<id>)
+// signed in with that address and picks an organization they manage.
+
+/** A site's pending outgoing transfer, as its sender sees it. */
+export type SiteTransfer = {
+ id: string;
+ recipientEmail: string;
+ createdAt: string;
+ expiresAt: string;
+ /** The link the recipient was emailed, for the sender to pass on themselves. */
+ url: string;
+};
+
+/** What the recipient is being offered. */
+export type IncomingSiteTransfer = {
+ id: string;
+ site: { siteId: number; name: string; domain: string };
+ sourceOrganizationId: string;
+ sourceOrganizationName: string;
+ /** The sender's email address; null when their account is gone. */
+ sentBy: string | null;
+ expiresAt: string;
+};
+
+export function fetchSiteTransfer(siteId: number) {
+ return authedFetch<{ transfer: SiteTransfer | null }>(`/sites/${siteId}/transfer`);
+}
+
+/** Starts the site's transfer, replacing (and so revoking) any pending one. */
+export function createSiteTransfer(siteId: number, email: string) {
+ return authedFetch<SiteTransfer>(`/sites/${siteId}/transfer`, undefined, {
+ method: "POST",
+ data: { email },
+ });
+}
+
+export function cancelSiteTransfer(siteId: number) {
+ return authedFetch<{ success: boolean }>(`/sites/${siteId}/transfer`, undefined, { method: "DELETE" });
+}
+
+/**
+ * The transfer behind a /transfer/<id> link. Fails with an ApiError: 403 (with
+ * `recipientEmail` in its body) when signed in as someone else, 404 when the
+ * link is invalid or expired.
+ */
+export function fetchIncomingSiteTransfer(transferId: string) {
+ return authedFetch<IncomingSiteTransfer>(`/site-transfers/${encodeURIComponent(transferId)}`);
+}
+
+/** Moves the site into one of the recipient's organizations. */
+export function acceptSiteTransfer(transferId: string, organizationId: string) {
+ return authedFetch<{ success: boolean; siteId: number; organizationId: string }>(
+ `/site-transfers/${encodeURIComponent(transferId)}/accept`,
+ undefined,
+ { method: "POST", data: { organizationId } }
+ );
+}
+
+export function declineSiteTransfer(transferId: string) {
+ return authedFetch<{ success: boolean }>(`/site-transfers/${encodeURIComponent(transferId)}/decline`, undefined, {
+ method: "POST",
+ });
+}
diff --git a/client/src/api/admin/endpoints/sites.ts b/client/src/api/admin/endpoints/sites.ts
index cfa80ec9b..5ce8e109f 100644
--- a/client/src/api/admin/endpoints/sites.ts
+++ b/client/src/api/admin/endpoints/sites.ts
@@ -1,3 +1,4 @@
+import type { OrgRole, Permission } from "@rybbit/shared";
import { authedFetch } from "../../utils";
export type SiteResponse = {
@@ -19,6 +20,10 @@ export type SiteResponse = {
blockBots: boolean;
firstPartyProxy?: boolean;
isOwner: boolean;
+ /** The viewer's role on this site; null for public and private-link viewers. */
+ role: OrgRole | null;
+ /** What that role allows here. Read through useSitePermissions, not directly. */
+ permissions: Permission[];
// Cloud only: the site collects nothing until its organization starts a trial or plan.
requiresPlan?: boolean;
// Analytics features
@@ -48,6 +53,9 @@ export type GetSitesFromOrgResponse = {
monthlyEventCount: number | null;
overMonthlyLimit: boolean | null;
} | null;
+ /** The viewer's role in the organization and what it allows. */
+ role: OrgRole | null;
+ permissions: Permission[];
sites: Array<{
id: string | null;
siteId: number;
@@ -63,6 +71,8 @@ export type GetSitesFromOrgResponse = {
blockBots: boolean;
sessionsLast24Hours: number;
isOwner: boolean;
+ role: OrgRole;
+ permissions: Permission[];
tags?: string[] | null;
teams?: { id: string; name: string }[];
// Cloud only: the site collects nothing until its organization starts a trial or plan.
diff --git a/client/src/api/admin/endpoints/teams.ts b/client/src/api/admin/endpoints/teams.ts
index f1e9e6e5f..af7837632 100644
--- a/client/src/api/admin/endpoints/teams.ts
+++ b/client/src/api/admin/endpoints/teams.ts
@@ -1,3 +1,4 @@
+import type { SiteGrantRole } from "@rybbit/shared";
import { authedFetch } from "../../utils";
export type TeamMember = {
@@ -10,6 +11,7 @@ export type TeamSite = {
siteId: number;
domain: string;
name: string;
+ role: SiteGrantRole | null;
};
export type Team = {
@@ -20,6 +22,8 @@ export type Team = {
updatedAt: string | null;
members: TeamMember[];
sites: TeamSite[];
+ /** The role the team's members get on its sites; null when each member's own role applies (or the grants differ). */
+ siteRole: SiteGrantRole | null;
};
export type ListTeamsResponse = {
@@ -30,18 +34,20 @@ export type CreateTeamInput = {
name: string;
memberUserIds?: string[];
siteIds?: number[];
+ /** Raises members' role on the team's sites; null leaves each member's own role. */
+ siteRole?: SiteGrantRole | null;
};
export type UpdateTeamInput = {
name?: string;
memberUserIds?: string[];
siteIds?: number[];
+ /** Raises members' role on the team's sites; null leaves each member's own role; omit to keep. */
+ siteRole?: SiteGrantRole | null;
};
export function fetchTeams(organizationId: string) {
- return authedFetch<ListTeamsResponse>(
- `/organizations/${organizationId}/teams`
- );
+ return authedFetch<ListTeamsResponse>(`/organizations/${organizationId}/teams`);
}
export function createTeam(organizationId: string, data: CreateTeamInput) {
@@ -52,26 +58,16 @@ export function createTeam(organizationId: string, data: CreateTeamInput) {
});
}
-export function updateTeam(
- organizationId: string,
- teamId: string,
- data: UpdateTeamInput
-) {
- return authedFetch<{ success: boolean }>(
- `/organizations/${organizationId}/teams/${teamId}`,
- undefined,
- {
- method: "PUT",
- data,
- headers: { "Content-Type": "application/json" },
- }
- );
+export function updateTeam(organizationId: string, teamId: string, data: UpdateTeamInput) {
+ return authedFetch<{ success: boolean }>(`/organizations/${organizationId}/teams/${teamId}`, undefined, {
+ method: "PUT",
+ data,
+ headers: { "Content-Type": "application/json" },
+ });
}
export function deleteTeam(organizationId: string, teamId: string) {
- return authedFetch<{ success: boolean }>(
- `/organizations/${organizationId}/teams/${teamId}`,
- undefined,
- { method: "DELETE" }
- );
+ return authedFetch<{ success: boolean }>(`/organizations/${organizationId}/teams/${teamId}`, undefined, {
+ method: "DELETE",
+ });
}
diff --git a/client/src/api/admin/hooks/useSiteTransfers.ts b/client/src/api/admin/hooks/useSiteTransfers.ts
new file mode 100644
index 000000000..e26c0e207
--- /dev/null
+++ b/client/src/api/admin/hooks/useSiteTransfers.ts
@@ -0,0 +1,66 @@
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import {
+ acceptSiteTransfer,
+ cancelSiteTransfer,
+ createSiteTransfer,
+ declineSiteTransfer,
+ fetchIncomingSiteTransfer,
+ fetchSiteTransfer,
+ USER_ORGANIZATIONS_QUERY_KEY,
+} from "../endpoints";
+
+const siteTransferKey = (siteId?: number) => ["site-transfer", siteId];
+
+/** The site's pending outgoing transfer, or null. Needs sites:transfer on the site. */
+export function useSiteTransfer(siteId?: number, options?: { enabled?: boolean }) {
+ return useQuery({
+ queryKey: siteTransferKey(siteId),
+ queryFn: () => fetchSiteTransfer(siteId!).then(response => response.transfer),
+ enabled: !!siteId && options?.enabled !== false,
+ });
+}
+
+export function useCreateSiteTransfer(siteId: number) {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (email: string) => createSiteTransfer(siteId, email),
+ onSuccess: transfer => queryClient.setQueryData(siteTransferKey(siteId), transfer),
+ });
+}
+
+export function useCancelSiteTransfer(siteId: number) {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: () => cancelSiteTransfer(siteId),
+ onSuccess: () => queryClient.setQueryData(siteTransferKey(siteId), null),
+ });
+}
+
+/** The transfer behind a /transfer/<id> link, for its signed-in recipient. */
+export function useIncomingSiteTransfer(transferId?: string, options?: { enabled?: boolean }) {
+ return useQuery({
+ queryKey: ["incoming-site-transfer", transferId],
+ queryFn: () => fetchIncomingSiteTransfer(transferId!),
+ enabled: !!transferId && options?.enabled !== false,
+ // A wrong account (403) or a dead link (404) won't change on retry.
+ retry: false,
+ });
+}
+
+export function useAcceptSiteTransfer(transferId: string) {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: (organizationId: string) => acceptSiteTransfer(transferId, organizationId),
+ onSuccess: () => {
+ queryClient.invalidateQueries({ queryKey: ["get-sites-from-org"] });
+ queryClient.invalidateQueries({ queryKey: ["get-site"] });
+ queryClient.invalidateQueries({ queryKey: [USER_ORGANIZATIONS_QUERY_KEY] });
+ },
+ });
+}
+
+export function useDeclineSiteTransfer(transferId: string) {
+ return useMutation({
+ mutationFn: () => declineSiteTransfer(transferId),
+ });
+}
diff --git a/client/src/api/utils.test.ts b/client/src/api/utils.test.ts
index e3949e8c2..d0cd79aa9 100644
--- a/client/src/api/utils.test.ts
+++ b/client/src/api/utils.test.ts
@@ -2,7 +2,7 @@ import axios, { AxiosRequestConfig } from "axios";
import { afterEach, describe, expect, it, vi } from "vitest";
import { BACKEND_URL } from "../lib/const";
import { setPrivateKeyResolver } from "./requestContext";
-import { authedFetch } from "./utils";
+import { ApiError, authedFetch } from "./utils";
vi.mock("axios", () => ({ default: vi.fn() }));
@@ -111,6 +111,17 @@ describe("authedFetch", () => {
await expect(authedFetch("/sites/42")).rejects.toThrow("You do not have access to this site");
});
+ it("keeps the status and body of a backend error for callers that branch on them", async () => {
+ const body = { error: "This transfer was sent to a different email address", recipientEmail: "[email protected]" };
+ axiosMock.mockRejectedValue({ response: { status: 403, data: body } });
+
+ const error = await authedFetch("/site-transfers/abc").catch((error: ApiError) => error);
+
+ expect(error).toBeInstanceOf(ApiError);
+ expect(error).toBeInstanceOf(Error);
+ expect(error).toMatchObject({ message: body.error, status: 403, body });
+ });
+
it("rethrows transport and malformed-response failures unchanged", async () => {
const networkError = new Error("socket closed");
axiosMock.mockRejectedValue(networkError);
diff --git a/client/src/api/utils.ts b/client/src/api/utils.ts
index 3b498d16e..8ad22ac8a 100644
--- a/client/src/api/utils.ts
+++ b/client/src/api/utils.ts
@@ -130,8 +130,21 @@ export async function authedFetch<T>(
return response.data;
} catch (error: any) {
if (error?.response?.data?.error) {
- throw new Error(error.response.data.error);
+ throw new ApiError(error.response.data.error, error.response.status, error.response.data);
}
throw error;
}
}
+
+/** A backend error response: its public message, plus the status and body for callers that branch on them. */
+export class ApiError extends Error {
+ status: number | undefined;
+ body: unknown;
+
+ constructor(message: string, status: number | undefined, body: unknown) {
+ super(message);
+ this.name = "ApiError";
+ this.status = status;
+ this.body = body;
+ }
+}
diff --git a/client/src/app/(home)/SiteCard.tsx b/client/src/app/(home)/SiteCard.tsx
index 3dff8ce12..b14714e2e 100644
--- a/client/src/app/(home)/SiteCard.tsx
+++ b/client/src/app/(home)/SiteCard.tsx
@@ -23,6 +23,8 @@ export interface SiteCardProps {
name: string;
domain: string;
tags?: string[];
+ /** The viewer may edit this site's tags (sites:configure on it). */
+ canEditTags?: boolean;
allTags?: string[];
onTagsUpdated?: () => void;
selectedTags?: string[];
@@ -111,6 +113,7 @@ function SiteCardView({
name,
domain,
tags = [],
+ canEditTags = false,
allTags = [],
onTagsUpdated,
onTagClick,
@@ -196,7 +199,7 @@ function SiteCardView({
+{tags.length - 3}
</Badge>
)}
- {onTagsUpdated && (
+ {canEditTags && onTagsUpdated && (
<Tooltip>
<TagEditor
siteId={siteId}
diff --git a/client/src/app/(home)/SiteCards.tsx b/client/src/app/(home)/SiteCards.tsx
index 281ba4532..74b1fa7fd 100644
--- a/client/src/app/(home)/SiteCards.tsx
+++ b/client/src/app/(home)/SiteCards.tsx
@@ -5,9 +5,11 @@ import { useStore } from "@/lib/store";
import { hasRangeTimes } from "@/lib/time";
import { BatchedSiteCard, SiteCard, SiteCardProps } from "./SiteCard";
-interface SiteCardsProps extends Omit<SiteCardProps, "siteId" | "name" | "domain" | "tags"> {
+type SiteFields = "siteId" | "name" | "domain" | "tags" | "canEditTags";
+
+interface SiteCardsProps extends Omit<SiteCardProps, SiteFields> {
organizationId: string;
- sites: Pick<SiteCardProps, "siteId" | "name" | "domain" | "tags">[];
+ sites: Pick<SiteCardProps, SiteFields>[];
}
export function SiteCards({ organizationId, sites, ...props }: SiteCardsProps) {
diff --git a/client/src/app/(home)/page.tsx b/client/src/app/(home)/page.tsx
index 3f2bdc23a..ca4c6b00f 100644
--- a/client/src/app/(home)/page.tsx
+++ b/client/src/app/(home)/page.tsx
@@ -20,6 +20,7 @@ import { Card, CardDescription, CardTitle } from "../../components/ui/card";
import { Input } from "../../components/ui/input";
import { MultiSelect } from "../../components/ui/multi-select";
import { Pagination } from "../../components/pagination";
+import { useOrgPermissions } from "../../hooks/usePermissions";
import { useSetPageTitle } from "../../hooks/useSetPageTitle";
import { authClient } from "../../lib/auth";
import { IS_CLOUD } from "../../lib/const";
@@ -76,11 +77,10 @@ export default function Home() {
const hasOrganizations = Array.isArray(userOrganizationsData) && userOrganizationsData.length > 0;
const hasNoOrganizations = !isLoading && !hasOrganizations;
- // Check user permissions for the active organization
- const activeOrgMembership = userOrganizationsData?.find(org => org.id === activeOrganization?.id);
-
- const isUserMember = activeOrgMembership?.role === "member";
- const canAddSites = hasOrganizations && !isUserMember;
+ // What the user may do in the active organization
+ const { can } = useOrgPermissions(activeOrganization?.id);
+ const canAddSites = hasOrganizations && can("sites:create");
+ const cantAddSitesReason = t("You don't have permission to add sites to this organization");
// Check if we should show sites content
const shouldShowSites = hasOrganizations && !isLoading;
@@ -153,7 +153,7 @@ export default function Home() {
teams={teams}
value={selectedTeamFilter}
onValueChange={setSelectedTeamFilter}
- canCreateTeam={!isUserMember && hasOrganizations}
+ canCreateTeam={hasOrganizations && can("teams:manage")}
/>
);
@@ -209,7 +209,7 @@ export default function Home() {
</div>
)}
<div className="hidden md:block">
- <AddSite disabled={!canAddSites} />
+ <AddSite disabled={!canAddSites} disabledReason={cantAddSitesReason} />
</div>
</div>
) : null;
@@ -218,7 +218,13 @@ export default function Home() {
<div className="flex flex-col gap-2">
<SiteCards
organizationId={activeOrganization?.id ?? ""}
- sites={paginatedSites?.map(site => ({ ...site, tags: site.tags ?? [] })) ?? []}
+ sites={
+ paginatedSites?.map(site => ({
+ ...site,
+ tags: site.tags ?? [],
+ canEditTags: site.permissions?.includes("sites:configure") ?? false,
+ })) ?? []
+ }
allTags={allTags}
onTagsUpdated={refetchSites}
selectedTags={selectedTags}
@@ -238,6 +244,8 @@ export default function Home() {
<CardTitle className="mb-2 text-xl">{t("No websites yet")}</CardTitle>
<CardDescription className="mb-4">{t("Add your first website to start tracking analytics")}</CardDescription>
<AddSite
+ disabled={!canAddSites}
+ disabledReason={cantAddSitesReason}
trigger={
<Button variant="success" disabled={!canAddSites}>
<Plus className="h-4 w-4" />
diff --git a/client/src/app/[site]/EnableFeatureButtons.test.tsx b/client/src/app/[site]/EnableFeatureButtons.test.tsx
index 0a1b189ea..021747d73 100644
--- a/client/src/app/[site]/EnableFeatureButtons.test.tsx
+++ b/client/src/app/[site]/EnableFeatureButtons.test.tsx
@@ -10,7 +10,7 @@ const mocks = vi.hoisted(() => ({
refetch: vi.fn(),
toastSuccess: vi.fn(),
toastError: vi.fn(),
- site: {} as Record<string, boolean>,
+ site: {} as Record<string, unknown>,
}));
vi.mock("next-intl", () => ({
@@ -37,7 +37,7 @@ function deferred() {
}
beforeEach(() => {
- mocks.site = {};
+ mocks.site = { permissions: ["sites:configure"] };
});
afterEach(() => {
@@ -83,6 +83,14 @@ describe.each([
expect(button.hasAttribute("aria-busy")).toBe(false);
});
+ it("asks for an admin instead of offering Enable without sites:configure", () => {
+ mocks.site = { permissions: ["analytics:read"] };
+ render(<Banner />);
+
+ expect(screen.queryByRole("button", { name: "Enable" })).toBeNull();
+ expect(screen.getByText("Ask a site admin to enable it.")).toBeTruthy();
+ });
+
it("reports a failure and lets the user try again", async () => {
mocks.updateSiteConfig.mockRejectedValue(new Error("Session replay requires a Pro subscription"));
render(<Banner />);
diff --git a/client/src/app/[site]/components/Header/ClaimSiteBanner.test.tsx b/client/src/app/[site]/components/Header/ClaimSiteBanner.test.tsx
index 447b57c42..11d22303c 100644
--- a/client/src/app/[site]/components/Header/ClaimSiteBanner.test.tsx
+++ b/client/src/app/[site]/components/Header/ClaimSiteBanner.test.tsx
@@ -181,7 +181,7 @@ describe("claim flow", () => {
expect(state.createOrg).not.toHaveBeenCalled();
});
it("lets an existing admin claim into their organization", async () => {
- state.organizations = [{ id: "org_1", name: "Existing", role: "admin" }];
+ state.organizations = [{ id: "org_1", name: "Existing", role: "admin", permissions: ["sites:create"] }];
show();
await openClaim();
fireEvent.click(await screen.findByRole("button", { name: "Claim site" }));
diff --git a/client/src/app/[site]/components/Header/ClaimSiteDialog.tsx b/client/src/app/[site]/components/Header/ClaimSiteDialog.tsx
index 060c222fa..f5bd722ab 100644
--- a/client/src/app/[site]/components/Header/ClaimSiteDialog.tsx
+++ b/client/src/app/[site]/components/Header/ClaimSiteDialog.tsx
@@ -86,7 +86,8 @@ export function ClaimSiteDialog({
const returnPath = `/${siteId}/${privateLinkKey}?claim=1`;
const [selectedOrganizationId, setSelectedOrganizationId] = useState<string>("");
- const adminOrganizations = (organizations ?? []).filter(org => org.role === "owner" || org.role === "admin");
+ // Organizations the user may add sites to.
+ const adminOrganizations = (organizations ?? []).filter(org => org.permissions?.includes("sites:create"));
const hasExistingOrganization = !!user && adminOrganizations.length > 0;
// Step 1 = account (skipped when signed in), step 2 = claim (existing org only), step 3 = plan (cloud only)
diff --git a/client/src/app/[site]/components/Header/UsageBanners.tsx b/client/src/app/[site]/components/Header/UsageBanners.tsx
index c7676e0b9..59ebb92ca 100644
--- a/client/src/app/[site]/components/Header/UsageBanners.tsx
+++ b/client/src/app/[site]/components/Header/UsageBanners.tsx
@@ -3,10 +3,13 @@ import { useExtracted } from "next-intl";
import Link from "next/link";
import { useCurrentSite } from "../../../../api/admin/hooks/useSites";
import { Button } from "../../../../components/ui/button";
+import { useCanInOrg } from "../../../../hooks/usePermissions";
export function UsageBanners() {
const t = useExtracted();
const { site, subscription } = useCurrentSite();
+ // Upgrading is a billing action, so only offer it to those who can take it.
+ const canUpgrade = useCanInOrg("billing:manage", site?.organizationId ?? undefined);
if (!site) return null;
@@ -35,12 +38,12 @@ export function UsageBanners() {
<span className="text-red-700 dark:text-red-300 font-medium">
{t("Monthly event limit exceeded:")} <strong>{formatNumber(subscription.monthlyEventCount || 0)}</strong> {t("of")}{" "}
<strong>{formatNumber(subscription.eventLimit)}</strong> {t("events used.")}{" "}
- {site.isOwner
+ {canUpgrade
? t("Upgrade your plan to continue collecting analytics.")
: t("Please contact your organization owner to upgrade.")}
</span>
</div>
- {site.isOwner && (
+ {canUpgrade && (
<Button variant="success" size="sm" asChild>
<Link href="/settings/billing">
{t("Upgrade")} <ArrowRight className="ml-1 h-3 w-3" />
@@ -60,12 +63,12 @@ export function UsageBanners() {
<span className="text-amber-700 dark:text-amber-300 font-medium">
{t("Approaching monthly event limit:")} <strong>{formatNumber(subscription?.monthlyEventCount || 0)}</strong> {t("of")}{" "}
<strong>{formatNumber(subscription?.eventLimit || 0)}</strong> {t("events used.")}{" "}
- {site.isOwner
+ {canUpgrade
? t("Consider upgrading to avoid interruptions.")
: t("You may want to notify your organization owner.")}
</span>
</div>
- {site.isOwner && (
+ {canUpgrade && (
<Button variant="success" size="sm" asChild>
<Link href="/settings/billing">
{t("Upgrade")} <ArrowRight className="ml-1 h-3 w-3" />
diff --git a/client/src/app/[site]/components/Sidebar/SiteSelector.tsx b/client/src/app/[site]/components/Sidebar/SiteSelector.tsx
index 528fd4380..68b2766b8 100644
--- a/client/src/app/[site]/components/Sidebar/SiteSelector.tsx
+++ b/client/src/app/[site]/components/Sidebar/SiteSelector.tsx
@@ -7,6 +7,7 @@ import { Favicon } from "../../../../components/Favicon";
import { Button } from "../../../../components/ui/button";
import { Command, CommandEmpty, CommandInput, CommandItem, CommandList } from "../../../../components/ui/command";
import { Popover, PopoverContent, PopoverTrigger } from "../../../../components/ui/popover";
+import { useCanInOrg } from "../../../../hooks/usePermissions";
import { authClient } from "../../../../lib/auth";
import { useStore } from "../../../../lib/store";
import { userStore } from "../../../../lib/userStore";
@@ -79,6 +80,7 @@ function SiteSelectorContent({ onSiteSelect }: { onSiteSelect: () => void }) {
const t = useExtracted();
const { data: activeOrganization } = authClient.useActiveOrganization();
const { data: sites } = useGetSitesFromOrg(activeOrganization?.id);
+ const canAddSites = useCanInOrg("sites:create", activeOrganization?.id);
const embed = useEmbedablePage();
const pathname = usePathname();
@@ -172,7 +174,7 @@ function SiteSelectorContent({ onSiteSelect }: { onSiteSelect: () => void }) {
</div>
)}
- {!isDemo && (
+ {!isDemo && canAddSites && (
<div className="border-t border-neutral-200 dark:border-neutral-800 p-1">
<AddSite
trigger={
diff --git a/client/src/app/[site]/components/SubHeader/Filters/NewFilterButton.tsx b/client/src/app/[site]/components/SubHeader/Filters/NewFilterButton.tsx
index a08a35931..2673258a7 100644
--- a/client/src/app/[site]/components/SubHeader/Filters/NewFilterButton.tsx
+++ b/client/src/app/[site]/components/SubHeader/Filters/NewFilterButton.tsx
@@ -4,12 +4,10 @@ import { Filter, FilterParameter, Segment } from "@rybbit/shared";
import { ListFilterPlus } from "lucide-react";
import { useExtracted } from "next-intl";
import { useRef, useState } from "react";
-import { useUserOrganizations } from "../../../../../api/admin/hooks/useOrganizations";
-import { useGetSite } from "../../../../../api/admin/hooks/useSites";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../../components/ui/basic-tabs";
import { Button } from "../../../../../components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "../../../../../components/ui/popover";
-import { authClient } from "../../../../../lib/auth";
+import { useCanOnSite } from "../../../../../hooks/usePermissions";
import { addFilter, useStore } from "../../../../../lib/store";
import { FilterPicker } from "./FilterPicker";
import { SegmentDialog } from "./SegmentDialog";
@@ -25,10 +23,8 @@ type DialogState = { segment?: Segment; initialFilters?: Filter[] } | null;
*/
export function NewFilterButton({ availableFilters }: { availableFilters?: FilterParameter[] }) {
const t = useExtracted();
- const session = authClient.useSession();
const { site, privateKey, filters } = useStore();
- const { data: siteInfo } = useGetSite(site, { enabled: !!session.data });
- const { data: organizations } = useUserOrganizations();
+ const canWriteSegments = useCanOnSite("segments:write", site);
const [open, setOpen] = useState(false);
const [tab, setTab] = useState<Tab>("filters");
@@ -36,10 +32,9 @@ export function NewFilterButton({ availableFilters }: { availableFilters?: Filte
const pendingRef = useRef<() => Filter | null>(() => null);
const [dialog, setDialog] = useState<DialogState>(null);
- // A signed-in visitor on someone else's public site is not a member; the
- // private-link view is read-only by design even for members.
- const isMember = !!siteInfo?.organizationId && !!organizations?.some(org => org.id === siteInfo.organizationId);
- const canWrite = !!session.data && !privateKey && isMember;
+ // Public viewers get no permissions from the server; the private-link view
+ // is read-only by design even for members.
+ const canWrite = !privateKey && canWriteSegments;
const resetPicker = () => {
pendingRef.current = () => null;
diff --git a/client/src/app/[site]/components/SubHeader/Filters/SegmentDialog.tsx b/client/src/app/[site]/components/SubHeader/Filters/SegmentDialog.tsx
index ff517c44b..23c357755 100644
--- a/client/src/app/[site]/components/SubHeader/Filters/SegmentDialog.tsx
+++ b/client/src/app/[site]/components/SubHeader/Filters/SegmentDialog.tsx
@@ -8,6 +8,7 @@ import { useRef, useState } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
import { useGetSite } from "../../../../../api/admin/hooks/useSites";
+import { useCanInOrg } from "../../../../../hooks/usePermissions";
import {
useCreateSegment,
useDeleteSegment,
@@ -164,9 +165,10 @@ function SegmentForm({ onOpenChange, siteId, segment, initialFilters, availableF
setPickerOpen(isOpen);
};
- // Org-wide scope is an admin decision on the server; only offer it when the
- // toggle can succeed, or when the segment is already org-wide.
- const canChooseScope = !!site?.isOwner || segment?.siteId === null;
+ // Org-wide scope needs segments:manage in the organization; only offer it
+ // when the toggle can succeed, or when the segment is already org-wide.
+ const canManageSegments = useCanInOrg("segments:manage", site?.organizationId ?? undefined);
+ const canChooseScope = (!!site?.organizationId && canManageSegments) || segment?.siteId === null;
const organizationName = activeOrganization?.name;
const isSaving = isCreating || isUpdating;
diff --git a/client/src/app/[site]/dashboards/[dashboardId]/page.tsx b/client/src/app/[site]/dashboards/[dashboardId]/page.tsx
index f77bda14d..951f05fae 100644
--- a/client/src/app/[site]/dashboards/[dashboardId]/page.tsx
+++ b/client/src/app/[site]/dashboards/[dashboardId]/page.tsx
@@ -25,6 +25,7 @@ import { Button } from "../../../../components/ui/button";
import { Skeleton } from "../../../../components/ui/skeleton";
import { toast } from "../../../../components/ui/sonner";
import { cn } from "../../../../lib/utils";
+import { useCanOnSite } from "../../../../hooks/usePermissions";
import { useSetPageTitle } from "../../../../hooks/useSetPageTitle";
import { canGoBack, canGoForward, goBack, goForward, useStore } from "../../../../lib/store";
import { DashboardCardEditor } from "../components/DashboardCardEditor";
@@ -47,6 +48,7 @@ export default function DashboardDetailPage() {
const { time, setTime } = useStore();
const { data: dashboard, isLoading } = useGetDashboard(siteId, dashboardId);
const updateDashboard = useUpdateDashboard();
+ const canWrite = useCanOnSite("dashboards:write", siteId);
const [editMode, setEditMode] = useState(false);
const [name, setName] = useState<string | null>(null);
@@ -393,12 +395,12 @@ export default function DashboardDetailPage() {
Save
</Button>
</>
- ) : (
+ ) : canWrite ? (
<Button variant="outline" size="sm" onClick={() => setEditMode(true)}>
<Pencil className="h-4 w-4" />
Edit
</Button>
- )}
+ ) : null}
</div>
</div>
@@ -411,10 +413,12 @@ export default function DashboardDetailPage() {
range above and can be dragged and resized.
</p>
</div>
- <Button variant="outline" onClick={handleAddCard}>
- <Plus className="h-4 w-4" />
- Add a card
- </Button>
+ {canWrite && (
+ <Button variant="outline" onClick={handleAddCard}>
+ <Plus className="h-4 w-4" />
+ Add a card
+ </Button>
+ )}
</div>
) : (
<div
diff --git a/client/src/app/[site]/dashboards/page.tsx b/client/src/app/[site]/dashboards/page.tsx
index 3f2d83f16..659b258ef 100644
--- a/client/src/app/[site]/dashboards/page.tsx
+++ b/client/src/app/[site]/dashboards/page.tsx
@@ -18,6 +18,7 @@ import {
} from "../../../components/ui/alert-dialog";
import { Card } from "../../../components/ui/card";
import { Skeleton } from "../../../components/ui/skeleton";
+import { useCanOnSite } from "../../../hooks/usePermissions";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
function relativeUpdated(updatedAt: string | null | undefined): string | null {
@@ -36,6 +37,7 @@ export default function DashboardsListPage() {
const { data: dashboards, isLoading } = useGetDashboards(siteId);
const createDashboard = useCreateDashboard();
const deleteDashboard = useDeleteDashboard();
+ const canWrite = useCanOnSite("dashboards:write", siteId);
const [pendingDelete, setPendingDelete] = useState<number | null>(null);
const handleCreate = async () => {
@@ -52,10 +54,12 @@ export default function DashboardsListPage() {
Build views from custom SQL queries, scoped to the site time range.
</p>
</div>
- <Button onClick={handleCreate} disabled={createDashboard.isPending}>
- {createDashboard.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}
- New dashboard
- </Button>
+ {canWrite && (
+ <Button onClick={handleCreate} disabled={createDashboard.isPending}>
+ {createDashboard.isPending ? <Loader2 className="h-4 w-4 animate-spin" /> : <Plus className="h-4 w-4" />}
+ New dashboard
+ </Button>
+ )}
</div>
{isLoading ? (
@@ -82,10 +86,12 @@ export default function DashboardsListPage() {
and arrange the cards to fit how you read your data.
</p>
</div>
- <Button variant="outline" onClick={handleCreate} disabled={createDashboard.isPending}>
- <Plus className="h-4 w-4" />
- Create your first dashboard
- </Button>
+ {canWrite && (
+ <Button variant="outline" onClick={handleCreate} disabled={createDashboard.isPending}>
+ <Plus className="h-4 w-4" />
+ Create your first dashboard
+ </Button>
+ )}
</div>
) : (
<div className="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
@@ -108,18 +114,20 @@ export default function DashboardsListPage() {
{updated && ` Β· updated ${updated}`}
</div>
</div>
- <Button
- size="smIcon"
- variant="ghost"
- className="opacity-0 transition-opacity focus-visible:opacity-100 group-hover:opacity-100"
- onClick={event => {
- event.stopPropagation();
- setPendingDelete(dashboard.dashboardId);
- }}
- aria-label={`Delete ${dashboard.name}`}
- >
- <Trash2 className="h-4 w-4 text-red-500" />
- </Button>
+ {canWrite && (
+ <Button
+ size="smIcon"
+ variant="ghost"
+ className="opacity-0 transition-opacity focus-visible:opacity-100 group-hover:opacity-100"
+ onClick={event => {
+ event.stopPropagation();
+ setPendingDelete(dashboard.dashboardId);
+ }}
+ aria-label={`Delete ${dashboard.name}`}
+ >
+ <Trash2 className="h-4 w-4 text-red-500" />
+ </Button>
+ )}
</Card>
);
})}
diff --git a/client/src/app/[site]/errors/components/EnableErrorTracking.tsx b/client/src/app/[site]/errors/components/EnableErrorTracking.tsx
index bf1c8ec85..13cdf43f4 100644
--- a/client/src/app/[site]/errors/components/EnableErrorTracking.tsx
+++ b/client/src/app/[site]/errors/components/EnableErrorTracking.tsx
@@ -9,6 +9,7 @@ import { updateSiteConfig } from "../../../../api/admin/endpoints";
import { useGetSite } from "../../../../api/admin/hooks/useSites";
import { Alert, AlertDescription, AlertTitle } from "../../../../components/ui/alert";
import { Button } from "../../../../components/ui/button";
+import { useCanOnSite } from "../../../../hooks/usePermissions";
export function EnableErrorTracking() {
const t = useExtracted();
@@ -16,6 +17,7 @@ export function EnableErrorTracking() {
const siteId = Number(params.site);
const { data: siteMetadata, refetch } = useGetSite(siteId);
const [isEnabling, setIsEnabling] = useState(false);
+ const canConfigure = useCanOnSite("sites:configure", siteId);
if (siteMetadata?.trackErrors) return null;
@@ -47,9 +49,13 @@ export function EnableErrorTracking() {
{t("Error tracking captures JavaScript errors and exceptions from your application.")} <b>{t("Note:")}</b>{" "}
{t("Enabling error tracking will increase your event usage.")}
</div>
- <Button size="sm" variant="success" loading={isEnabling} onClick={enable}>
- {t("Enable")}
- </Button>
+ {canConfigure ? (
+ <Button size="sm" variant="success" loading={isEnabling} onClick={enable}>
+ {t("Enable")}
+ </Button>
+ ) : (
+ <p>{t("Ask a site admin to enable it.")}</p>
+ )}
</AlertDescription>
</div>
</div>
diff --git a/client/src/app/[site]/experiments/components/ExperimentRow.tsx b/client/src/app/[site]/experiments/components/ExperimentRow.tsx
index ee435f6b3..d1e687c42 100644
--- a/client/src/app/[site]/experiments/components/ExperimentRow.tsx
+++ b/client/src/app/[site]/experiments/components/ExperimentRow.tsx
@@ -39,7 +39,16 @@ function MetaChip({ icon, children }: { icon: ReactNode; children: ReactNode })
);
}
-export function ExperimentRow({ experiment, experiments }: { experiment: Experiment; experiments: Experiment[] }) {
+export function ExperimentRow({
+ experiment,
+ experiments,
+ canWrite,
+}: {
+ experiment: Experiment;
+ experiments: Experiment[];
+ /** experiments:write: start, pause, complete, edit and delete. Without it the row is read-only. */
+ canWrite: boolean;
+}) {
const t = useExtracted();
const deleteMutation = useDeleteExperiment();
const updateMutation = useUpdateExperiment();
@@ -121,58 +130,60 @@ export function ExperimentRow({ experiment, experiments }: { experiment: Experim
)}
</div>
- <div className="flex shrink-0 items-center gap-2">
- {experiment.status !== "running" && experiment.status !== "completed" && (
- <Button size="sm" onClick={() => setStatus("running")} disabled={updateMutation.isPending}>
- <Play className="h-3.5 w-3.5" />
- {t("Start")}
- </Button>
- )}
- {experiment.status === "running" && (
- <Button
- size="sm"
- variant="secondary"
- onClick={() => setStatus("paused")}
- disabled={updateMutation.isPending}
- >
- <Pause className="h-3.5 w-3.5" />
- {t("Pause")}
- </Button>
- )}
- {experiment.status !== "completed" && (
- <Button
- size="sm"
- variant="secondary"
- onClick={() => setCompleteOpen(true)}
- disabled={updateMutation.isPending}
- >
- <Square className="h-3.5 w-3.5" />
- {t("Complete")}
- </Button>
- )}
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button size="smIcon" variant="ghost" aria-label={t("Actions")}>
- <MoreHorizontal className="h-4 w-4" />
+ {canWrite && (
+ <div className="flex shrink-0 items-center gap-2">
+ {experiment.status !== "running" && experiment.status !== "completed" && (
+ <Button size="sm" onClick={() => setStatus("running")} disabled={updateMutation.isPending}>
+ <Play className="h-3.5 w-3.5" />
+ {t("Start")}
</Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end" className="w-40">
- <DropdownMenuItem onSelect={() => setEditOpen(true)}>
- <Pencil className="mr-2 h-4 w-4" />
- {t("Edit")}
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- disabled={deleteMutation.isPending}
- onSelect={() => setDeleteOpen(true)}
- className="text-red-600 focus:text-red-600 dark:text-red-400 dark:focus:text-red-400"
+ )}
+ {experiment.status === "running" && (
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={() => setStatus("paused")}
+ disabled={updateMutation.isPending}
>
- <Trash2 className="mr-2 h-4 w-4" />
- {t("Delete")}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
+ <Pause className="h-3.5 w-3.5" />
+ {t("Pause")}
+ </Button>
+ )}
+ {experiment.status !== "completed" && (
+ <Button
+ size="sm"
+ variant="secondary"
+ onClick={() => setCompleteOpen(true)}
+ disabled={updateMutation.isPending}
+ >
+ <Square className="h-3.5 w-3.5" />
+ {t("Complete")}
+ </Button>
+ )}
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button size="smIcon" variant="ghost" aria-label={t("Actions")}>
+ <MoreHorizontal className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-40">
+ <DropdownMenuItem onSelect={() => setEditOpen(true)}>
+ <Pencil className="mr-2 h-4 w-4" />
+ {t("Edit")}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ disabled={deleteMutation.isPending}
+ onSelect={() => setDeleteOpen(true)}
+ className="text-red-600 focus:text-red-600 dark:text-red-400 dark:focus:text-red-400"
+ >
+ <Trash2 className="mr-2 h-4 w-4" />
+ {t("Delete")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ )}
</div>
<div className="p-4">
diff --git a/client/src/app/[site]/experiments/page.tsx b/client/src/app/[site]/experiments/page.tsx
index d06d7dfbc..539c3ea44 100644
--- a/client/src/app/[site]/experiments/page.tsx
+++ b/client/src/app/[site]/experiments/page.tsx
@@ -4,6 +4,7 @@ import { useExperiments } from "@/api/analytics/hooks/experiments/useExperiments
import { NothingFound } from "@/components/NothingFound";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
+import { useCanOnSite } from "@/hooks/usePermissions";
import { useSetPageTitle } from "@/hooks/useSetPageTitle";
import { GOALS_PAGE_FILTERS } from "@/lib/filterGroups";
import { useStore } from "@/lib/store";
@@ -20,6 +21,7 @@ export default function ExperimentsPage() {
useSetPageTitle("Experiments");
const { site } = useStore();
const { data: experiments, isLoading } = useExperiments();
+ const canWrite = useCanOnSite("experiments:write");
const [search, setSearch] = useState("");
const [createOpen, setCreateOpen] = useState(false);
@@ -37,7 +39,7 @@ export default function ExperimentsPage() {
return (
<div className="mx-auto max-w-[1400px] space-y-3 p-2 md:p-4">
<SubHeader availableFilters={GOALS_PAGE_FILTERS} />
- <ExperimentDialog experiments={experiments || []} open={createOpen} onOpenChange={setCreateOpen} />
+ {canWrite && <ExperimentDialog experiments={experiments || []} open={createOpen} onOpenChange={setCreateOpen} />}
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<Input
@@ -47,10 +49,12 @@ export default function ExperimentsPage() {
value={search}
onChange={event => setSearch(event.target.value)}
/>
- <Button onClick={() => setCreateOpen(true)}>
- <Plus className="h-4 w-4" />
- {t("New experiment")}
- </Button>
+ {canWrite && (
+ <Button onClick={() => setCreateOpen(true)}>
+ <Plus className="h-4 w-4" />
+ {t("New experiment")}
+ </Button>
+ )}
</div>
{isLoading || !site ? (
@@ -58,7 +62,12 @@ export default function ExperimentsPage() {
) : filteredExperiments.length > 0 ? (
<div className="grid gap-3">
{filteredExperiments.map(experiment => (
- <ExperimentRow key={experiment.experimentId} experiment={experiment} experiments={experiments || []} />
+ <ExperimentRow
+ key={experiment.experimentId}
+ experiment={experiment}
+ experiments={experiments || []}
+ canWrite={canWrite}
+ />
))}
</div>
) : experiments?.length ? (
@@ -73,10 +82,12 @@ export default function ExperimentsPage() {
title={t("No experiments yet")}
description={t("Create an experiment from a multivariate feature flag and connect it to a conversion goal.")}
action={
- <Button onClick={() => setCreateOpen(true)}>
- <Plus className="h-4 w-4" />
- {t("New experiment")}
- </Button>
+ canWrite ? (
+ <Button onClick={() => setCreateOpen(true)}>
+ <Plus className="h-4 w-4" />
+ {t("New experiment")}
+ </Button>
+ ) : undefined
}
/>
)}
diff --git a/client/src/app/[site]/feature-flags/components/FeatureFlagTable.test.tsx b/client/src/app/[site]/feature-flags/components/FeatureFlagTable.test.tsx
index 92d0d4809..5ed1321ee 100644
--- a/client/src/app/[site]/feature-flags/components/FeatureFlagTable.test.tsx
+++ b/client/src/app/[site]/feature-flags/components/FeatureFlagTable.test.tsx
@@ -51,10 +51,10 @@ const flag: FeatureFlag = {
stats: [],
};
-function renderTable() {
+function renderTable(canWrite = true) {
render(
<TooltipProvider>
- <FeatureFlagTable flags={[flag]} />
+ <FeatureFlagTable flags={[flag]} canWrite={canWrite} />
</TooltipProvider>
);
}
@@ -84,6 +84,15 @@ afterEach(() => {
});
describe("FeatureFlagTable", () => {
+ it("is read-only without flags:write: no switch and no actions, but the state still shows", () => {
+ renderTable(false);
+
+ expect(screen.getByText("new-checkout")).toBeTruthy();
+ expect(screen.getByText("On")).toBeTruthy();
+ expect(screen.queryByRole("switch")).toBeNull();
+ expect(screen.queryByRole("button", { name: "Actions" })).toBeNull();
+ });
+
it("copies a flag's key from its row", async () => {
mocks.writeText.mockResolvedValue(undefined);
renderTable();
diff --git a/client/src/app/[site]/feature-flags/components/FeatureFlagTable.tsx b/client/src/app/[site]/feature-flags/components/FeatureFlagTable.tsx
index 68d577ec1..e7cc6e863 100644
--- a/client/src/app/[site]/feature-flags/components/FeatureFlagTable.tsx
+++ b/client/src/app/[site]/feature-flags/components/FeatureFlagTable.tsx
@@ -277,7 +277,8 @@ function RowActionsCell({ row }: CellContext<FeatureFlag, unknown>) {
);
}
-export function FeatureFlagTable({ flags }: { flags: FeatureFlag[] }) {
+/** `canWrite` (flags:write) shows the on/off switch and the edit and delete actions; without it the table is read-only. */
+export function FeatureFlagTable({ flags, canWrite }: { flags: FeatureFlag[]; canWrite: boolean }) {
const t = useExtracted();
const getRuntimeLabel = useRuntimeLabel();
const updateMutation = useUpdateFeatureFlag();
@@ -322,11 +323,13 @@ export function FeatureFlagTable({ flags }: { flags: FeatureFlag[] }) {
const flag = info.row.original;
return (
<div className="flex items-center gap-2">
- <Switch
- checked={flag.enabled}
- disabled={updateMutation.isPending}
- onCheckedChange={enabled => updateMutation.mutate({ flagId: flag.flagId, payload: { enabled } })}
- />
+ {canWrite && (
+ <Switch
+ checked={flag.enabled}
+ disabled={updateMutation.isPending}
+ onCheckedChange={enabled => updateMutation.mutate({ flagId: flag.flagId, payload: { enabled } })}
+ />
+ )}
<Badge variant={flag.enabled ? "success" : "secondary"}>{flag.enabled ? t("On") : t("Off")}</Badge>
<Badge variant="outline">{getRuntimeLabel(flag.runtime)}</Badge>
</div>
@@ -371,11 +374,15 @@ export function FeatureFlagTable({ flags }: { flags: FeatureFlag[] }) {
header: ({ column }) => <SortHeader column={column}>{t("Updated")}</SortHeader>,
cell: info => renderTimeCell(info.getValue()),
}),
- columnHelper.display({
- id: "actions",
- header: () => <span className="sr-only">{t("Actions")}</span>,
- cell: RowActionsCell,
- }),
+ ...(canWrite
+ ? [
+ columnHelper.display({
+ id: "actions",
+ header: () => <span className="sr-only">{t("Actions")}</span>,
+ cell: RowActionsCell,
+ }),
+ ]
+ : []),
];
const table = useReactTable({
diff --git a/client/src/app/[site]/feature-flags/page.tsx b/client/src/app/[site]/feature-flags/page.tsx
index 1646c8112..e448da28f 100644
--- a/client/src/app/[site]/feature-flags/page.tsx
+++ b/client/src/app/[site]/feature-flags/page.tsx
@@ -4,6 +4,7 @@ import { useFeatureFlags } from "@/api/analytics/hooks/featureFlags/useFeatureFl
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { NothingFound } from "@/components/NothingFound";
+import { useCanOnSite } from "@/hooks/usePermissions";
import { useSetPageTitle } from "@/hooks/useSetPageTitle";
import { Flag, Plus } from "lucide-react";
import { useExtracted } from "next-intl";
@@ -16,6 +17,7 @@ export default function FeatureFlagsPage() {
const t = useExtracted();
useSetPageTitle("Feature Flags");
const { data: flags, isLoading } = useFeatureFlags();
+ const canWrite = useCanOnSite("flags:write");
const [search, setSearch] = useState("");
const filteredFlags = useMemo(() => {
@@ -36,20 +38,22 @@ export default function FeatureFlagsPage() {
value={search}
onChange={event => setSearch(event.target.value)}
/>
- <FeatureFlagDialog
- trigger={
- <Button>
- <Plus className="h-4 w-4" />
- {t("New flag")}
- </Button>
- }
- />
+ {canWrite && (
+ <FeatureFlagDialog
+ trigger={
+ <Button>
+ <Plus className="h-4 w-4" />
+ {t("New flag")}
+ </Button>
+ }
+ />
+ )}
</div>
{isLoading ? (
<FeatureFlagSkeleton />
) : filteredFlags.length > 0 ? (
- <FeatureFlagTable flags={filteredFlags} />
+ <FeatureFlagTable flags={filteredFlags} canWrite={canWrite} />
) : flags?.length ? (
<NothingFound icon={<Flag className="h-10 w-10" />} title={t("No feature flags found")} />
) : (
@@ -57,14 +61,16 @@ export default function FeatureFlagsPage() {
icon={<Flag className="h-10 w-10" />}
title={t("No feature flags yet")}
action={
- <FeatureFlagDialog
- trigger={
- <Button>
- <Plus className="h-4 w-4" />
- {t("New flag")}
- </Button>
- }
- />
+ canWrite ? (
+ <FeatureFlagDialog
+ trigger={
+ <Button>
+ <Plus className="h-4 w-4" />
+ {t("New flag")}
+ </Button>
+ }
+ />
+ ) : undefined
}
/>
)}
diff --git a/client/src/app/[site]/funnels/components/FunnelRow.test.tsx b/client/src/app/[site]/funnels/components/FunnelRow.test.tsx
index 4bd904190..eb29e99d8 100644
--- a/client/src/app/[site]/funnels/components/FunnelRow.test.tsx
+++ b/client/src/app/[site]/funnels/components/FunnelRow.test.tsx
@@ -45,7 +45,7 @@ function renderRow() {
return render(
<QueryClientProvider client={client}>
<TooltipProvider>
- <FunnelRow funnel={funnel} index={1} />
+ <FunnelRow funnel={funnel} index={1} canWrite />
</TooltipProvider>
</QueryClientProvider>
);
diff --git a/client/src/app/[site]/funnels/components/FunnelRow.tsx b/client/src/app/[site]/funnels/components/FunnelRow.tsx
index e54f01a44..d03e180e5 100644
--- a/client/src/app/[site]/funnels/components/FunnelRow.tsx
+++ b/client/src/app/[site]/funnels/components/FunnelRow.tsx
@@ -20,9 +20,11 @@ import { resolvePropertyFilters, targetTypeToEventType } from "../../../../lib/e
interface FunnelRowProps {
funnel: SavedFunnel;
index: number;
+ /** funnels:write: edit, clone and delete. */
+ canWrite: boolean;
}
-export function FunnelRow({ funnel, index }: FunnelRowProps) {
+export function FunnelRow({ funnel, index, canWrite }: FunnelRowProps) {
const t = useExtracted();
const stepTypeLabels: Record<FunnelStepType, string> = {
@@ -123,56 +125,60 @@ export function FunnelRow({ funnel, index }: FunnelRowProps) {
<div className="flex items-center gap-4">
<div className="flex">
- {/* Edit button */}
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="ghost"
- size="icon"
- onClick={e => {
- e.stopPropagation();
- setIsEditModalOpen(true);
- }}
- >
- <Edit className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{t("Edit Funnel")}</TooltipContent>
- </Tooltip>
-
- {/* Clone button */}
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="ghost"
- size="icon"
- onClick={e => {
- e.stopPropagation();
- setIsCloneModalOpen(true);
- }}
- >
- <Copy className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{t("Clone Funnel")}</TooltipContent>
- </Tooltip>
-
- {/* Delete button */}
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="ghost"
- size="icon"
- onClick={e => {
- e.stopPropagation();
- setIsDeleteModalOpen(true);
- }}
- >
- <Trash2 className="h-4 w-4" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{t("Delete Funnel")}</TooltipContent>
- </Tooltip>
+ {canWrite && (
+ <>
+ {/* Edit button */}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={e => {
+ e.stopPropagation();
+ setIsEditModalOpen(true);
+ }}
+ >
+ <Edit className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{t("Edit Funnel")}</TooltipContent>
+ </Tooltip>
+
+ {/* Clone button */}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={e => {
+ e.stopPropagation();
+ setIsCloneModalOpen(true);
+ }}
+ >
+ <Copy className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{t("Clone Funnel")}</TooltipContent>
+ </Tooltip>
+
+ {/* Delete button */}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="icon"
+ onClick={e => {
+ e.stopPropagation();
+ setIsDeleteModalOpen(true);
+ }}
+ >
+ <Trash2 className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{t("Delete Funnel")}</TooltipContent>
+ </Tooltip>
+ </>
+ )}
<Button variant="ghost" size="icon" onClick={handleExpand}>
{expanded ? <ChevronUp strokeWidth={3} /> : <ChevronDown strokeWidth={3} />}
diff --git a/client/src/app/[site]/funnels/page.tsx b/client/src/app/[site]/funnels/page.tsx
index a1f6fdfd5..85241e783 100644
--- a/client/src/app/[site]/funnels/page.tsx
+++ b/client/src/app/[site]/funnels/page.tsx
@@ -12,6 +12,7 @@ import { SavedFunnel } from "../../../api/analytics/endpoints";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
import { ErrorState } from "../../../components/ErrorState";
import { NothingFound } from "../../../components/NothingFound";
+import { useCanOnSite } from "../../../hooks/usePermissions";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
import { SubHeader } from "../components/SubHeader/SubHeader";
import { CreateFunnelDialog } from "./components/CreateFunnel";
@@ -65,6 +66,7 @@ export default function FunnelsPage() {
const { site } = useStore();
const { data: funnels, isLoading, error } = useGetFunnels(site);
+ const canWrite = useCanOnSite("funnels:write");
const [searchQuery, setSearchQuery] = useState("");
// Filter funnels based on search query
@@ -96,7 +98,7 @@ export default function FunnelsPage() {
value={searchQuery}
onChange={e => setSearchQuery(e.target.value)}
/>
- <CreateFunnelDialog />
+ {canWrite && <CreateFunnelDialog />}
</div>
{isLoading || !funnels ? (
@@ -113,7 +115,7 @@ export default function FunnelsPage() {
) : filteredFunnels?.length ? (
<div className="space-y-4">
{filteredFunnels.map((funnel: SavedFunnel, index: number) => (
- <FunnelRow key={funnel.id} funnel={funnel} index={index} />
+ <FunnelRow key={funnel.id} funnel={funnel} index={index} canWrite={canWrite} />
))}
</div>
) : funnels?.length ? (
@@ -127,7 +129,7 @@ export default function FunnelsPage() {
icon={<Funnel className="w-10 h-10" />}
title={t("No funnels yet")}
description={<span>{t("Create your first funnel to track conversions through your site's user journey.")} <ExternalLink href="https://rybbit.com/docs/funnels">{t("Learn more")}</ExternalLink></span>}
- action={<CreateFunnelDialog />}
+ action={canWrite ? <CreateFunnelDialog /> : undefined}
/>
)}
</div>
diff --git a/client/src/app/[site]/goals/components/GoalCard.tsx b/client/src/app/[site]/goals/components/GoalCard.tsx
index 4d5026780..7a4aca7f3 100644
--- a/client/src/app/[site]/goals/components/GoalCard.tsx
+++ b/client/src/app/[site]/goals/components/GoalCard.tsx
@@ -37,6 +37,8 @@ import { GoalBarChartSkeleton } from "./skeleton";
interface GoalCardProps {
goal: Goal;
siteId: number;
+ /** goals:write: edit, clone and delete. */
+ canWrite: boolean;
timeSeries?: GoalTimeSeriesPoint[];
isLoadingTimeSeries: boolean;
}
@@ -154,7 +156,7 @@ function GoalMetricBarChart({
);
}
-export default function GoalCard({ goal, siteId, timeSeries, isLoadingTimeSeries }: GoalCardProps) {
+export default function GoalCard({ goal, siteId, canWrite, timeSeries, isLoadingTimeSeries }: GoalCardProps) {
const t = useExtracted();
const [isDeleteDialogOpen, setIsDeleteDialogOpen] = useState(false);
const [isEditModalOpen, setIsEditModalOpen] = useState(false);
@@ -252,33 +254,35 @@ export default function GoalCard({ goal, siteId, timeSeries, isLoadingTimeSeries
</div>
{/* Right section - Actions */}
<div className="flex shrink-0 justify-end gap-1 md:pl-4">
- <div onClick={e => e.stopPropagation()}>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button variant="ghost" size="smIcon" aria-label={t("Goal actions")}>
- <MoreHorizontal className="h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem onClick={() => setIsEditModalOpen(true)}>
- <Edit className="h-4 w-4" />
- {t("Edit Goal")}
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => setIsCloneModalOpen(true)}>
- <Copy className="h-4 w-4" />
- {t("Clone Goal")}
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <DropdownMenuItem
- onClick={() => setIsDeleteDialogOpen(true)}
- className="text-red-600 focus:text-red-600 dark:text-red-400 dark:focus:text-red-400"
- >
- <Trash2 className="h-4 w-4" />
- {t("Delete Goal")}
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
+ {canWrite && (
+ <div onClick={e => e.stopPropagation()}>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button variant="ghost" size="smIcon" aria-label={t("Goal actions")}>
+ <MoreHorizontal className="h-4 w-4" />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => setIsEditModalOpen(true)}>
+ <Edit className="h-4 w-4" />
+ {t("Edit Goal")}
+ </DropdownMenuItem>
+ <DropdownMenuItem onClick={() => setIsCloneModalOpen(true)}>
+ <Copy className="h-4 w-4" />
+ {t("Clone Goal")}
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ onClick={() => setIsDeleteDialogOpen(true)}
+ className="text-red-600 focus:text-red-600 dark:text-red-400 dark:focus:text-red-400"
+ >
+ <Trash2 className="h-4 w-4" />
+ {t("Delete Goal")}
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ )}
<Tooltip>
<TooltipTrigger asChild>
<Button variant="ghost" size="smIcon">
diff --git a/client/src/app/[site]/goals/components/GoalsList.tsx b/client/src/app/[site]/goals/components/GoalsList.tsx
index 629714d4f..48be72bb2 100644
--- a/client/src/app/[site]/goals/components/GoalsList.tsx
+++ b/client/src/app/[site]/goals/components/GoalsList.tsx
@@ -6,11 +6,13 @@ import { Goal, GoalTimeSeriesPoint } from "../../../../api/analytics/endpoints";
interface GoalsListProps {
goals: Goal[];
siteId: number;
+ /** goals:write: edit, clone and delete. */
+ canWrite: boolean;
timeSeriesByGoal: Map<number, GoalTimeSeriesPoint[]>;
isLoadingTimeSeries: boolean;
}
-export default function GoalsList({ goals, siteId, timeSeriesByGoal, isLoadingTimeSeries }: GoalsListProps) {
+export default function GoalsList({ goals, siteId, canWrite, timeSeriesByGoal, isLoadingTimeSeries }: GoalsListProps) {
return (
<div className="flex flex-col gap-3">
{goals.map(goal => (
@@ -18,6 +20,7 @@ export default function GoalsList({ goals, siteId, timeSeriesByGoal, isLoadingTi
key={goal.goalId}
goal={goal}
siteId={siteId}
+ canWrite={canWrite}
timeSeries={timeSeriesByGoal.get(goal.goalId)}
isLoadingTimeSeries={isLoadingTimeSeries}
/>
diff --git a/client/src/app/[site]/goals/page.tsx b/client/src/app/[site]/goals/page.tsx
index cb4feb78a..90cc12d58 100644
--- a/client/src/app/[site]/goals/page.tsx
+++ b/client/src/app/[site]/goals/page.tsx
@@ -9,6 +9,7 @@ import { BucketSelection } from "../../../components/BucketSelection";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
import { NothingFound } from "../../../components/NothingFound";
import { Pagination } from "../../../components/pagination";
+import { useCanOnSite } from "../../../hooks/usePermissions";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
import { useStore } from "../../../lib/store";
import { GOALS_PAGE_FILTERS } from "../../../lib/filterGroups";
@@ -71,6 +72,7 @@ export default function GoalsPage() {
useSetPageTitle("Goals");
const { site } = useStore();
+ const canWrite = useCanOnSite("goals:write");
const [searchQuery, setSearchQuery] = useState("");
const [pagination, setPagination] = useState({
pageIndex: 0, // TablePagination uses 0-based indexing
@@ -181,7 +183,7 @@ export default function GoalsPage() {
/>
<BucketSelection size="default" />
</div>
- <CreateGoalButton siteId={Number(site)} />
+ {canWrite && <CreateGoalButton siteId={Number(site)} />}
</div>
{/* if site is not loaded, show skeleton */}
{isLoading || !site ? (
@@ -202,7 +204,7 @@ export default function GoalsPage() {
<ExternalLink href="https://rybbit.com/docs/goals">{t("Learn more")}</ExternalLink>
</span>
}
- action={<CreateGoalButton siteId={Number(site)} />}
+ action={canWrite ? <CreateGoalButton siteId={Number(site)} /> : undefined}
/>
) : filteredGoals.length === 0 ? (
<NothingFound
@@ -215,6 +217,7 @@ export default function GoalsPage() {
<GoalsList
goals={filteredGoals}
siteId={Number(site)}
+ canWrite={canWrite}
timeSeriesByGoal={timeSeriesByGoal}
isLoadingTimeSeries={isLoadingGoalTimeSeries}
/>
diff --git a/client/src/app/[site]/main/components/MainSection/annotations/AnnotationFormDialog.tsx b/client/src/app/[site]/main/components/MainSection/annotations/AnnotationFormDialog.tsx
index 026f142ae..3eb3c369b 100644
--- a/client/src/app/[site]/main/components/MainSection/annotations/AnnotationFormDialog.tsx
+++ b/client/src/app/[site]/main/components/MainSection/annotations/AnnotationFormDialog.tsx
@@ -63,7 +63,7 @@ export function AnnotationFormDialog({
const t = useExtracted();
const { site } = useStore();
const timezone = getTimezone();
- const { isAdmin } = useAnnotationPermissions();
+ const { canManageAll } = useAnnotationPermissions();
const createAnnotation = useCreateAnnotation();
const updateAnnotation = useUpdateAnnotation();
@@ -322,7 +322,7 @@ export function AnnotationFormDialog({
</FormItem>
)}
/>
- {isAdmin && (
+ {canManageAll && (
<FormField
control={form.control}
name="scope"
diff --git a/client/src/app/[site]/main/components/MainSection/annotations/useAnnotationPermissions.ts b/client/src/app/[site]/main/components/MainSection/annotations/useAnnotationPermissions.ts
index 0e8c75c83..d837c498b 100644
--- a/client/src/app/[site]/main/components/MainSection/annotations/useAnnotationPermissions.ts
+++ b/client/src/app/[site]/main/components/MainSection/annotations/useAnnotationPermissions.ts
@@ -1,41 +1,38 @@
"use client";
import type { Annotation } from "@rybbit/shared";
-import { useQuery } from "@tanstack/react-query";
-import { getUserOrganizations, USER_ORGANIZATIONS_QUERY_KEY } from "@/api/admin/endpoints";
import { useGetSite } from "@/api/admin/hooks/useSites";
+import { useOrgPermissions, useSitePermissions } from "@/hooks/usePermissions";
import { authClient } from "@/lib/auth";
import { useStore } from "@/lib/store";
/**
- * Who may do what with annotations on the current site. Mirrors the server
- * rules: members create and manage their own, admins and owners manage all,
- * and public or private-link viewers only read.
+ * Who may do what with annotations on the current site, from the server's
+ * permission lists: annotations:write creates and manages your own site
+ * annotations; annotations:manage on the site manages everyone's site
+ * annotations, and in the organization, the organization-wide ones. Public and
+ * private-link viewers only read.
*/
export function useAnnotationPermissions() {
const { site, privateKey } = useStore();
const session = authClient.useSession();
const userId = session.data?.user.id;
+ // The private-link view is read-only by design, even for members.
const signedIn = !!userId && !privateKey;
- const { data: siteData } = useGetSite(site, { enabled: signedIn });
- // A signed-in visitor on someone else's public dashboard has a session but
- // no membership; the organization list tells the two apart.
- const { data: organizations } = useQuery({
- queryKey: [USER_ORGANIZATIONS_QUERY_KEY],
- queryFn: getUserOrganizations,
- enabled: signedIn,
- });
+ const { data: siteData } = useGetSite(site);
+ const sitePermissions = useSitePermissions(site);
+ const orgPermissions = useOrgPermissions(siteData?.organizationId ?? undefined);
- const isAdmin = signedIn && !!siteData?.isOwner;
- const isMember =
- isAdmin ||
- (!!siteData?.organizationId && !!organizations?.some(org => org.id === siteData.organizationId));
+ const canWrite = signedIn && sitePermissions.can("annotations:write");
+ const canManageSite = signedIn && sitePermissions.can("annotations:manage");
+ const canManageAll = signedIn && !!siteData?.organizationId && orgPermissions.can("annotations:manage");
return {
- canCreate: signedIn && isMember,
- isAdmin,
+ canCreate: canWrite,
+ /** May create and edit organization-wide annotations. */
+ canManageAll,
canManage: (annotation: Annotation) =>
- isAdmin || (annotation.siteId !== null && signedIn && annotation.userId === userId),
+ annotation.siteId === null ? canManageAll : canManageSite || (canWrite && annotation.userId === userId),
};
}
diff --git a/client/src/app/[site]/main/components/sections/SearchConsole.tsx b/client/src/app/[site]/main/components/sections/SearchConsole.tsx
index a4e51c162..a7cc53ba1 100644
--- a/client/src/app/[site]/main/components/sections/SearchConsole.tsx
+++ b/client/src/app/[site]/main/components/sections/SearchConsole.tsx
@@ -3,7 +3,6 @@ import round from "lodash/round";
import { Expand, Info, SquareArrowOutUpRight } from "lucide-react";
import { useExtracted } from "next-intl";
import { useState } from "react";
-import { useCurrentSite } from "../../../../../api/admin/hooks/useSites";
import { GSCDimension } from "../../../../../api/gsc/endpoints";
import { useConnectGSC } from "../../../../../api/gsc/hooks/useConnectGSC";
import { useGetGSCConnection } from "../../../../../api/gsc/hooks/useGetGSCConnection";
@@ -12,6 +11,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../../compone
import { Button } from "../../../../../components/ui/button";
import { Card, CardContent, CardLoader } from "../../../../../components/ui/card";
import { ScrollArea } from "../../../../../components/ui/scroll-area";
+import { useCanOnSite } from "../../../../../hooks/usePermissions";
import { formatter, getCountryName, truncateString } from "../../../../../lib/utils";
import { CountryFlag } from "../../../components/shared/icons/CountryFlag";
import { DeviceIcon } from "../../../components/shared/icons/Device";
@@ -22,13 +22,12 @@ type Tab = "queries" | "pages" | "countries" | "devices";
function ConnectPrompt() {
const { mutate: connect, isPending } = useConnectGSC();
- const { site } = useCurrentSite();
const t = useExtracted();
- // Connecting completes an OAuth flow that requires site admin access on the
- // server. Members would be stranded on a 403 after Google consent, so show
+ // Connecting completes an OAuth flow that requires gsc:write on the server.
+ // Anyone without it would be stranded on a 403 after Google consent, so show
// them an explanation instead of a button they can't complete.
- const canConnect = site?.isOwner ?? false;
+ const canConnect = useCanOnSite("gsc:write");
return (
<div className="flex flex-col items-center justify-center mt-12 gap-4">
diff --git a/client/src/app/[site]/performance/components/EnableWebVitals.tsx b/client/src/app/[site]/performance/components/EnableWebVitals.tsx
index 06037c145..4198b5dea 100644
--- a/client/src/app/[site]/performance/components/EnableWebVitals.tsx
+++ b/client/src/app/[site]/performance/components/EnableWebVitals.tsx
@@ -9,6 +9,7 @@ import { updateSiteConfig } from "../../../../api/admin/endpoints";
import { useGetSite } from "../../../../api/admin/hooks/useSites";
import { Alert, AlertDescription, AlertTitle } from "../../../../components/ui/alert";
import { Button } from "../../../../components/ui/button";
+import { useCanOnSite } from "../../../../hooks/usePermissions";
export function EnableWebVitals() {
const t = useExtracted();
@@ -16,6 +17,7 @@ export function EnableWebVitals() {
const siteId = Number(params.site);
const { data: siteMetadata, refetch } = useGetSite(siteId);
const [isEnabling, setIsEnabling] = useState(false);
+ const canConfigure = useCanOnSite("sites:configure", siteId);
if (siteMetadata?.webVitals) return null;
@@ -47,9 +49,13 @@ export function EnableWebVitals() {
{t("Web Vitals collection provides Core Web Vitals metrics like LCP, CLS, and INP.")} <b>{t("Note:")}</b>{" "}
{t("Enabling Web Vitals will increase your event usage.")}
</div>
- <Button size="sm" variant="success" loading={isEnabling} onClick={enable}>
- {t("Enable")}
- </Button>
+ {canConfigure ? (
+ <Button size="sm" variant="success" loading={isEnabling} onClick={enable}>
+ {t("Enable")}
+ </Button>
+ ) : (
+ <p>{t("Ask a site admin to enable it.")}</p>
+ )}
</AlertDescription>
</div>
</div>
diff --git a/client/src/app/[site]/replay/components/EnableSessionReplay.tsx b/client/src/app/[site]/replay/components/EnableSessionReplay.tsx
index 9fa66dc49..f5a74b4db 100644
--- a/client/src/app/[site]/replay/components/EnableSessionReplay.tsx
+++ b/client/src/app/[site]/replay/components/EnableSessionReplay.tsx
@@ -9,6 +9,7 @@ import { updateSiteConfig } from "../../../../api/admin/endpoints";
import { useGetSite } from "../../../../api/admin/hooks/useSites";
import { Alert, AlertDescription, AlertTitle } from "../../../../components/ui/alert";
import { Button } from "../../../../components/ui/button";
+import { useCanOnSite } from "../../../../hooks/usePermissions";
import { planIncludesReplay } from "../../../../lib/subscription/planUtils";
import { useStripeSubscription } from "../../../../lib/subscription/useStripeSubscription";
import { IS_CLOUD } from "../../../../lib/const";
@@ -20,6 +21,7 @@ export function EnableSessionReplay() {
const { data: siteMetadata, isLoading, refetch } = useGetSite(siteId);
const { data: subscription } = useStripeSubscription();
const [isEnabling, setIsEnabling] = useState(false);
+ const canConfigure = useCanOnSite("sites:configure", siteId);
const canEnableReplay = !IS_CLOUD || planIncludesReplay(subscription);
@@ -54,9 +56,13 @@ export function EnableSessionReplay() {
{t("and the client will send significantly more and larger payloads.")}{" "}
<b>{t("Only enable this if you will actually use it.")}</b>
</div>
- <Button size="sm" variant="success" loading={isEnabling} onClick={enable}>
- {t("Enable")}
- </Button>
+ {canConfigure ? (
+ <Button size="sm" variant="success" loading={isEnabling} onClick={enable}>
+ {t("Enable")}
+ </Button>
+ ) : (
+ <p>{t("Ask a site admin to enable it.")}</p>
+ )}
</AlertDescription>
</div>
</div>
diff --git a/client/src/app/[site]/replay/components/ReplayCard.tsx b/client/src/app/[site]/replay/components/ReplayCard.tsx
index 56eaf740c..a8a62ec85 100644
--- a/client/src/app/[site]/replay/components/ReplayCard.tsx
+++ b/client/src/app/[site]/replay/components/ReplayCard.tsx
@@ -4,6 +4,7 @@ import { DateTime } from "luxon";
import { useExtracted } from "next-intl";
import { useState } from "react";
import { useDateTimeFormat } from "../../../../hooks/useDateTimeFormat";
+import { useCanOnSite } from "../../../../hooks/usePermissions";
import { useDeleteSessionReplay } from "../../../../api/analytics/hooks/sessionReplay/useDeleteSessionReplay";
import { Avatar } from "../../../../components/Avatar";
import { IdentifiedBadge } from "../../../../components/IdentifiedBadge";
@@ -74,6 +75,7 @@ export function ReplayCard({ replay, onSelect }: { replay: SessionReplayListItem
);
const [isDialogOpen, setIsDialogOpen] = useState(false);
const deleteSessionReplay = useDeleteSessionReplay();
+ const canDelete = useCanOnSite("replay:delete");
const startTime = DateTime.fromSQL(replay.start_time, { zone: "utc" }).setZone(getTimezone());
const duration = replay.duration_ms ? Math.ceil(replay.duration_ms / 1000) : null;
const isSelected = sessionId === replay.session_id;
@@ -130,45 +132,47 @@ export function ReplayCard({ replay, onSelect }: { replay: SessionReplayListItem
</span>
{replay.identified_user_id && <IdentifiedBadge traits={replay.traits} userId={replay.identified_user_id} />}
- <AlertDialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
- <AlertDialogTrigger asChild>
- <Button
- variant="ghost"
- size="sm"
- aria-label={t("Delete Session Replay")}
- className="ml-auto -mr-1 opacity-0 group-hover:opacity-100 focus-visible:opacity-100 transition-opacity h-6 w-6 p-0 text-neutral-500 hover:bg-red-500/10 hover:text-red-500 dark:hover:text-red-400"
- onClick={e => {
- e.stopPropagation();
- setIsDialogOpen(true);
- }}
- >
- <Trash2 className="w-3.5 h-3.5" />
- </Button>
- </AlertDialogTrigger>
- <AlertDialogContent onClick={e => e.stopPropagation()}>
- <AlertDialogHeader>
- <AlertDialogTitle>{t("Delete Session Replay")}</AlertDialogTitle>
- <AlertDialogDescription>
- {t(
- "Are you sure you want to delete this session replay? This action cannot be undone and will permanently remove the replay data."
- )}
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel onClick={e => e.stopPropagation()}>{t("Cancel")}</AlertDialogCancel>
- <AlertDialogAction
- variant="destructive"
+ {canDelete && (
+ <AlertDialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
+ <AlertDialogTrigger asChild>
+ <Button
+ variant="ghost"
+ size="sm"
+ aria-label={t("Delete Session Replay")}
+ className="ml-auto -mr-1 opacity-0 group-hover:opacity-100 focus-visible:opacity-100 transition-opacity h-6 w-6 p-0 text-neutral-500 hover:bg-red-500/10 hover:text-red-500 dark:hover:text-red-400"
onClick={e => {
e.stopPropagation();
- handleDelete();
+ setIsDialogOpen(true);
}}
- disabled={deleteSessionReplay.isPending}
>
- {deleteSessionReplay.isPending ? t("Deleting...") : t("Delete")}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
+ <Trash2 className="w-3.5 h-3.5" />
+ </Button>
+ </AlertDialogTrigger>
+ <AlertDialogContent onClick={e => e.stopPropagation()}>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{t("Delete Session Replay")}</AlertDialogTitle>
+ <AlertDialogDescription>
+ {t(
+ "Are you sure you want to delete this session replay? This action cannot be undone and will permanently remove the replay data."
+ )}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel onClick={e => e.stopPropagation()}>{t("Cancel")}</AlertDialogCancel>
+ <AlertDialogAction
+ variant="destructive"
+ onClick={e => {
+ e.stopPropagation();
+ handleDelete();
+ }}
+ disabled={deleteSessionReplay.isPending}
+ >
+ {deleteSessionReplay.isPending ? t("Deleting...") : t("Delete")}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )}
</div>
{/* Page path */}
diff --git a/client/src/app/[site]/user/[userId]/components/UserActions.tsx b/client/src/app/[site]/user/[userId]/components/UserActions.tsx
index 758abb59a..baba8ea65 100644
--- a/client/src/app/[site]/user/[userId]/components/UserActions.tsx
+++ b/client/src/app/[site]/user/[userId]/components/UserActions.tsx
@@ -7,6 +7,7 @@ import { useState } from "react";
import { UserInfo } from "@/api/analytics/endpoints";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { useSitePermissions } from "@/hooks/usePermissions";
import { DeleteUserDialog } from "./DeleteUserDialog";
import { IdentifyUserDialog } from "./IdentifyUserDialog";
@@ -19,34 +20,42 @@ export function UserActions({ userId, data }: UserActionsProps) {
const t = useExtracted();
const [identifyOpen, setIdentifyOpen] = useState(false);
const [deleteOpen, setDeleteOpen] = useState(false);
+ const { can } = useSitePermissions();
const isIdentified = !!data.identified_user_id;
+ const canWriteUsers = can("users:write");
+ const canDelete = can("users:delete");
return (
<div className="flex items-center gap-1">
- {!isIdentified && (
+ {canWriteUsers && !isIdentified && (
<Button size="sm" onClick={() => setIdentifyOpen(true)}>
<UserPlus className="h-3.5 w-3.5 mr-1.5" />
{t("Identify User")}
</Button>
)}
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="ghost"
- size="smIcon"
- aria-label={t("Delete User")}
- className="text-neutral-500 hover:bg-red-500/10 hover:text-red-500 dark:hover:text-red-400"
- onClick={() => setDeleteOpen(true)}
- >
- <Trash2 className="w-3.5 h-3.5" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>{t("Delete User")}</TooltipContent>
- </Tooltip>
-
- <IdentifyUserDialog anonymousId={data.user_id || userId} open={identifyOpen} onOpenChange={setIdentifyOpen} />
- <DeleteUserDialog userId={userId} open={deleteOpen} onOpenChange={setDeleteOpen} />
+ {canDelete && (
+ <>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ variant="ghost"
+ size="smIcon"
+ aria-label={t("Delete User")}
+ className="text-neutral-500 hover:bg-red-500/10 hover:text-red-500 dark:hover:text-red-400"
+ onClick={() => setDeleteOpen(true)}
+ >
+ <Trash2 className="w-3.5 h-3.5" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{t("Delete User")}</TooltipContent>
+ </Tooltip>
+ <DeleteUserDialog userId={userId} open={deleteOpen} onOpenChange={setDeleteOpen} />
+ </>
+ )}
+ {canWriteUsers && (
+ <IdentifyUserDialog anonymousId={data.user_id || userId} open={identifyOpen} onOpenChange={setIdentifyOpen} />
+ )}
</div>
);
}
diff --git a/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx b/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx
index 3a77f08f3..0f4b22d74 100644
--- a/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx
+++ b/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx
@@ -10,8 +10,8 @@ import { UserInfo, UserSessionCountResponse } from "../../../../../api/analytics
import { ChannelIcon, extractDomain, getDisplayName } from "../../../../../components/Channel";
import { Favicon } from "../../../../../components/Favicon";
import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../../components/ui/tooltip";
+import { useCanOnSite } from "../../../../../hooks/usePermissions";
import { useConfigs } from "../../../../../lib/configs";
-import { userStore } from "../../../../../lib/userStore";
import { PerformanceMetric } from "../../../performance/performanceStore";
import {
formatMetricValue,
@@ -38,7 +38,7 @@ const VITALS_ORDER: PerformanceMetric[] = ["lcp", "cls", "inp", "fcp", "ttfb"];
export function UserSidebar({ data, isLoading, sessionCount, isLoadingCalendar, getRegionName }: UserSidebarProps) {
const t = useExtracted();
const { configs } = useConfigs();
- const { user } = userStore();
+ const canEditTraits = useCanOnSite("users:write");
const [traitsOpen, setTraitsOpen] = useState(false);
const isIdentified = !!data?.identified_user_id;
@@ -194,12 +194,12 @@ export function UserSidebar({ data, isLoading, sessionCount, isLoadingCalendar,
)}
{/* User Traits (identified users only) */}
- {isIdentified && data && (customTraits.length > 0 || !!user) && (
+ {isIdentified && data && (customTraits.length > 0 || canEditTraits) && (
<SidebarCard>
<SidebarHeader
title={t("User Traits")}
right={
- user ? (
+ canEditTraits ? (
<Button
variant="ghost"
size="smIcon"
diff --git a/client/src/app/admin/components/organizations/EditOrganizationMemberDialog.tsx b/client/src/app/admin/components/organizations/EditOrganizationMemberDialog.tsx
index ecb2f841e..13f68dcc6 100644
--- a/client/src/app/admin/components/organizations/EditOrganizationMemberDialog.tsx
+++ b/client/src/app/admin/components/organizations/EditOrganizationMemberDialog.tsx
@@ -1,5 +1,6 @@
"use client";
+import type { OrgRole } from "@rybbit/shared";
import { useQueryClient } from "@tanstack/react-query";
import { DateTime } from "luxon";
import { useExtracted } from "next-intl";
@@ -10,6 +11,7 @@ import {
useDeleteAdminOrganizationMember,
useUpdateAdminOrganizationMember,
} from "@/api/admin/hooks/useAdminOrganizations";
+import { RoleSelect } from "@/app/settings/organization/components/RoleSelect";
import {
AlertDialog,
AlertDialogAction,
@@ -38,6 +40,7 @@ import { Skeleton } from "@/components/ui/skeleton";
import { Switch } from "@/components/ui/switch";
import { toast } from "@/components/ui/sonner";
import { authClient } from "@/lib/auth";
+import { isAdminRole, ORG_ROLES } from "@/lib/roles";
import { userStore } from "@/lib/userStore";
interface EditOrganizationMemberDialogProps {
@@ -63,7 +66,7 @@ export function EditOrganizationMemberDialog({
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [systemRole, setSystemRole] = useState<"user" | "admin">("user");
- const [memberRole, setMemberRole] = useState<"owner" | "admin" | "member">("member");
+ const [memberRole, setMemberRole] = useState<OrgRole>("member");
const [restricted, setRestricted] = useState(false);
const [siteIds, setSiteIds] = useState<number[]>([]);
const [banned, setBanned] = useState(false);
@@ -96,7 +99,9 @@ export function EditOrganizationMemberDialog({
toast.error(t("Name and email are required"));
return;
}
- if (memberRole === "member" && restricted && siteIds.length === 0) {
+ // Owners and admins reach every site, so only the other roles can be restricted.
+ const restrictable = !isAdminRole(memberRole);
+ if (restrictable && restricted && siteIds.length === 0) {
toast.error(t("Select at least one site or disable site restrictions"));
return;
}
@@ -118,8 +123,8 @@ export function EditOrganizationMemberDialog({
await updateMembership.mutateAsync({
role: memberRole,
- hasRestrictedSiteAccess: memberRole === "member" && restricted,
- siteIds: memberRole === "member" && restricted ? siteIds : [],
+ hasRestrictedSiteAccess: restrictable && restricted,
+ siteIds: restrictable && restricted ? siteIds : [],
});
if (value.user.id !== currentUserId) {
@@ -213,21 +218,17 @@ export function EditOrganizationMemberDialog({
</Select>
</div>
<div className="space-y-2">
- <Label>{t("Organization role")}</Label>
- <Select value={memberRole} onValueChange={role => setMemberRole(role as typeof memberRole)}>
- <SelectTrigger>
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="owner">{t("Owner")}</SelectItem>
- <SelectItem value="admin">{t("Admin")}</SelectItem>
- <SelectItem value="member">{t("Member")}</SelectItem>
- </SelectContent>
- </Select>
+ <Label htmlFor="admin-member-org-role">{t("Organization role")}</Label>
+ <RoleSelect
+ id="admin-member-org-role"
+ value={memberRole}
+ roles={ORG_ROLES}
+ onValueChange={setMemberRole}
+ />
</div>
</section>
- {memberRole === "member" && (
+ {!isAdminRole(memberRole) && (
<section className="space-y-3 border-t border-neutral-150 pt-4 dark:border-neutral-800">
<div className="flex items-center justify-between gap-4">
<div>
diff --git a/client/src/app/admin/components/users/AddToOrganizationDialog.tsx b/client/src/app/admin/components/users/AddToOrganizationDialog.tsx
index 2c4ed083a..04a128424 100644
--- a/client/src/app/admin/components/users/AddToOrganizationDialog.tsx
+++ b/client/src/app/admin/components/users/AddToOrganizationDialog.tsx
@@ -1,5 +1,8 @@
"use client";
+import type { OrgRole } from "@rybbit/shared";
+
+import { RoleSelect } from "@/app/settings/organization/components/RoleSelect";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -10,11 +13,11 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useState } from "react";
import { toast } from "@/components/ui/sonner";
import { Alert } from "@/components/ui/alert";
import { useAddUserToOrganization } from "@/api/admin/hooks/useOrganizations";
+import { ORG_ROLES } from "@/lib/roles";
import { useExtracted } from "next-intl";
import { RemoteOrganizationCombobox } from "../shared/RemoteOrganizationCombobox";
@@ -28,7 +31,7 @@ interface AddToOrganizationDialogProps {
export function AddToOrganizationDialog({ userEmail, userId, open, onOpenChange }: AddToOrganizationDialogProps) {
const [organizationId, setOrganizationId] = useState<string>("");
const [organizationName, setOrganizationName] = useState<string>("");
- const [role, setRole] = useState<"admin" | "member" | "owner">("member");
+ const [role, setRole] = useState<OrgRole>("member");
const [error, setError] = useState("");
const t = useExtracted();
@@ -87,16 +90,7 @@ export function AddToOrganizationDialog({ userEmail, userId, open, onOpenChange
</div>
<div className="grid gap-2">
<Label htmlFor="role">{t("Role")}</Label>
- <Select value={role} onValueChange={value => setRole(value as "admin" | "member" | "owner")}>
- <SelectTrigger id="role">
- <SelectValue placeholder={t("Select a role")} />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="owner">{t("Owner")}</SelectItem>
- <SelectItem value="admin">{t("Admin")}</SelectItem>
- <SelectItem value="member">{t("Member")}</SelectItem>
- </SelectContent>
- </Select>
+ <RoleSelect id="role" value={role} roles={ORG_ROLES} onValueChange={setRole} />
</div>
{error && <Alert variant="destructive">{error}</Alert>}
</div>
diff --git a/client/src/app/components/AddSite.tsx b/client/src/app/components/AddSite.tsx
index b4af43eaa..3ee896c99 100644
--- a/client/src/app/components/AddSite.tsx
+++ b/client/src/app/components/AddSite.tsx
@@ -63,7 +63,16 @@ interface CreateToggle {
hidden?: boolean;
}
-export function AddSite({ trigger, disabled }: { trigger?: React.ReactNode; disabled?: boolean }) {
+export function AddSite({
+ trigger,
+ disabled,
+ disabledReason,
+}: {
+ trigger?: React.ReactNode;
+ disabled?: boolean;
+ /** Shown in a tooltip while `disabled`, e.g. when the user can't add sites to this organization. */
+ disabledReason?: string;
+}) {
const { setSite } = useStore();
const router = useRouter();
const t = useExtracted();
@@ -289,6 +298,25 @@ export function AddSite({ trigger, disabled }: { trigger?: React.ReactNode; disa
);
};
+ if (disabled && disabledReason) {
+ return (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ {/* A disabled button gets no pointer events, so the tooltip hangs off this wrapper. */}
+ <span tabIndex={0} className="inline-flex">
+ {trigger || (
+ <Button disabled>
+ <Plus className="h-4 w-4" />
+ {t("Add Site")}
+ </Button>
+ )}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>{disabledReason}</TooltipContent>
+ </Tooltip>
+ );
+ }
+
if (subscription?.status !== "active" && subscription?.status !== "trialing" && IS_CLOUD) {
return (
<Tooltip>
diff --git a/client/src/app/components/PlanRequired.test.tsx b/client/src/app/components/PlanRequired.test.tsx
index 51819a1b5..ec7b5cf35 100644
--- a/client/src/app/components/PlanRequired.test.tsx
+++ b/client/src/app/components/PlanRequired.test.tsx
@@ -5,8 +5,8 @@ import { PlanRequiredNotice, useCheckoutReturn } from "./PlanRequired";
const mocks = vi.hoisted(() => ({
useStripeSubscription: vi.fn(),
- organizations: { data: [{ id: "org_b", role: "owner" }], isLoading: false } as {
- data: { id: string; role: string }[] | undefined;
+ organizations: { data: [{ id: "org_b", role: "owner", permissions: ["billing:manage"] }], isLoading: false } as {
+ data: { id: string; role: string; permissions: string[] }[] | undefined;
isLoading: boolean;
},
search: "",
@@ -23,7 +23,7 @@ vi.mock("@/api/admin/hooks/useOrganizationMembers", () => ({ useOrganizationMemb
vi.mock("@/lib/subscription/useStripeSubscription", () => ({ useStripeSubscription: mocks.useStripeSubscription }));
beforeEach(() => {
- mocks.organizations = { data: [{ id: "org_b", role: "owner" }], isLoading: false };
+ mocks.organizations = { data: [{ id: "org_b", role: "owner", permissions: ["billing:manage"] }], isLoading: false };
mocks.useStripeSubscription.mockReturnValue({ data: { trialEligible: true }, isLoading: false });
mocks.search = "";
});
diff --git a/client/src/app/components/PlanRequired.tsx b/client/src/app/components/PlanRequired.tsx
index 0f29dfa76..ae4fd2178 100644
--- a/client/src/app/components/PlanRequired.tsx
+++ b/client/src/app/components/PlanRequired.tsx
@@ -29,10 +29,11 @@ export function usePlanPrompt(organizationId: string | undefined) {
// This organization's subscription, not the active one's: a dashboard can belong to another
// organization the person is in, and only that one's history decides whether a trial is on offer.
const { data: subscription, isLoading: isLoadingSubscription } = useStripeSubscription(organizationId);
- const role = organizations?.find(org => org.id === organizationId)?.role;
+ const permissions = organizations?.find(org => org.id === organizationId)?.permissions;
return {
isLoading: isLoadingOrganizations || isLoadingSubscription,
- isOwner: role === "owner",
+ // Starting a plan is billing, which the server lets owners (and system admins) do.
+ isOwner: !!permissions?.includes("billing:manage"),
trialEligible: subscription?.trialEligible !== false,
};
}
diff --git a/client/src/app/settings/billing/layout.tsx b/client/src/app/settings/billing/layout.tsx
index 4348aba1c..7b6c65e51 100644
--- a/client/src/app/settings/billing/layout.tsx
+++ b/client/src/app/settings/billing/layout.tsx
@@ -1,16 +1,10 @@
"use client";
import { useExtracted } from "next-intl";
-import { authClient } from "../../../lib/auth";
+import { OrgPermissionGate } from "../components/OrgPermissionGate";
export default function BillingLayout({ children }: { children: React.ReactNode }) {
const t = useExtracted();
- const { data: session } = authClient.useSession();
- const { data: activeOrg } = authClient.useActiveOrganization();
- const currentMember = activeOrg?.members?.find(
- (m) => m.userId === session?.user?.id
- );
- const isMember = currentMember?.role === "member";
return (
<div className="space-y-5">
@@ -21,13 +15,12 @@ export default function BillingLayout({ children }: { children: React.ReactNode
</p>
</div>
- {isMember ? (
- <div className="rounded-lg border border-neutral-200 dark:border-neutral-800 p-6 text-center text-neutral-500 dark:text-neutral-400">
- {t("You don't have permission to view subscription settings.")}
- </div>
- ) : (
+ <OrgPermissionGate
+ permission="billing:manage"
+ deniedMessage={t("You don't have permission to view subscription settings.")}
+ >
<div className="mt-6">{children}</div>
- )}
+ </OrgPermissionGate>
</div>
);
}
diff --git a/client/src/app/settings/billing/page.tsx b/client/src/app/settings/billing/page.tsx
index 707467f59..3759d00e5 100644
--- a/client/src/app/settings/billing/page.tsx
+++ b/client/src/app/settings/billing/page.tsx
@@ -12,6 +12,7 @@ import { OverridePlan } from "../../../components/subscription/OverridePlan";
import { CustomPlan } from "../../../components/subscription/CustomPlan";
import { Building } from "lucide-react";
import { useExtracted } from "next-intl";
+import { useCanInOrg } from "@/hooks/usePermissions";
import { authClient } from "@/lib/auth";
import { useEffect } from "react";
import { AppSumoPlan } from "../../../components/subscription/AppSumoPlan";
@@ -31,9 +32,7 @@ export default function OrganizationBillingPage() {
}
}, [session?.user?.email]);
- // Check if the current user is an owner by looking at the members in the active organization
- const currentUserMember = activeOrg?.members?.find(member => member.userId === session?.user?.id);
- const isOwner = currentUserMember?.role === "owner";
+ const canManageBilling = useCanInOrg("billing:manage", activeOrg?.id);
const isLoading = isLoadingSubscription || isPending;
@@ -43,7 +42,7 @@ export default function OrganizationBillingPage() {
return <NoOrganization message={t("You need to select an organization to manage your subscription.")} />;
}
- if (!isOwner) {
+ if (!canManageBilling) {
return (
<Card className="p-6 flex flex-col items-center text-center w-full">
<div className="mx-auto w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center mb-4">
diff --git a/client/src/app/settings/components/OrgPermissionGate.tsx b/client/src/app/settings/components/OrgPermissionGate.tsx
new file mode 100644
index 000000000..5c6c6cab5
--- /dev/null
+++ b/client/src/app/settings/components/OrgPermissionGate.tsx
@@ -0,0 +1,43 @@
+"use client";
+
+import type { Permission } from "@rybbit/shared";
+import { useExtracted } from "next-intl";
+import { useOrgPermissions } from "../../../hooks/usePermissions";
+import { authClient } from "../../../lib/auth";
+
+/**
+ * Shows a settings section only to users whose role in the active organization
+ * holds `permission`. It waits for the session and the organization list rather
+ * than flashing the denial, and leaves "no organization" to the page itself.
+ */
+export function OrgPermissionGate({
+ permission,
+ deniedMessage,
+ children,
+}: {
+ permission: Permission;
+ deniedMessage: string;
+ children: React.ReactNode;
+}) {
+ const t = useExtracted();
+ const { data: session } = authClient.useSession();
+ const { can, isLoading } = useOrgPermissions();
+
+ if (isLoading) {
+ return (
+ <div className="flex justify-center py-8">
+ <div className="animate-pulse">{t("Loading organization...")}</div>
+ </div>
+ );
+ }
+
+ if (session?.session.activeOrganizationId && !can(permission)) {
+ return (
+ <div className="rounded-lg border border-neutral-200 dark:border-neutral-800 p-6 text-center text-neutral-500 dark:text-neutral-400">
+ {deniedMessage}
+ </div>
+ );
+ }
+
+ return <>{children}</>;
+}
diff --git a/client/src/app/settings/organization/components/CreateUserDialog.tsx b/client/src/app/settings/organization/components/CreateUserDialog.tsx
index d4b569964..a59f7ef64 100644
--- a/client/src/app/settings/organization/components/CreateUserDialog.tsx
+++ b/client/src/app/settings/organization/components/CreateUserDialog.tsx
@@ -1,5 +1,6 @@
"use client";
+import type { OrgRole } from "@rybbit/shared";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -12,7 +13,6 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { UserPlus } from "lucide-react";
import { useExtracted } from "next-intl";
import { useState } from "react";
@@ -20,18 +20,21 @@ import { toast } from "@/components/ui/sonner";
import { Alert } from "../../../../components/ui/alert";
import { validateEmail } from "../../../../lib/auth-utils";
import { useCreateUserInOrganization } from "../../../../api/admin/hooks/useOrganizations";
+import { RoleSelect } from "./RoleSelect";
interface CreateUserDialogProps {
organizationId: string;
onSuccess: () => void;
+ /** Roles the current user may give, from the server. */
+ assignableRoles: OrgRole[];
}
-export function CreateUserDialog({ organizationId, onSuccess }: CreateUserDialogProps) {
+export function CreateUserDialog({ organizationId, onSuccess, assignableRoles }: CreateUserDialogProps) {
const t = useExtracted();
const [email, setEmail] = useState("");
const [name, setName] = useState("");
const [password, setPassword] = useState("");
- const [role, setRole] = useState<"admin" | "member" | "owner">("member");
+ const [role, setRole] = useState<OrgRole>("member");
const [open, setOpen] = useState(false);
const [error, setError] = useState("");
@@ -126,16 +129,7 @@ export function CreateUserDialog({ organizationId, onSuccess }: CreateUserDialog
</div>
<div className="grid gap-2">
<Label htmlFor="role">{t("Role")}</Label>
- <Select value={role} onValueChange={value => setRole(value as "admin" | "member" | "owner")}>
- <SelectTrigger>
- <SelectValue placeholder={t("Select a role")} />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="owner">{t("Owner")}</SelectItem>
- <SelectItem value="admin">{t("Admin")}</SelectItem>
- <SelectItem value="member">{t("Member")}</SelectItem>
- </SelectContent>
- </Select>
+ <RoleSelect id="role" value={role} roles={assignableRoles} onValueChange={setRole} />
</div>
{error && <Alert variant="destructive">{error}</Alert>}
</div>
diff --git a/client/src/app/settings/organization/components/EditMemberDialog.tsx b/client/src/app/settings/organization/components/EditMemberDialog.tsx
index 6809c2315..8d4f422c1 100644
--- a/client/src/app/settings/organization/components/EditMemberDialog.tsx
+++ b/client/src/app/settings/organization/components/EditMemberDialog.tsx
@@ -1,5 +1,6 @@
"use client";
+import type { OrgRole, SiteGrantRole } from "@rybbit/shared";
import { useQueryClient } from "@tanstack/react-query";
import { useExtracted } from "next-intl";
import { useEffect, useState } from "react";
@@ -28,9 +29,10 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { authClient } from "@/lib/auth";
+import { isAdminRole, siteRolesAbove } from "@/lib/roles";
+import { RoleSelect, SiteRoleSelect } from "./RoleSelect";
import { SiteAccessMultiSelect } from "./SiteAccessMultiSelect";
type Member = GetOrganizationMembersResponse["data"][0];
@@ -40,28 +42,41 @@ interface EditMemberDialogProps {
open: boolean;
onClose: () => void;
onSuccess: () => void;
- isOwner: boolean;
+ /** Roles the current user may give, from the server; empty when they can't change roles. */
+ assignableRoles: OrgRole[];
}
-export function EditMemberDialog({ member, open, onClose, onSuccess, isOwner }: EditMemberDialogProps) {
+export function EditMemberDialog({ member, open, onClose, onSuccess, assignableRoles }: EditMemberDialogProps) {
const { data: activeOrganization } = authClient.useActiveOrganization();
+ const { data: session } = authClient.useSession();
const queryClient = useQueryClient();
const t = useExtracted();
+ // Renaming goes through better-auth's system-admin endpoint, so only system admins may do it.
+ const canRename = session?.user.role === "admin";
+ const canChangeRole = assignableRoles.length > 0;
+
const [name, setName] = useState("");
const [role, setRole] = useState<string>("member");
const [restrictSiteAccess, setRestrictSiteAccess] = useState(false);
const [selectedSiteIds, setSelectedSiteIds] = useState<number[]>([]);
+ const [siteRole, setSiteRole] = useState<SiteGrantRole | null>(null);
const [isSaving, setIsSaving] = useState(false);
const [isRemoving, setIsRemoving] = useState(false);
const [confirmRemoveOpen, setConfirmRemoveOpen] = useState(false);
+ // A site role only raises the organization role, so only roles above it are offered, and a
+ // chosen one the organization role has since caught up with no longer counts.
+ const siteRoleOptions = siteRolesAbove(role);
+ const effectiveSiteRole = siteRole && siteRoleOptions.includes(siteRole) ? siteRole : null;
+
useEffect(() => {
if (open && member) {
setName(member.user.name || "");
setRole(member.role);
setRestrictSiteAccess(member.siteAccess?.hasRestrictedSiteAccess ?? false);
setSelectedSiteIds(member.siteAccess?.siteIds ?? []);
+ setSiteRole(member.siteAccess?.siteRole ?? null);
setConfirmRemoveOpen(false);
}
}, [open, member]);
@@ -69,45 +84,55 @@ export function EditMemberDialog({ member, open, onClose, onSuccess, isOwner }:
const handleSave = async () => {
if (!member || !activeOrganization?.id) return;
- if (role === "member" && restrictSiteAccess && selectedSiteIds.length === 0) {
+ if (!isAdminRole(role) && restrictSiteAccess && selectedSiteIds.length === 0) {
toast.error(t("Please select at least one site or disable site restrictions"));
return;
}
setIsSaving(true);
try {
- // Update name if changed
- if (name !== (member.user.name || "")) {
- await authClient.admin.updateUser({
+ // better-auth reports failures in the result rather than throwing.
+ if (canRename && name !== (member.user.name || "")) {
+ const { error } = await authClient.admin.updateUser({
userId: member.userId,
data: { name },
});
+ if (error) {
+ throw new Error(error.message || t("Failed to update member"));
+ }
}
- // If promoting from member to admin/owner, clear site restrictions first
- // (must happen while still a member, since the API rejects updates for non-members)
- if (member.role === "member" && role !== "member" && member.siteAccess?.hasRestrictedSiteAccess) {
- await updateMemberSiteAccess(activeOrganization.id, member.id, {
- hasRestrictedSiteAccess: false,
- siteIds: [],
- });
- }
-
- // Update role if changed
- if (role !== member.role && isOwner) {
- await authClient.organization.updateMemberRole({
+ // The role goes first: if it fails, the member keeps their site restrictions.
+ const roleChanged = canChangeRole && role !== member.role;
+ if (roleChanged) {
+ const { error } = await authClient.organization.updateMemberRole({
memberId: member.id,
organizationId: activeOrganization.id,
- role: role as "admin" | "member" | "owner",
+ role,
});
+ if (error) {
+ throw new Error(error.message || t("Failed to update member"));
+ }
}
- // Update site access for members
- if (role === "member") {
+ if (!isAdminRole(role)) {
await updateMemberSiteAccess(activeOrganization.id, member.id, {
hasRestrictedSiteAccess: restrictSiteAccess,
siteIds: selectedSiteIds,
+ siteRole: restrictSiteAccess ? effectiveSiteRole : null,
});
+ } else if (roleChanged && !isAdminRole(member.role) && member.siteAccess?.hasRestrictedSiteAccess) {
+ // Promoted to admin or owner: drop the restrictions they no longer need. Admins and owners reach
+ // every site whatever is stored, so if the server refuses this, access is already right and the
+ // role change still stands; the old list only matters if they are demoted again.
+ try {
+ await updateMemberSiteAccess(activeOrganization.id, member.id, {
+ hasRestrictedSiteAccess: false,
+ siteIds: [],
+ });
+ } catch (error) {
+ console.warn("Couldn't clear site restrictions after promotion:", error);
+ }
}
queryClient.invalidateQueries({ queryKey: ["organization-members"] });
@@ -148,7 +173,7 @@ export function EditMemberDialog({ member, open, onClose, onSuccess, isOwner }:
if (!member) return null;
- const isRestrictable = role === "member";
+ const isRestrictable = !isAdminRole(role);
return (
<Dialog open={open} onOpenChange={() => onClose()}>
@@ -165,29 +190,22 @@ export function EditMemberDialog({ member, open, onClose, onSuccess, isOwner }:
<div className="text-sm text-neutral-500 dark:text-neutral-300">{member.user.email}</div>
</div>
- <div className="grid gap-2">
- <Label htmlFor="name">{t("Name")}</Label>
- <Input
- id="name"
- value={name}
- onChange={(e: React.ChangeEvent<HTMLInputElement>) => setName(e.target.value)}
- placeholder={t("Name")}
- />
- </div>
+ {canRename && (
+ <div className="grid gap-2">
+ <Label htmlFor="name">{t("Name")}</Label>
+ <Input
+ id="name"
+ value={name}
+ onChange={(e: React.ChangeEvent<HTMLInputElement>) => setName(e.target.value)}
+ placeholder={t("Name")}
+ />
+ </div>
+ )}
- {isOwner && (
+ {canChangeRole && (
<div className="grid gap-2">
<Label htmlFor="role">{t("Role")}</Label>
- <Select value={role} onValueChange={setRole}>
- <SelectTrigger>
- <SelectValue placeholder={t("Select a role")} />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="owner">{t("Owner")}</SelectItem>
- <SelectItem value="admin">{t("Admin")}</SelectItem>
- <SelectItem value="member">{t("Member")}</SelectItem>
- </SelectContent>
- </Select>
+ <RoleSelect id="role" value={role} roles={assignableRoles} onValueChange={setRole} />
</div>
)}
@@ -219,6 +237,21 @@ export function EditMemberDialog({ member, open, onClose, onSuccess, isOwner }:
)
: t("This member will only have access to the selected sites.")}
</p>
+ {siteRoleOptions.length > 0 && (
+ <div className="grid gap-2 mt-4">
+ <Label htmlFor="site-role">{t("Role on these sites")}</Label>
+ <SiteRoleSelect
+ id="site-role"
+ value={effectiveSiteRole}
+ roles={siteRoleOptions}
+ ownRoleLabel={t("Their organization role")}
+ onValueChange={setSiteRole}
+ />
+ <p className="text-xs text-neutral-500 dark:text-neutral-300">
+ {t("Raises their role on the selected sites only.")}
+ </p>
+ </div>
+ )}
</div>
) : (
<p className="text-sm text-neutral-500 dark:text-neutral-300 pl-6">
@@ -233,7 +266,7 @@ export function EditMemberDialog({ member, open, onClose, onSuccess, isOwner }:
</>
) : (
<p className="text-sm text-neutral-500 dark:text-neutral-300">
- {role === "owner" ? t("Organization owners") : t("Admins")} {t("automatically have access to all sites.")}
+ {t("Owners and admins automatically have access to all sites.")}
</p>
)}
diff --git a/client/src/app/settings/organization/components/Invitations.test.tsx b/client/src/app/settings/organization/components/Invitations.test.tsx
index 1a99beda0..6f45ff5a3 100644
--- a/client/src/app/settings/organization/components/Invitations.test.tsx
+++ b/client/src/app/settings/organization/components/Invitations.test.tsx
@@ -40,7 +40,7 @@ vi.mock("@/components/ui/sonner", () => ({
}));
function openConfirmation() {
- render(<Invitations organizationId="org-1" isOwner />);
+ render(<Invitations organizationId="org-1" canManage />);
fireEvent.click(screen.getByRole("button", { name: "Cancel invitation for [email protected]" }));
return screen.getByRole("alertdialog");
}
@@ -55,6 +55,12 @@ afterEach(() => {
});
describe("Invitations", () => {
+ it("offers no cancel action without permission to manage members", () => {
+ render(<Invitations organizationId="org-1" canManage={false} />);
+ expect(screen.getByText("[email protected]")).toBeTruthy();
+ expect(screen.queryByRole("button", { name: "Cancel invitation for [email protected]" })).toBeNull();
+ });
+
it("asks before cancelling, and keeping the invitation does nothing", () => {
const dialog = openConfirmation();
expect(dialog.textContent).toContain("The invitation sent to [email protected] will stop working.");
diff --git a/client/src/app/settings/organization/components/Invitations.tsx b/client/src/app/settings/organization/components/Invitations.tsx
index 4121a3cc2..7c1f052a4 100644
--- a/client/src/app/settings/organization/components/Invitations.tsx
+++ b/client/src/app/settings/organization/components/Invitations.tsx
@@ -19,10 +19,12 @@ import { Button } from "../../../../components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "../../../../components/ui/card";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../../../components/ui/table";
import { authClient } from "../../../../lib/auth";
+import { useRoleInfo } from "../../../../lib/roles";
interface InvitationsProps {
organizationId: string;
- isOwner: boolean;
+ /** Cancel pending invitations (members:manage). */
+ canManage: boolean;
}
function CancelInvitationButton({
@@ -94,8 +96,9 @@ function CancelInvitationButton({
);
}
-export function Invitations({ organizationId, isOwner }: InvitationsProps) {
+export function Invitations({ organizationId, canManage }: InvitationsProps) {
const t = useExtracted();
+ const roleInfo = useRoleInfo();
const {
data: invitations,
@@ -117,7 +120,7 @@ export function Invitations({ organizationId, isOwner }: InvitationsProps) {
<TableHead>{t("Role")}</TableHead>
<TableHead>{t("Status")}</TableHead>
<TableHead>{t("Expires")}</TableHead>
- {isOwner && <TableHead className="w-12">{t("Actions")}</TableHead>}
+ {canManage && <TableHead className="w-12">{t("Actions")}</TableHead>}
</TableRow>
</TableHeader>
<TableBody>
@@ -137,7 +140,7 @@ export function Invitations({ organizationId, isOwner }: InvitationsProps) {
<TableCell>
<div className="h-4 bg-muted animate-pulse rounded w-20"></div>
</TableCell>
- {isOwner && (
+ {canManage && (
<TableCell>
<div className="h-8 bg-muted animate-pulse rounded w-16 ml-auto"></div>
</TableCell>
@@ -150,20 +153,14 @@ export function Invitations({ organizationId, isOwner }: InvitationsProps) {
pendingInvitations.map(invitation => (
<TableRow key={invitation.id}>
<TableCell>{invitation.email}</TableCell>
- <TableCell className="capitalize">
- {invitation.role === "admin"
- ? t("Admin")
- : invitation.role === "owner"
- ? t("Owner")
- : t("Member")}
- </TableCell>
+ <TableCell className="capitalize">{roleInfo(invitation.role).label}</TableCell>
<TableCell>
<Badge variant="secondary">{t("Pending")}</Badge>
</TableCell>
<TableCell>
{DateTime.fromJSDate(new Date(invitation.expiresAt)).toLocaleString(DateTime.DATE_SHORT)}
</TableCell>
- {isOwner && (
+ {canManage && (
<TableCell className="text-right">
{invitation.status === "pending" && (
<CancelInvitationButton invitation={invitation} onCancelled={refetchInvitations} />
@@ -174,7 +171,7 @@ export function Invitations({ organizationId, isOwner }: InvitationsProps) {
))
) : (
<TableRow>
- <TableCell colSpan={isOwner ? 5 : 4} className="text-center py-6 text-muted-foreground">
+ <TableCell colSpan={canManage ? 5 : 4} className="text-center py-6 text-muted-foreground">
{t("No pending invitations")}
</TableCell>
</TableRow>
diff --git a/client/src/app/settings/organization/components/InviteMemberDialog.tsx b/client/src/app/settings/organization/components/InviteMemberDialog.tsx
index 63ed542c2..1fb554a3a 100644
--- a/client/src/app/settings/organization/components/InviteMemberDialog.tsx
+++ b/client/src/app/settings/organization/components/InviteMemberDialog.tsx
@@ -1,5 +1,6 @@
"use client";
+import type { OrgRole, SiteGrantRole } from "@rybbit/shared";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { UserPlus } from "lucide-react";
import { useExtracted } from "next-intl";
@@ -25,17 +26,26 @@ import { Alert } from "@/components/ui/alert";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { authClient } from "@/lib/auth";
import { IS_CLOUD } from "@/lib/const";
+import { isAdminRole, siteRolesAbove } from "@/lib/roles";
import { useStripeSubscription } from "@/lib/subscription/useStripeSubscription";
+import { RoleSelect, SiteRoleSelect } from "./RoleSelect";
import { SiteAccessMultiSelect } from "./SiteAccessMultiSelect";
interface InviteMemberDialogProps {
organizationId: string;
onSuccess: () => void;
memberCount: number;
+ /** Roles the current user may give, from the server. */
+ assignableRoles: OrgRole[];
}
-export function InviteMemberDialog({ organizationId, onSuccess, memberCount }: InviteMemberDialogProps) {
+export function InviteMemberDialog({
+ organizationId,
+ onSuccess,
+ memberCount,
+ assignableRoles,
+}: InviteMemberDialogProps) {
const { data: subscription } = useStripeSubscription();
const queryClient = useQueryClient();
const t = useExtracted();
@@ -51,23 +61,30 @@ export function InviteMemberDialog({ organizationId, onSuccess, memberCount }: I
const teams = teamsData?.teams || [];
const [email, setEmail] = useState("");
- const [role, setRole] = useState<"admin" | "member" | "owner">("member");
+ const [role, setRole] = useState<OrgRole>("member");
+ const isRestrictable = !isAdminRole(role);
const [restrictSiteAccess, setRestrictSiteAccess] = useState(false);
const [selectedSiteIds, setSelectedSiteIds] = useState<number[]>([]);
+ const [siteRole, setSiteRole] = useState<SiteGrantRole | null>(null);
+ // A site role only raises the invited role, so only roles above it are offered.
+ const siteRoleOptions = siteRolesAbove(role);
+ const effectiveSiteRole = siteRole && siteRoleOptions.includes(siteRole) ? siteRole : null;
const [selectedTeamId, setSelectedTeamId] = useState<string>("none");
const [open, setOpen] = useState(false);
const [error, setError] = useState("");
const inviteMutation = useMutation({
mutationFn: async () => {
- const hasSiteRestrictions = role === "member" && restrictSiteAccess;
+ const hasSiteRestrictions = isRestrictable && restrictSiteAccess;
const result = await authClient.organization.inviteMember({
email,
- role,
+ // better-auth's client types only know its default roles; the server's access control defines ours.
+ role: role as "owner" | "admin" | "member",
organizationId,
...(selectedTeamId && selectedTeamId !== "none" ? { teamId: selectedTeamId } : {}),
hasRestrictedSiteAccess: hasSiteRestrictions,
siteIds: hasSiteRestrictions ? selectedSiteIds : [],
+ siteRole: (hasSiteRestrictions && effectiveSiteRole) || undefined,
});
if (result.error) {
@@ -85,6 +102,7 @@ export function InviteMemberDialog({ organizationId, onSuccess, memberCount }: I
setRole("member");
setRestrictSiteAccess(false);
setSelectedSiteIds([]);
+ setSiteRole(null);
setSelectedTeamId("none");
setError("");
},
@@ -101,7 +119,7 @@ export function InviteMemberDialog({ organizationId, onSuccess, memberCount }: I
return;
}
- if (role === "member" && restrictSiteAccess && selectedSiteIds.length === 0) {
+ if (isRestrictable && restrictSiteAccess && selectedSiteIds.length === 0) {
setError(t("Please select at least one site or disable site restrictions"));
return;
}
@@ -121,7 +139,9 @@ export function InviteMemberDialog({ organizationId, onSuccess, memberCount }: I
</span>
</TooltipTrigger>
<TooltipContent>
- {t("You have reached the limit of {limit} members. Upgrade to add more members", { limit: String(memberLimit) })}
+ {t("You have reached the limit of {limit} members. Upgrade to add more members", {
+ limit: String(memberLimit),
+ })}
</TooltipContent>
</Tooltip>
);
@@ -153,28 +173,21 @@ export function InviteMemberDialog({ organizationId, onSuccess, memberCount }: I
</div>
<div className="grid gap-2">
<Label htmlFor="role">{t("Role")}</Label>
- <Select
+ <RoleSelect
+ id="role"
value={role}
+ roles={assignableRoles}
onValueChange={value => {
- setRole(value as "admin" | "member" | "owner");
- if (value !== "member") {
+ setRole(value);
+ if (isAdminRole(value)) {
setRestrictSiteAccess(false);
setSelectedSiteIds([]);
}
}}
- >
- <SelectTrigger>
- <SelectValue placeholder={t("Select a role")} />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value="owner">{t("Owner")}</SelectItem>
- <SelectItem value="admin">{t("Admin")}</SelectItem>
- <SelectItem value="member">{t("Member")}</SelectItem>
- </SelectContent>
- </Select>
+ />
</div>
- {role === "member" && (
+ {isRestrictable && (
<div className="grid gap-3">
<div className="flex items-center space-x-2">
<Checkbox
@@ -197,6 +210,21 @@ export function InviteMemberDialog({ organizationId, onSuccess, memberCount }: I
<p className="text-xs text-muted-foreground mt-2">
{t("This member will only have access to the selected sites.")}
</p>
+ {siteRoleOptions.length > 0 && (
+ <div className="grid gap-2 mt-4">
+ <Label htmlFor="invite-site-role">{t("Role on these sites")}</Label>
+ <SiteRoleSelect
+ id="invite-site-role"
+ value={effectiveSiteRole}
+ roles={siteRoleOptions}
+ ownRoleLabel={t("Their organization role")}
+ onValueChange={setSiteRole}
+ />
+ <p className="text-xs text-muted-foreground">
+ {t("Raises their role on the selected sites only.")}
+ </p>
+ </div>
+ )}
</div>
)}
</div>
diff --git a/client/src/app/settings/organization/components/MembersTable.tsx b/client/src/app/settings/organization/components/MembersTable.tsx
index 549563775..cad9097e7 100644
--- a/client/src/app/settings/organization/components/MembersTable.tsx
+++ b/client/src/app/settings/organization/components/MembersTable.tsx
@@ -1,5 +1,6 @@
"use client";
+import type { OrgRole } from "@rybbit/shared";
import { DateTime } from "luxon";
import { Pencil } from "lucide-react";
import { useExtracted } from "next-intl";
@@ -9,15 +10,9 @@ import { GetOrganizationMembersResponse } from "../../../../api/admin/endpoints/
import { Badge } from "../../../../components/ui/badge";
import { Button } from "../../../../components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "../../../../components/ui/card";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "../../../../components/ui/table";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../../../components/ui/table";
import { IS_CLOUD } from "../../../../lib/const";
+import { isAdminRole, useRoleInfo } from "../../../../lib/roles";
import { getTimezone } from "../../../../lib/store";
import { CreateUserDialog } from "./CreateUserDialog";
import { EditMemberDialog } from "./EditMemberDialog";
@@ -29,8 +24,10 @@ interface MembersTableProps {
org: { id: string; name: string; slug: string; createdAt: Date };
members: GetOrganizationMembersResponse | undefined;
membersLoading: boolean;
- isOwner: boolean;
- isAdmin: boolean;
+ /** Invite, edit and remove members. */
+ canManageMembers: boolean;
+ /** Roles the current user may give; a member is editable only when their current role is one of them. */
+ assignableRoles: OrgRole[];
onRefresh: () => void;
}
@@ -38,12 +35,14 @@ export function MembersTable({
org,
members,
membersLoading,
- isOwner,
- isAdmin,
+ canManageMembers,
+ assignableRoles,
onRefresh,
}: MembersTableProps) {
const t = useExtracted();
+ const roleInfo = useRoleInfo();
const [selectedMember, setSelectedMember] = useState<MemberData | null>(null);
+ const canEditMember = (member: MemberData) => assignableRoles.some(role => role === member.role);
return (
<>
@@ -53,16 +52,17 @@ export function MembersTable({
<CardTitle className="text-xl">{t("Members")}</CardTitle>
<div className="flex items-center gap-2">
- {isOwner && (
+ {canManageMembers && (
<>
{IS_CLOUD ? (
<InviteMemberDialog
organizationId={org.id}
onSuccess={onRefresh}
memberCount={members?.data?.length || 0}
+ assignableRoles={assignableRoles}
/>
) : (
- <CreateUserDialog organizationId={org.id} onSuccess={onRefresh} />
+ <CreateUserDialog organizationId={org.id} onSuccess={onRefresh} assignableRoles={assignableRoles} />
)}
</>
)}
@@ -78,7 +78,7 @@ export function MembersTable({
<TableHead>{t("Role")}</TableHead>
<TableHead>{t("Site Access")}</TableHead>
<TableHead>{t("Joined")}</TableHead>
- {isAdmin && <TableHead className="w-12">{t("Actions")}</TableHead>}
+ {canManageMembers && <TableHead className="w-12">{t("Actions")}</TableHead>}
</TableRow>
</TableHeader>
<TableBody>
@@ -100,7 +100,7 @@ export function MembersTable({
<TableCell>
<div className="h-4 bg-muted animate-pulse rounded w-20"></div>
</TableCell>
- {isAdmin && (
+ {canManageMembers && (
<TableCell>
<div className="h-8 bg-muted animate-pulse rounded w-16 ml-auto"></div>
</TableCell>
@@ -113,21 +113,20 @@ export function MembersTable({
<TableRow key={member.id}>
<TableCell>{member.user?.name || "β€”"}</TableCell>
<TableCell>{member.user?.email}</TableCell>
- <TableCell className="capitalize">
- {member.role === "admin"
- ? t("Admin")
- : member.role === "owner"
- ? t("Owner")
- : t("Member")}
- </TableCell>
+ <TableCell className="capitalize">{roleInfo(member.role).label}</TableCell>
<TableCell>
- {member.role === "member" ? (
+ {!isAdminRole(member.role) ? (
<div className="flex flex-wrap gap-1">
{member.siteAccess?.hasRestrictedSiteAccess && (
<Badge variant="default">
- {t("{count} sites", {
- count: String(member.siteAccess.siteIds.length),
- })}
+ {member.siteAccess.siteRole
+ ? t("{count} sites Β· {role}", {
+ count: String(member.siteAccess.siteIds.length),
+ role: roleInfo(member.siteAccess.siteRole).label,
+ })
+ : t("{count} sites", {
+ count: String(member.siteAccess.siteIds.length),
+ })}
</Badge>
)}
{member.teams?.map(team => (
@@ -139,10 +138,9 @@ export function MembersTable({
{team.name}
</Badge>
))}
- {!member.siteAccess?.hasRestrictedSiteAccess &&
- !member.teams?.length && (
- <Badge variant="secondary">{t("All sites")}</Badge>
- )}
+ {!member.siteAccess?.hasRestrictedSiteAccess && !member.teams?.length && (
+ <Badge variant="secondary">{t("All sites")}</Badge>
+ )}
</div>
) : (
<Badge variant="outline">{t("All sites")}</Badge>
@@ -153,14 +151,10 @@ export function MembersTable({
.setZone(getTimezone())
.toLocaleString(DateTime.DATE_SHORT)}
</TableCell>
- {isAdmin && (
+ {canManageMembers && (
<TableCell className="text-right">
- {(isOwner || member.role !== "owner") && (
- <Button
- size="smIcon"
- variant="ghost"
- onClick={() => setSelectedMember(member)}
- >
+ {canEditMember(member) && (
+ <Button size="smIcon" variant="ghost" onClick={() => setSelectedMember(member)}>
<Pencil className="h-4 w-4" />
</Button>
)}
@@ -170,10 +164,7 @@ export function MembersTable({
))}
{(!members?.data || members.data.length === 0) && (
<TableRow>
- <TableCell
- colSpan={isAdmin ? 6 : 5}
- className="text-center py-6 text-muted-foreground"
- >
+ <TableCell colSpan={canManageMembers ? 6 : 5} className="text-center py-6 text-muted-foreground">
{t("No members found")}
</TableCell>
</TableRow>
@@ -190,7 +181,7 @@ export function MembersTable({
open={!!selectedMember}
onClose={() => setSelectedMember(null)}
onSuccess={onRefresh}
- isOwner={isOwner}
+ assignableRoles={assignableRoles}
/>
</>
);
diff --git a/client/src/app/settings/organization/components/RoleSelect.tsx b/client/src/app/settings/organization/components/RoleSelect.tsx
new file mode 100644
index 000000000..c6716bc91
--- /dev/null
+++ b/client/src/app/settings/organization/components/RoleSelect.tsx
@@ -0,0 +1,85 @@
+"use client";
+
+import type { OrgRole, SiteGrantRole } from "@rybbit/shared";
+import { useExtracted } from "next-intl";
+
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { useRoleInfo } from "@/lib/roles";
+
+interface RoleSelectProps {
+ id?: string;
+ value: string;
+ onValueChange: (role: OrgRole) => void;
+ /** The roles the current user may give, from the server (useOrgPermissions().assignableRoles). */
+ roles: readonly OrgRole[];
+}
+
+/** A role option: its label, and underneath, what it allows. */
+function RoleOption({ value, label, description }: { value: string; label: string; description?: string }) {
+ return (
+ <SelectItem value={value} textValue={label}>
+ <span className="flex flex-col py-0.5">
+ <span>{label}</span>
+ {description && (
+ <span className="text-xs text-neutral-500 dark:text-neutral-400 whitespace-normal">{description}</span>
+ )}
+ </span>
+ </SelectItem>
+ );
+}
+
+/** A role picker listing only the roles the current user may assign, each with what it allows. */
+export function RoleSelect({ id, value, onValueChange, roles }: RoleSelectProps) {
+ const t = useExtracted();
+ const roleInfo = useRoleInfo();
+
+ return (
+ <Select value={value} onValueChange={role => onValueChange(role as OrgRole)}>
+ <SelectTrigger id={id}>
+ {/* Just the label here; the descriptions are for choosing. */}
+ <SelectValue placeholder={t("Select a role")}>{value ? roleInfo(value).label : null}</SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {roles.map(role => (
+ <RoleOption key={role} value={role} {...roleInfo(role)} />
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
+
+// Radix Select items can't carry an empty value, so "no site role" gets a stand-in.
+const OWN_ROLE = "own-role";
+
+interface SiteRoleSelectProps {
+ id?: string;
+ /** null: no site role, so the person's own role applies. */
+ value: SiteGrantRole | null;
+ onValueChange: (role: SiteGrantRole | null) => void;
+ /** The site roles to offer after the no-site-role option. */
+ roles: readonly SiteGrantRole[];
+ /** What the no-site-role option is called here, e.g. "Their organization role". */
+ ownRoleLabel: string;
+}
+
+/** A picker for the role a site grant carries, or none. */
+export function SiteRoleSelect({ id, value, onValueChange, roles, ownRoleLabel }: SiteRoleSelectProps) {
+ const roleInfo = useRoleInfo();
+
+ return (
+ <Select
+ value={value ?? OWN_ROLE}
+ onValueChange={role => onValueChange(role === OWN_ROLE ? null : (role as SiteGrantRole))}
+ >
+ <SelectTrigger id={id}>
+ <SelectValue>{value ? roleInfo(value).label : ownRoleLabel}</SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ <RoleOption value={OWN_ROLE} label={ownRoleLabel} />
+ {roles.map(role => (
+ <RoleOption key={role} value={role} {...roleInfo(role)} />
+ ))}
+ </SelectContent>
+ </Select>
+ );
+}
diff --git a/client/src/app/settings/organization/layout.tsx b/client/src/app/settings/organization/layout.tsx
index d1379541a..5aee2cc14 100644
--- a/client/src/app/settings/organization/layout.tsx
+++ b/client/src/app/settings/organization/layout.tsx
@@ -6,18 +6,12 @@ import { useState } from "react";
import { CreateOrganizationDialog } from "../../../components/CreateOrganizationDialog";
import { OrganizationSelector } from "../../../components/OrganizationSelector";
import { Button } from "../../../components/ui/button";
-import { authClient } from "../../../lib/auth";
+import { OrgPermissionGate } from "../components/OrgPermissionGate";
export default function OrganizationLayout({ children }: { children: React.ReactNode }) {
const [createOrgDialogOpen, setCreateOrgDialogOpen] = useState(false);
const t = useExtracted();
- const { data: session } = authClient.useSession();
- const { data: activeOrg } = authClient.useActiveOrganization();
- const currentMember = activeOrg?.members?.find(
- (m) => m.userId === session?.user?.id
- );
- const isMember = currentMember?.role === "member";
return (
<>
@@ -40,15 +34,12 @@ export default function OrganizationLayout({ children }: { children: React.React
/>
</div>
- {isMember ? (
- <div className="rounded-lg border border-neutral-200 dark:border-neutral-800 p-6 text-center text-neutral-500 dark:text-neutral-400">
- {t("You don't have permission to view organization settings.")}
- </div>
- ) : (
- <>
- <div className="mt-6">{children}</div>
- </>
- )}
+ <OrgPermissionGate
+ permission="members:manage"
+ deniedMessage={t("You don't have permission to view organization settings.")}
+ >
+ <div className="mt-6">{children}</div>
+ </OrgPermissionGate>
</div>
</>
);
diff --git a/client/src/app/settings/organization/page.tsx b/client/src/app/settings/organization/page.tsx
index 8a5405b7c..0f3bcab16 100644
--- a/client/src/app/settings/organization/page.tsx
+++ b/client/src/app/settings/organization/page.tsx
@@ -8,6 +8,7 @@ import { NoOrganization } from "../../../components/NoOrganization";
import { Button } from "../../../components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "../../../components/ui/card";
import { Input } from "../../../components/ui/input";
+import { useOrgPermissions } from "../../../hooks/usePermissions";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
import { authClient } from "../../../lib/auth";
import { ApiKeyManager } from "../account/components/ApiKeyManager";
@@ -61,10 +62,9 @@ function Organization({
const { data: members, refetch, isLoading: membersLoading } = useOrganizationMembers(org.id);
const { refetch: refetchInvitations } = useOrganizationInvitations(org.id);
- const { data } = authClient.useSession();
-
- const isOwner = !!members?.data.find(member => member.role === "owner" && member.userId === data?.user?.id);
- const isAdmin = !!members?.data.find(member => member.role === "admin" && member.userId === data?.user?.id) || isOwner;
+ const { can, assignableRoles } = useOrgPermissions(org.id);
+ const canRename = can("org:rename");
+ const canDelete = can("org:delete");
const handleRefresh = () => {
refetch();
@@ -102,29 +102,33 @@ function Organization({
return (
<>
- {isOwner && (
+ {(canRename || canDelete) && (
<Card>
<CardHeader>
<CardTitle className="text-xl">{t("Organization")}</CardTitle>
</CardHeader>
- <CardContent>
- <div className="space-y-2">
- <h4 className="text-sm font-medium">{t("Organization Name")}</h4>
- <p className="text-xs text-neutral-500">{t("Update your organization name")}</p>
- <div className="flex space-x-2">
- <Input id="name" value={name} onChange={({ target }) => setName(target.value)} placeholder="name" />
- <Button variant="outline" onClick={handleOrganizationNameUpdate} disabled={name === org.name}>
- {isUpdating ? t("Updating...") : t("Update")}
- </Button>
+ <CardContent className="space-y-4">
+ {canRename && (
+ <div className="space-y-2">
+ <h4 className="text-sm font-medium">{t("Organization Name")}</h4>
+ <p className="text-xs text-neutral-500">{t("Update your organization name")}</p>
+ <div className="flex space-x-2">
+ <Input id="name" value={name} onChange={({ target }) => setName(target.value)} placeholder="name" />
+ <Button variant="outline" onClick={handleOrganizationNameUpdate} disabled={name === org.name}>
+ {isUpdating ? t("Updating...") : t("Update")}
+ </Button>
+ </div>
</div>
- </div>
- <div className="pt-4 border-t mt-4 space-y-2">
- <h4 className="text-sm font-medium">{t("Delete Organization")}</h4>
- <p className="text-xs text-neutral-500">{t("Permanently delete this organization and all its data")}</p>
- <div className="w-[200px]">
- <DeleteOrganizationDialog organization={org} onSuccess={handleRefresh} />
+ )}
+ {canDelete && (
+ <div className={canRename ? "pt-4 border-t space-y-2" : "space-y-2"}>
+ <h4 className="text-sm font-medium">{t("Delete Organization")}</h4>
+ <p className="text-xs text-neutral-500">{t("Permanently delete this organization and all its data")}</p>
+ <div className="w-[200px]">
+ <DeleteOrganizationDialog organization={org} onSuccess={handleRefresh} />
+ </div>
</div>
- </div>
+ )}
</CardContent>
</Card>
)}
@@ -133,14 +137,14 @@ function Organization({
org={org}
members={members}
membersLoading={membersLoading}
- isOwner={isOwner}
- isAdmin={isAdmin}
+ canManageMembers={can("members:manage")}
+ assignableRoles={assignableRoles}
onRefresh={handleRefresh}
/>
- <Invitations organizationId={org.id} isOwner={isOwner} />
+ <Invitations organizationId={org.id} canManage={can("members:manage")} />
- {isAdmin && <ApiKeyManager organizationId={org.id} />}
+ {can("apikeys:manage") && <ApiKeyManager organizationId={org.id} />}
</>
);
}
diff --git a/client/src/app/settings/teams/components/CreateEditTeamDialog.tsx b/client/src/app/settings/teams/components/CreateEditTeamDialog.tsx
index 9de578348..0cb879972 100644
--- a/client/src/app/settings/teams/components/CreateEditTeamDialog.tsx
+++ b/client/src/app/settings/teams/components/CreateEditTeamDialog.tsx
@@ -1,5 +1,6 @@
"use client";
+import type { SiteGrantRole } from "@rybbit/shared";
import { useExtracted } from "next-intl";
import { useEffect, useState } from "react";
import { toast } from "@/components/ui/sonner";
@@ -8,6 +9,7 @@ import { Team } from "@/api/admin/endpoints/teams";
import { useCreateTeam, useUpdateTeam } from "@/api/admin/hooks/useTeams";
import { useOrganizationMembers } from "@/api/admin/hooks/useOrganizationMembers";
import { useGetSitesFromOrg } from "@/api/admin/hooks/useSites";
+import { SiteRoleSelect } from "@/app/settings/organization/components/RoleSelect";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import {
@@ -22,6 +24,7 @@ import {
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { authClient } from "@/lib/auth";
+import { SITE_GRANT_ROLES } from "@/lib/roles";
interface CreateEditTeamDialogProps {
team?: Team;
@@ -53,6 +56,7 @@ export function CreateEditTeamDialog({
const [name, setName] = useState("");
const [selectedMemberIds, setSelectedMemberIds] = useState<string[]>([]);
const [selectedSiteIds, setSelectedSiteIds] = useState<number[]>([]);
+ const [siteRole, setSiteRole] = useState<SiteGrantRole | null>(null);
const isEditing = !!existingTeam;
@@ -61,12 +65,14 @@ export function CreateEditTeamDialog({
if (open) {
if (existingTeam) {
setName(existingTeam.name);
- setSelectedMemberIds(existingTeam.members.map((m) => m.userId));
- setSelectedSiteIds(existingTeam.sites.map((s) => s.siteId));
+ setSelectedMemberIds(existingTeam.members.map(m => m.userId));
+ setSelectedSiteIds(existingTeam.sites.map(s => s.siteId));
+ setSiteRole(existingTeam.siteRole ?? null);
} else {
setName("");
setSelectedMemberIds([]);
setSelectedSiteIds([]);
+ setSiteRole(null);
}
}
}, [open, existingTeam]);
@@ -75,26 +81,18 @@ export function CreateEditTeamDialog({
const sites = sitesData?.sites || [];
const handleMemberToggle = (userId: string) => {
- setSelectedMemberIds((prev) =>
- prev.includes(userId)
- ? prev.filter((id) => id !== userId)
- : [...prev, userId]
- );
+ setSelectedMemberIds(prev => (prev.includes(userId) ? prev.filter(id => id !== userId) : [...prev, userId]));
};
const handleSiteToggle = (siteId: number) => {
- setSelectedSiteIds((prev) =>
- prev.includes(siteId)
- ? prev.filter((id) => id !== siteId)
- : [...prev, siteId]
- );
+ setSelectedSiteIds(prev => (prev.includes(siteId) ? prev.filter(id => id !== siteId) : [...prev, siteId]));
};
const handleSelectAllMembers = () => {
if (selectedMemberIds.length === members.length) {
setSelectedMemberIds([]);
} else {
- setSelectedMemberIds(members.map((m) => m.userId));
+ setSelectedMemberIds(members.map(m => m.userId));
}
};
@@ -102,7 +100,7 @@ export function CreateEditTeamDialog({
if (selectedSiteIds.length === sites.length) {
setSelectedSiteIds([]);
} else {
- setSelectedSiteIds(sites.map((s) => s.siteId));
+ setSelectedSiteIds(sites.map(s => s.siteId));
}
};
@@ -123,6 +121,7 @@ export function CreateEditTeamDialog({
name: name.trim(),
memberUserIds: selectedMemberIds,
siteIds: selectedSiteIds,
+ siteRole,
},
});
toast.success(t("Team updated successfully"));
@@ -133,6 +132,7 @@ export function CreateEditTeamDialog({
name: name.trim(),
memberUserIds: selectedMemberIds,
siteIds: selectedSiteIds,
+ siteRole,
},
});
toast.success(t("Team created successfully"));
@@ -141,11 +141,7 @@ export function CreateEditTeamDialog({
onSuccess?.();
} catch (error) {
toast.error(
- error instanceof Error
- ? error.message
- : isEditing
- ? t("Failed to update team")
- : t("Failed to create team")
+ error instanceof Error ? error.message : isEditing ? t("Failed to update team") : t("Failed to create team")
);
}
};
@@ -155,15 +151,11 @@ export function CreateEditTeamDialog({
const dialogContent = (
<DialogContent className="max-w-lg max-h-[85vh] overflow-y-auto">
<DialogHeader>
- <DialogTitle>
- {isEditing ? t("Edit Team") : t("Create Team")}
- </DialogTitle>
+ <DialogTitle>{isEditing ? t("Edit Team") : t("Create Team")}</DialogTitle>
<DialogDescription>
{isEditing
? t("Update team name, members, and site assignments.")
- : t(
- "Create a new team to group sites and control member access."
- )}
+ : t("Create a new team to group sites and control member access.")}
</DialogDescription>
</DialogHeader>
@@ -174,7 +166,7 @@ export function CreateEditTeamDialog({
<Input
id="team-name"
value={name}
- onChange={(e) => setName(e.target.value)}
+ onChange={e => setName(e.target.value)}
placeholder={t("Enter team name")}
/>
</div>
@@ -182,23 +174,15 @@ export function CreateEditTeamDialog({
{/* Members */}
<div className="space-y-2">
<Label className="font-medium">{t("Members")}</Label>
- <p className="text-xs text-muted-foreground">
- {t("Select which members belong to this team.")}
- </p>
+ <p className="text-xs text-muted-foreground">{t("Select which members belong to this team.")}</p>
<div className="space-y-2">
<div className="flex items-center space-x-2">
<Checkbox
id="select-all-members"
- checked={
- members.length > 0 &&
- selectedMemberIds.length === members.length
- }
+ checked={members.length > 0 && selectedMemberIds.length === members.length}
onCheckedChange={handleSelectAllMembers}
/>
- <Label
- htmlFor="select-all-members"
- className="text-sm font-medium cursor-pointer"
- >
+ <Label htmlFor="select-all-members" className="text-sm font-medium cursor-pointer">
{t("Select all")} ({members.length})
</Label>
</div>
@@ -218,28 +202,16 @@ export function CreateEditTeamDialog({
{t("No members in this organization")}
</div>
) : (
- members.map((m) => (
- <div
- key={m.userId}
- className="flex items-center space-x-3 p-2.5 hover:bg-muted/50"
- >
+ members.map(m => (
+ <div key={m.userId} className="flex items-center space-x-3 p-2.5 hover:bg-muted/50">
<Checkbox
id={`member-${m.userId}`}
checked={selectedMemberIds.includes(m.userId)}
onCheckedChange={() => handleMemberToggle(m.userId)}
/>
- <Label
- htmlFor={`member-${m.userId}`}
- className="flex-1 cursor-pointer text-sm"
- >
- <span className="font-medium">
- {m.user?.name || m.user?.email}
- </span>
- {m.user?.name && (
- <span className="text-muted-foreground ml-2">
- {m.user.email}
- </span>
- )}
+ <Label htmlFor={`member-${m.userId}`} className="flex-1 cursor-pointer text-sm">
+ <span className="font-medium">{m.user?.name || m.user?.email}</span>
+ {m.user?.name && <span className="text-muted-foreground ml-2">{m.user.email}</span>}
</Label>
</div>
))
@@ -260,16 +232,10 @@ export function CreateEditTeamDialog({
<div className="flex items-center space-x-2">
<Checkbox
id="select-all-sites"
- checked={
- sites.length > 0 &&
- selectedSiteIds.length === sites.length
- }
+ checked={sites.length > 0 && selectedSiteIds.length === sites.length}
onCheckedChange={handleSelectAllSites}
/>
- <Label
- htmlFor="select-all-sites"
- className="text-sm font-medium cursor-pointer"
- >
+ <Label htmlFor="select-all-sites" className="text-sm font-medium cursor-pointer">
{t("Select all")} ({sites.length})
</Label>
</div>
@@ -286,20 +252,14 @@ export function CreateEditTeamDialog({
{t("No sites in this organization")}
</div>
) : (
- sites.map((site) => (
- <div
- key={site.siteId}
- className="flex items-center space-x-3 p-2.5 hover:bg-muted/50"
- >
+ sites.map(site => (
+ <div key={site.siteId} className="flex items-center space-x-3 p-2.5 hover:bg-muted/50">
<Checkbox
id={`site-${site.siteId}`}
checked={selectedSiteIds.includes(site.siteId)}
onCheckedChange={() => handleSiteToggle(site.siteId)}
/>
- <Label
- htmlFor={`site-${site.siteId}`}
- className="flex-1 cursor-pointer text-sm"
- >
+ <Label htmlFor={`site-${site.siteId}`} className="flex-1 cursor-pointer text-sm">
<span className="font-medium">{site.name}</span>
</Label>
</div>
@@ -308,6 +268,21 @@ export function CreateEditTeamDialog({
</div>
</div>
</div>
+
+ {/* Site role */}
+ <div className="space-y-2">
+ <Label htmlFor="team-site-role" className="font-medium">
+ {t("Role on the team's sites")}
+ </Label>
+ <SiteRoleSelect
+ id="team-site-role"
+ value={siteRole}
+ roles={SITE_GRANT_ROLES}
+ ownRoleLabel={t("Each member's own role")}
+ onValueChange={setSiteRole}
+ />
+ <p className="text-xs text-muted-foreground">{t("Raises members' role on these sites; never lowers it.")}</p>
+ </div>
</div>
<DialogFooter>
diff --git a/client/src/app/settings/teams/layout.tsx b/client/src/app/settings/teams/layout.tsx
index db834f00d..669caa356 100644
--- a/client/src/app/settings/teams/layout.tsx
+++ b/client/src/app/settings/teams/layout.tsx
@@ -3,18 +3,16 @@
import { Plus } from "lucide-react";
import { useExtracted } from "next-intl";
import { Button } from "../../../components/ui/button";
+import { useOrgPermissions } from "../../../hooks/usePermissions";
import { authClient } from "../../../lib/auth";
+import { OrgPermissionGate } from "../components/OrgPermissionGate";
import { CreateEditTeamDialog } from "./components/CreateEditTeamDialog";
import { ExternalLink } from "../../../components/ExternalLink";
export default function TeamsLayout({ children }: { children: React.ReactNode }) {
const t = useExtracted();
- const { data: session } = authClient.useSession();
const { data: activeOrg } = authClient.useActiveOrganization();
- const currentMember = activeOrg?.members?.find(
- (m) => m.userId === session?.user?.id
- );
- const isMember = currentMember?.role === "member";
+ const { can } = useOrgPermissions();
return (
<div className="space-y-5">
@@ -28,7 +26,7 @@ export default function TeamsLayout({ children }: { children: React.ReactNode })
</ExternalLink>
</p>
</div>
- {activeOrg?.id && !isMember && (
+ {activeOrg?.id && can("teams:manage") && (
<CreateEditTeamDialog
trigger={
<Button size="sm">
@@ -40,13 +38,12 @@ export default function TeamsLayout({ children }: { children: React.ReactNode })
)}
</div>
- {isMember ? (
- <div className="rounded-lg border border-neutral-200 dark:border-neutral-800 p-6 text-center text-neutral-500 dark:text-neutral-400">
- {t("You don't have permission to view team settings.")}
- </div>
- ) : (
+ <OrgPermissionGate
+ permission="teams:manage"
+ deniedMessage={t("You don't have permission to view team settings.")}
+ >
<div className="mt-6">{children}</div>
- )}
+ </OrgPermissionGate>
</div>
);
}
diff --git a/client/src/app/settings/teams/page.tsx b/client/src/app/settings/teams/page.tsx
index 050452451..8ca140d76 100644
--- a/client/src/app/settings/teams/page.tsx
+++ b/client/src/app/settings/teams/page.tsx
@@ -1,6 +1,6 @@
"use client";
-import { ChevronDown, Globe, Pencil, Users2 } from "lucide-react";
+import { ChevronDown, Globe, Pencil, ShieldCheck, Users2 } from "lucide-react";
import { useExtracted } from "next-intl";
import { useState } from "react";
@@ -10,6 +10,7 @@ import { NoOrganization } from "@/components/NoOrganization";
import { Button } from "@/components/ui/button";
import { useSetPageTitle } from "@/hooks/useSetPageTitle";
import { authClient } from "@/lib/auth";
+import { useRoleInfo } from "@/lib/roles";
import { cn } from "@/lib/utils";
import { CreateEditTeamDialog } from "./components/CreateEditTeamDialog";
import { DeleteTeamDialog } from "./components/DeleteTeamDialog";
@@ -17,17 +18,15 @@ import { DeleteTeamDialog } from "./components/DeleteTeamDialog";
export default function TeamsPage() {
useSetPageTitle("Organization Teams");
const t = useExtracted();
- const { data: activeOrganization, isPending } =
- authClient.useActiveOrganization();
- const { data: teamsData, isLoading: teamsLoading } = useTeams(
- activeOrganization?.id
- );
+ const roleInfo = useRoleInfo();
+ const { data: activeOrganization, isPending } = authClient.useActiveOrganization();
+ const { data: teamsData, isLoading: teamsLoading } = useTeams(activeOrganization?.id);
const [editingTeam, setEditingTeam] = useState<Team | null>(null);
const [expandedTeams, setExpandedTeams] = useState<Set<string>>(new Set());
const toggleExpanded = (teamId: string) => {
- setExpandedTeams((prev) => {
+ setExpandedTeams(prev => {
const next = new Set(prev);
if (next.has(teamId)) {
next.delete(teamId);
@@ -48,11 +47,7 @@ export default function TeamsPage() {
if (!activeOrganization) {
return (
- <NoOrganization
- message={t(
- "You need to create or be added to an organization before you can manage teams."
- )}
- />
+ <NoOrganization message={t("You need to create or be added to an organization before you can manage teams.")} />
);
}
@@ -63,140 +58,117 @@ export default function TeamsPage() {
{teamsLoading ? (
<div className="space-y-3">
{Array.from({ length: 2 }).map((_, i) => (
- <div
- key={i}
- className="h-20 bg-muted animate-pulse rounded-lg"
- />
+ <div key={i} className="h-20 bg-muted animate-pulse rounded-lg" />
))}
</div>
) : teams.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">
<Users2 className="h-10 w-10 mx-auto mb-3 opacity-50" />
<p className="font-medium">{t("No teams yet")}</p>
- <p className="text-sm mt-1">
- {t(
- "Create a team to group sites and manage member access."
- )}
- </p>
+ <p className="text-sm mt-1">{t("Create a team to group sites and manage member access.")}</p>
</div>
) : (
<div className="space-y-3">
- {teams.map((team) => {
- const isExpanded = expandedTeams.has(team.id);
- return (
- <div
- key={team.id}
- className="border rounded-lg transition-colors bg-white dark:bg-neutral-900/70"
- >
- <div
- className="flex items-center justify-between p-4 cursor-pointer hover:bg-muted/50"
- onClick={() => toggleExpanded(team.id)}
- >
- <div className="flex items-center gap-3 flex-1 min-w-0">
- <ChevronDown
- className={cn(
- "h-4 w-4 shrink-0 text-muted-foreground transition-transform",
- !isExpanded && "-rotate-90"
- )}
- />
- <div className="flex-1 min-w-0">
- <h3 className="font-medium truncate">{team.name}</h3>
- <div className="flex items-center gap-3 mt-1 text-sm text-muted-foreground">
- <span className="flex items-center gap-1">
- <Users2 className="h-3.5 w-3.5" />
- {t("{count} members", {
- count: String(team.members.length),
- })}
- </span>
- <span className="flex items-center gap-1">
- <Globe className="h-3.5 w-3.5" />
- {t("{count} sites", {
- count: String(team.sites.length),
- })}
- </span>
- </div>
- </div>
- </div>
- <div
- className="flex items-center gap-2 ml-4"
- onClick={(e) => e.stopPropagation()}
- >
- <Button
- variant="ghost"
- size="smIcon"
- onClick={() => setEditingTeam(team)}
- >
- <Pencil className="h-3.5 w-3.5" />
- </Button>
- <DeleteTeamDialog team={team} />
+ {teams.map(team => {
+ const isExpanded = expandedTeams.has(team.id);
+ return (
+ <div key={team.id} className="border rounded-lg transition-colors bg-white dark:bg-neutral-900/70">
+ <div
+ className="flex items-center justify-between p-4 cursor-pointer hover:bg-muted/50"
+ onClick={() => toggleExpanded(team.id)}
+ >
+ <div className="flex items-center gap-3 flex-1 min-w-0">
+ <ChevronDown
+ className={cn(
+ "h-4 w-4 shrink-0 text-muted-foreground transition-transform",
+ !isExpanded && "-rotate-90"
+ )}
+ />
+ <div className="flex-1 min-w-0">
+ <h3 className="font-medium truncate">{team.name}</h3>
+ <div className="flex items-center gap-3 mt-1 text-sm text-muted-foreground">
+ <span className="flex items-center gap-1">
+ <Users2 className="h-3.5 w-3.5" />
+ {t("{count} members", {
+ count: String(team.members.length),
+ })}
+ </span>
+ <span className="flex items-center gap-1">
+ <Globe className="h-3.5 w-3.5" />
+ {t("{count} sites", {
+ count: String(team.sites.length),
+ })}
+ </span>
+ {team.siteRole && (
+ <span className="flex items-center gap-1">
+ <ShieldCheck className="h-3.5 w-3.5" />
+ {t("Site role: {role}", { role: roleInfo(team.siteRole).label })}
+ </span>
+ )}
</div>
</div>
- {isExpanded && (
- <div className="border-t px-4 py-3">
- <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
- <div>
- <h4 className="text-sm font-medium mb-2 flex items-center gap-1.5">
- <Users2 className="h-3.5 w-3.5" />
- {t("Members")}
- </h4>
- {team.members.length === 0 ? (
- <p className="text-sm text-muted-foreground">
- {t("No members")}
- </p>
- ) : (
- <div className="space-y-1">
- {team.members.map((member) => (
- <div
- key={member.userId}
- className="text-sm py-1 px-5 rounded hover:bg-muted/50"
- >
- <span>{member.userName || member.userEmail}</span>
- {member.userName && (
- <span className="text-muted-foreground ml-2 text-xs">
- {member.userEmail}
- </span>
- )}
- </div>
- ))}
+ </div>
+ <div className="flex items-center gap-2 ml-4" onClick={e => e.stopPropagation()}>
+ <Button variant="ghost" size="smIcon" onClick={() => setEditingTeam(team)}>
+ <Pencil className="h-3.5 w-3.5" />
+ </Button>
+ <DeleteTeamDialog team={team} />
+ </div>
+ </div>
+ {isExpanded && (
+ <div className="border-t px-4 py-3">
+ <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
+ <div>
+ <h4 className="text-sm font-medium mb-2 flex items-center gap-1.5">
+ <Users2 className="h-3.5 w-3.5" />
+ {t("Members")}
+ </h4>
+ {team.members.length === 0 ? (
+ <p className="text-sm text-muted-foreground">{t("No members")}</p>
+ ) : (
+ <div className="space-y-1">
+ {team.members.map(member => (
+ <div key={member.userId} className="text-sm py-1 px-5 rounded hover:bg-muted/50">
+ <span>{member.userName || member.userEmail}</span>
+ {member.userName && (
+ <span className="text-muted-foreground ml-2 text-xs">{member.userEmail}</span>
+ )}
</div>
- )}
+ ))}
</div>
- <div>
- <h4 className="text-sm font-medium mb-2 flex items-center gap-1.5">
- <Globe className="h-3.5 w-3.5" />
- {t("Sites")}
- </h4>
- {team.sites.length === 0 ? (
- <p className="text-sm text-muted-foreground">
- {t("No sites")}
- </p>
- ) : (
- <div className="space-y-1">
- {team.sites.map((site) => (
- <div
- key={site.siteId}
- className="text-sm py-1 px-5 rounded hover:bg-muted/50"
- >
- {site.name}
- </div>
- ))}
+ )}
+ </div>
+ <div>
+ <h4 className="text-sm font-medium mb-2 flex items-center gap-1.5">
+ <Globe className="h-3.5 w-3.5" />
+ {t("Sites")}
+ </h4>
+ {team.sites.length === 0 ? (
+ <p className="text-sm text-muted-foreground">{t("No sites")}</p>
+ ) : (
+ <div className="space-y-1">
+ {team.sites.map(site => (
+ <div key={site.siteId} className="text-sm py-1 px-5 rounded hover:bg-muted/50">
+ {site.name}
</div>
- )}
+ ))}
</div>
- </div>
+ )}
</div>
- )}
+ </div>
</div>
- );
- })}
- </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
)}
{/* Edit Team Dialog */}
<CreateEditTeamDialog
team={editingTeam || undefined}
open={!!editingTeam}
- onOpenChange={(open) => {
+ onOpenChange={open => {
if (!open) setEditingTeam(null);
}}
/>
diff --git a/client/src/app/transfer/[transferId]/page.test.tsx b/client/src/app/transfer/[transferId]/page.test.tsx
new file mode 100644
index 000000000..129ca160b
--- /dev/null
+++ b/client/src/app/transfer/[transferId]/page.test.tsx
@@ -0,0 +1,209 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { ApiError } from "@/api/utils";
+
+import SiteTransferPage from "./page";
+
+const mocks = vi.hoisted(() => ({
+ session: { data: null as { user: { email: string } } | null, isPending: false },
+ incoming: { data: undefined as unknown, error: null as unknown, isLoading: false },
+ organizations: [] as { id: string; name: string; permissions: string[] }[],
+ accept: vi.fn(),
+ decline: vi.fn(),
+ push: vi.fn(),
+ createOrganization: vi.fn(),
+ setActive: vi.fn(),
+ signOut: vi.fn(),
+ sendVerificationEmail: vi.fn(async () => ({ error: null })),
+}));
+
+vi.mock("next-intl", () => ({
+ useExtracted: () => (message: string, values?: Record<string, unknown>) =>
+ values ? message.replace(/\{(\w+)\}/g, (_, key: string) => String(values[key])) : message,
+}));
+
+vi.mock("next/navigation", () => ({
+ useParams: () => ({ transferId: "tr_1" }),
+ useRouter: () => ({ push: mocks.push }),
+}));
+
+vi.mock("@/lib/auth", () => ({
+ authClient: {
+ useSession: () => mocks.session,
+ signOut: mocks.signOut,
+ sendVerificationEmail: mocks.sendVerificationEmail,
+ organization: { create: mocks.createOrganization, setActive: mocks.setActive },
+ },
+}));
+
+vi.mock("@/lib/store", () => ({ getTimezone: () => "UTC" }));
+
+vi.mock("@/components/RybbitLogo", () => ({ RybbitLogo: () => null }));
+
+vi.mock("@/api/admin/hooks/useOrganizations", () => ({
+ USER_ORGANIZATIONS_QUERY_KEY: "userOrganizations",
+ useUserOrganizations: () => ({ data: mocks.organizations, isLoading: false }),
+}));
+
+vi.mock("@/api/admin/hooks/useSiteTransfers", () => ({
+ useIncomingSiteTransfer: () => mocks.incoming,
+ useAcceptSiteTransfer: () => ({ mutateAsync: mocks.accept }),
+ useDeclineSiteTransfer: () => ({ mutate: mocks.decline, isPending: false }),
+}));
+
+vi.mock("@/app/invitation/components/login", () => ({
+ Login: ({ callbackURL }: { callbackURL: string }) => <div>login form returning to {callbackURL}</div>,
+}));
+
+vi.mock("@/app/invitation/components/signup", () => ({
+ Signup: ({ callbackURL }: { callbackURL: string }) => <div>signup form returning to {callbackURL}</div>,
+}));
+
+const transfer = {
+ id: "tr_1",
+ site: { siteId: 42, name: "Acme", domain: "acme.dev" },
+ sourceOrganizationId: "org-source",
+ sourceOrganizationName: "Acme Agency",
+ sentBy: "[email protected]",
+ expiresAt: "2026-10-06T12:00:00.000Z",
+};
+
+function renderPage() {
+ return render(
+ <QueryClientProvider client={new QueryClient()}>
+ <SiteTransferPage />
+ </QueryClientProvider>
+ );
+}
+
+beforeEach(() => {
+ mocks.session = { data: { user: { email: "[email protected]" } }, isPending: false };
+ mocks.incoming = { data: transfer, error: null, isLoading: false };
+ mocks.organizations = [];
+ mocks.accept.mockResolvedValue({ success: true, siteId: 42, organizationId: "org-mine" });
+ mocks.setActive.mockResolvedValue({ data: {}, error: null });
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe("site transfer page", () => {
+ it("asks a signed-out visitor to sign in, then brings them back to the link", () => {
+ mocks.session = { data: null, isPending: false };
+ renderPage();
+
+ expect(screen.getByText("Sign in with the email address the transfer was sent to.")).toBeTruthy();
+ expect(screen.getByText("signup form returning to /transfer/tr_1")).toBeTruthy();
+ });
+
+ it("names the right address when signed in as someone else", () => {
+ mocks.incoming = {
+ data: undefined,
+ error: new ApiError("This transfer was sent to a different email address", 403, {
+ reason: "wrong_account",
+ recipientEmailHint: "gβ€’β€’@example.com",
+ }),
+ isLoading: false,
+ };
+ renderPage();
+
+ expect(screen.getByText("This transfer was sent to gβ€’β€’@example.com. Sign in with that address.")).toBeTruthy();
+ expect(screen.getByText("Signed in as [email protected]")).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Sign out" })).toBeTruthy();
+ });
+
+ it("asks an unverified recipient to verify their address first", async () => {
+ mocks.incoming = {
+ data: undefined,
+ error: new ApiError("Verify your email address to accept this transfer", 403, { reason: "email_unverified" }),
+ isLoading: false,
+ };
+ renderPage();
+
+ fireEvent.click(screen.getByRole("button", { name: "Send verification email" }));
+
+ await waitFor(() => expect(screen.getByText("Verification email sent. Check your inbox.")).toBeTruthy());
+ expect(mocks.sendVerificationEmail).toHaveBeenCalledWith({
+ email: "[email protected]",
+ callbackURL: expect.stringMatching(/\/transfer\/tr_1$/),
+ });
+ });
+
+ it("says a dead link is no longer valid", () => {
+ mocks.incoming = {
+ data: undefined,
+ error: new ApiError("This transfer link is no longer valid", 404, {}),
+ isLoading: false,
+ };
+ renderPage();
+
+ expect(screen.getByText("This link is no longer valid")).toBeTruthy();
+ });
+
+ it("moves the site into an organization the recipient manages, then opens it there", async () => {
+ mocks.organizations = [
+ { id: "org-source", name: "Acme Agency", permissions: ["sites:create"] },
+ { id: "org-viewer", name: "Read Only", permissions: ["sites:read"] },
+ { id: "org-mine", name: "Ada's Org", permissions: ["sites:read", "sites:create"] },
+ ];
+ renderPage();
+
+ expect(screen.getByText("[email protected] is transferring this site to you from Acme Agency.")).toBeTruthy();
+ fireEvent.click(screen.getByRole("button", { name: "Accept transfer" }));
+
+ await waitFor(() => expect(mocks.push).toHaveBeenCalledWith("/42"));
+ expect(mocks.accept).toHaveBeenCalledWith("org-mine");
+ expect(mocks.setActive).toHaveBeenCalledWith({ organizationId: "org-mine" });
+ expect(mocks.createOrganization).not.toHaveBeenCalled();
+ });
+
+ it("creates an organization first when the recipient manages none", async () => {
+ mocks.createOrganization.mockResolvedValue({ data: { id: "org-new" }, error: null });
+ mocks.accept.mockResolvedValue({ success: true, siteId: 42, organizationId: "org-new" });
+ renderPage();
+
+ const accept = screen.getByRole("button", { name: "Accept transfer" });
+ expect(accept.hasAttribute("disabled")).toBe(true);
+ fireEvent.change(screen.getByLabelText("Create an organization"), { target: { value: "Ada Labs" } });
+ fireEvent.click(accept);
+
+ await waitFor(() => expect(mocks.push).toHaveBeenCalledWith("/42"));
+ expect(mocks.createOrganization).toHaveBeenCalledWith({
+ name: "Ada Labs",
+ slug: expect.stringMatching(/^ada-labs-/),
+ });
+ expect(mocks.accept).toHaveBeenCalledWith("org-new");
+ expect(mocks.setActive).toHaveBeenCalledWith({ organizationId: "org-new" });
+ });
+
+ it("shows why accepting failed and stays on the page", async () => {
+ mocks.organizations = [{ id: "org-mine", name: "Ada's Org", permissions: ["sites:create"] }];
+ mocks.accept.mockRejectedValue(new Error("The site has moved since this transfer was sent"));
+ renderPage();
+
+ fireEvent.click(screen.getByRole("button", { name: "Accept transfer" }));
+
+ expect(await screen.findByText("The site has moved since this transfer was sent")).toBeTruthy();
+ expect(mocks.push).not.toHaveBeenCalled();
+ });
+
+ it("declines only after confirming", () => {
+ mocks.organizations = [{ id: "org-mine", name: "Ada's Org", permissions: ["sites:create"] }];
+ renderPage();
+
+ fireEvent.click(screen.getByRole("button", { name: "Decline" }));
+ expect(screen.getByRole("alertdialog").textContent).toContain(
+ "acme.dev stays with Acme Agency, and this link stops working."
+ );
+ expect(mocks.decline).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole("button", { name: "Decline transfer" }));
+ expect(mocks.decline).toHaveBeenCalledTimes(1);
+ mocks.decline.mock.calls[0][1].onSuccess();
+ expect(mocks.push).toHaveBeenCalledWith("/");
+ });
+});
diff --git a/client/src/app/transfer/[transferId]/page.tsx b/client/src/app/transfer/[transferId]/page.tsx
new file mode 100644
index 000000000..e353d7853
--- /dev/null
+++ b/client/src/app/transfer/[transferId]/page.tsx
@@ -0,0 +1,400 @@
+"use client";
+
+import { useQueryClient } from "@tanstack/react-query";
+import { AlertCircle } from "lucide-react";
+import { DateTime } from "luxon";
+import { useExtracted } from "next-intl";
+import { useParams, useRouter } from "next/navigation";
+import { useState } from "react";
+
+import type { IncomingSiteTransfer } from "@/api/admin/endpoints/siteTransfers";
+import { USER_ORGANIZATIONS_QUERY_KEY, useUserOrganizations } from "@/api/admin/hooks/useOrganizations";
+import {
+ useAcceptSiteTransfer,
+ useDeclineSiteTransfer,
+ useIncomingSiteTransfer,
+} from "@/api/admin/hooks/useSiteTransfers";
+import { ApiError } from "@/api/utils";
+import { Login } from "@/app/invitation/components/login";
+import { Signup } from "@/app/invitation/components/signup";
+import { Favicon } from "@/components/Favicon";
+import { ThreeDotLoader } from "@/components/Loaders";
+import { RybbitLogo } from "@/components/RybbitLogo";
+import {
+ AlertDialog,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from "@/components/ui/alert-dialog";
+import { Alert, AlertDescription } from "@/components/ui/alert";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { authClient } from "@/lib/auth";
+import { getTimezone } from "@/lib/store";
+
+// The recipient's side of a site transfer (see server/src/api/sites/siteTransfers.ts):
+// the emailed link lands here, and the recipient, signed in with the address it
+// was sent to, moves the site into an organization they manage.
+
+function slugFromName(name: string) {
+ const base = name
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "");
+ return `${base || "org"}-${Math.random().toString(36).slice(2, 6)}`;
+}
+
+function PageCard({ title, children }: { title: string; children: React.ReactNode }) {
+ return (
+ <Card className="w-full max-w-md p-1">
+ <CardHeader>
+ <RybbitLogo width={32} height={32} />
+ <CardTitle className="text-2xl flex justify-center text-center">{title}</CardTitle>
+ </CardHeader>
+ <CardContent>{children}</CardContent>
+ </Card>
+ );
+}
+
+function SignInToAccept({ transferId }: { transferId: string }) {
+ const t = useExtracted();
+ const [activeTab, setActiveTab] = useState<"login" | "signup">("signup");
+ // Brings OAuth sign-ins back here.
+ const callbackURL = `/transfer/${encodeURIComponent(transferId)}`;
+
+ return (
+ <PageCard title={t("Accept a site transfer")}>
+ <p className="text-center text-sm text-muted-foreground -mt-2 mb-6">
+ {t("Sign in with the email address the transfer was sent to.")}
+ </p>
+ <Tabs value={activeTab} onValueChange={value => setActiveTab(value as "login" | "signup")}>
+ <TabsList className="grid w-full grid-cols-2 mb-6">
+ <TabsTrigger value="signup">{t("Sign Up")}</TabsTrigger>
+ <TabsTrigger value="login">{t("Login")}</TabsTrigger>
+ </TabsList>
+ <TabsContent value="login">
+ <Login callbackURL={callbackURL} />
+ </TabsContent>
+ <TabsContent value="signup">
+ <Signup callbackURL={callbackURL} />
+ </TabsContent>
+ </Tabs>
+ </PageCard>
+ );
+}
+
+function WrongAccount({ recipientEmail, currentEmail }: { recipientEmail: string; currentEmail: string }) {
+ const t = useExtracted();
+ const queryClient = useQueryClient();
+ const [isSigningOut, setIsSigningOut] = useState(false);
+
+ const signOut = async () => {
+ setIsSigningOut(true);
+ queryClient.clear();
+ await authClient.signOut();
+ // Back to this page signed out, where the sign-in form returns here.
+ window.location.reload();
+ };
+
+ return (
+ <PageCard title={t("Accept a site transfer")}>
+ <div className="flex flex-col gap-4 text-center">
+ <p className="text-sm">
+ {t("This transfer was sent to {recipientEmail}. Sign in with that address.", { recipientEmail })}
+ </p>
+ <p className="text-xs text-muted-foreground">{t("Signed in as {email}", { email: currentEmail })}</p>
+ <Button onClick={signOut} loading={isSigningOut} loadingLabel={t("Signing out...")} className="w-full">
+ {t("Sign out")}
+ </Button>
+ </div>
+ </PageCard>
+ );
+}
+
+function VerifyEmail({ transferId, email }: { transferId: string; email: string }) {
+ const t = useExtracted();
+ const [status, setStatus] = useState<"idle" | "sending" | "sent" | "error">("idle");
+
+ const send = async () => {
+ setStatus("sending");
+ // Opening the emailed link verifies the address and brings them back here.
+ const { error } = await authClient.sendVerificationEmail({
+ email,
+ callbackURL: `${window.location.origin}/transfer/${encodeURIComponent(transferId)}`,
+ });
+ setStatus(error ? "error" : "sent");
+ };
+
+ return (
+ <PageCard title={t("Verify your email to accept this transfer")}>
+ <div className="flex flex-col gap-4 text-center">
+ <p className="text-sm">{t("We'll send a link to {email}. Open it, then come back to this page.", { email })}</p>
+ {status === "sent" ? (
+ <p className="text-sm text-muted-foreground">{t("Verification email sent. Check your inbox.")}</p>
+ ) : (
+ <Button onClick={send} loading={status === "sending"} className="w-full">
+ {t("Send verification email")}
+ </Button>
+ )}
+ {status === "error" && (
+ <Alert variant="destructive">
+ <AlertCircle className="h-4 w-4" />
+ <AlertDescription>{t("Couldn't send the email. Try again in a moment.")}</AlertDescription>
+ </Alert>
+ )}
+ </div>
+ </PageCard>
+ );
+}
+
+function InvalidLink() {
+ const t = useExtracted();
+ const router = useRouter();
+
+ return (
+ <PageCard title={t("This link is no longer valid")}>
+ <div className="flex flex-col gap-4 text-center">
+ <p className="text-sm text-muted-foreground">
+ {t("The transfer may have expired, been cancelled, or already been accepted.")}
+ </p>
+ <Button variant="outline" onClick={() => router.push("/")} className="w-full">
+ {t("Go to dashboard")}
+ </Button>
+ </div>
+ </PageCard>
+ );
+}
+
+function AcceptTransfer({ transfer }: { transfer: IncomingSiteTransfer }) {
+ const t = useExtracted();
+ const router = useRouter();
+ const queryClient = useQueryClient();
+ const { data: organizations, isLoading: isLoadingOrganizations } = useUserOrganizations();
+ const acceptTransfer = useAcceptSiteTransfer(transfer.id);
+ const declineTransfer = useDeclineSiteTransfer(transfer.id);
+
+ const [selectedOrganizationId, setSelectedOrganizationId] = useState("");
+ const [organizationName, setOrganizationName] = useState("");
+ // Stays set once accepted, while we navigate to the site.
+ const [isAccepting, setIsAccepting] = useState(false);
+ const [confirmDeclineOpen, setConfirmDeclineOpen] = useState(false);
+ const [error, setError] = useState("");
+
+ // Organizations the recipient may add sites to, other than the one it's leaving.
+ const targets = (organizations ?? []).filter(
+ org => org.permissions.includes("sites:create") && org.id !== transfer.sourceOrganizationId
+ );
+ const targetId = selectedOrganizationId || targets[0]?.id;
+ const { domain } = transfer.site;
+ const expires = DateTime.fromISO(transfer.expiresAt).setZone(getTimezone()).toLocaleString(DateTime.DATE_MED);
+
+ const handleAccept = async () => {
+ setError("");
+ setIsAccepting(true);
+ try {
+ let organizationId = targetId;
+ if (!organizationId) {
+ const name = organizationName.trim();
+ const { data, error: createError } = await authClient.organization.create({ name, slug: slugFromName(name) });
+ if (createError) {
+ throw new Error(createError.message || t("Failed to create organization"));
+ }
+ if (!data?.id) {
+ throw new Error(t("No organization ID returned"));
+ }
+ organizationId = data.id;
+ // If accepting fails from here, the new organization shows up as the target to retry with.
+ void queryClient.invalidateQueries({ queryKey: [USER_ORGANIZATIONS_QUERY_KEY] });
+ }
+
+ const result = await acceptTransfer.mutateAsync(organizationId);
+ await authClient.organization.setActive({ organizationId: result.organizationId });
+ router.push(`/${result.siteId}`);
+ } catch (acceptError) {
+ setError(acceptError instanceof Error ? acceptError.message : String(acceptError));
+ setIsAccepting(false);
+ }
+ };
+
+ const handleDecline = () => {
+ setError("");
+ declineTransfer.mutate(undefined, {
+ onSuccess: () => router.push("/"),
+ onError: declineError => {
+ setConfirmDeclineOpen(false);
+ setError(declineError.message || t("Failed to decline the transfer"));
+ },
+ });
+ };
+
+ return (
+ <PageCard title={t("Accept {domain}", { domain })}>
+ <div className="flex flex-col gap-5">
+ <p className="text-center text-sm text-muted-foreground -mt-2">
+ {transfer.sentBy
+ ? t("{sender} is transferring this site to you from {organization}.", {
+ sender: transfer.sentBy,
+ organization: transfer.sourceOrganizationName,
+ })
+ : t("{organization} is transferring this site to you.", {
+ organization: transfer.sourceOrganizationName,
+ })}
+ </p>
+
+ <div className="flex items-center gap-3 rounded-lg border border-neutral-150 px-4 py-3 dark:border-neutral-800">
+ <Favicon domain={domain} className="h-5 w-5 shrink-0" />
+ <div className="min-w-0">
+ <div className="truncate text-sm font-medium">{transfer.site.name || domain}</div>
+ {transfer.site.name && transfer.site.name !== domain && (
+ <div className="truncate text-xs text-muted-foreground">{domain}</div>
+ )}
+ </div>
+ </div>
+
+ {isLoadingOrganizations ? (
+ <ThreeDotLoader className="py-4" />
+ ) : targets.length > 0 ? (
+ <div className="grid gap-2">
+ <Label htmlFor="transfer-organization">{t("Move it into")}</Label>
+ <Select value={targetId} onValueChange={setSelectedOrganizationId}>
+ <SelectTrigger id="transfer-organization">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {targets.map(org => (
+ <SelectItem key={org.id} value={org.id}>
+ {org.name}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <p className="text-xs text-muted-foreground">{t("The site moves there with all its data.")}</p>
+ </div>
+ ) : (
+ <div className="grid gap-2">
+ <Label htmlFor="transfer-new-organization">{t("Create an organization")}</Label>
+ <Input
+ id="transfer-new-organization"
+ placeholder={t("Organization name")}
+ value={organizationName}
+ onChange={event => setOrganizationName(event.target.value)}
+ />
+ <p className="text-xs text-muted-foreground">
+ {t("You don't manage an organization yet. The site moves into this new one.")}
+ </p>
+ </div>
+ )}
+
+ {error && (
+ <Alert variant="destructive">
+ <AlertCircle className="h-4 w-4" />
+ <AlertDescription>{error}</AlertDescription>
+ </Alert>
+ )}
+
+ <div className="flex flex-col gap-2">
+ <Button
+ variant="success"
+ className="w-full"
+ onClick={handleAccept}
+ loading={isAccepting}
+ loadingLabel={t("Accepting...")}
+ disabled={isLoadingOrganizations || (!targetId && !organizationName.trim()) || declineTransfer.isPending}
+ >
+ {t("Accept transfer")}
+ </Button>
+ <AlertDialog
+ open={confirmDeclineOpen}
+ onOpenChange={next => {
+ if (!declineTransfer.isPending) setConfirmDeclineOpen(next);
+ }}
+ >
+ <AlertDialogTrigger asChild>
+ <Button variant="ghost" className="w-full" disabled={isAccepting || declineTransfer.isPending}>
+ {t("Decline")}
+ </Button>
+ </AlertDialogTrigger>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>{t("Decline this transfer?")}</AlertDialogTitle>
+ <AlertDialogDescription>
+ {t("{domain} stays with {organization}, and this link stops working.", {
+ domain,
+ organization: transfer.sourceOrganizationName,
+ })}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel disabled={declineTransfer.isPending}>{t("Cancel")}</AlertDialogCancel>
+ {/* A plain Button, so the dialog stays open while the request runs. */}
+ <Button variant="destructive" onClick={handleDecline} loading={declineTransfer.isPending}>
+ {t("Decline transfer")}
+ </Button>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+
+ <p className="text-center text-xs text-muted-foreground">{t("This link expires {date}.", { date: expires })}</p>
+ </div>
+ </PageCard>
+ );
+}
+
+function IncomingTransfer({ transferId, currentEmail }: { transferId: string; currentEmail: string }) {
+ const t = useExtracted();
+ const { data: transfer, error, isLoading } = useIncomingSiteTransfer(transferId);
+
+ if (isLoading) {
+ return <ThreeDotLoader />;
+ }
+ if (error instanceof ApiError && error.status === 403) {
+ const body = error.body as { reason?: string; recipientEmailHint?: string } | undefined;
+ if (body?.reason === "email_unverified") {
+ return <VerifyEmail transferId={transferId} email={currentEmail} />;
+ }
+ // The server only reveals a masked address, e.g. "tβ€’β€’@example.org".
+ return <WrongAccount recipientEmail={body?.recipientEmailHint ?? ""} currentEmail={currentEmail} />;
+ }
+ if (error instanceof ApiError && error.status === 404) {
+ return <InvalidLink />;
+ }
+ if (error || !transfer) {
+ return (
+ <PageCard title={t("Accept a site transfer")}>
+ <Alert variant="destructive">
+ <AlertCircle className="h-4 w-4" />
+ <AlertDescription>{error?.message || t("Failed to load the transfer")}</AlertDescription>
+ </Alert>
+ </PageCard>
+ );
+ }
+ return <AcceptTransfer transfer={transfer} />;
+}
+
+export default function SiteTransferPage() {
+ const { transferId } = useParams<{ transferId: string }>();
+ const { data: session, isPending } = authClient.useSession();
+
+ return (
+ <div className="flex flex-col min-h-dvh">
+ <div className="flex justify-center items-center grow p-4">
+ {isPending ? (
+ <ThreeDotLoader />
+ ) : !session?.user ? (
+ <SignInToAccept transferId={transferId} />
+ ) : (
+ <IncomingTransfer transferId={transferId} currentEmail={session.user.email} />
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/AuthenticationGuard.tsx b/client/src/components/AuthenticationGuard.tsx
index b34364075..aef90b86f 100644
--- a/client/src/components/AuthenticationGuard.tsx
+++ b/client/src/components/AuthenticationGuard.tsx
@@ -6,6 +6,8 @@ import { userStore } from "../lib/userStore";
import { useGetSiteIsPublic } from "../api/admin/hooks/useSites";
const PUBLIC_ROUTES = ["/login", "/signup", "/try", "/invitation", "/reset-password", "/as/callback", "/auth/consent"];
+// Pages under these prefixes show their own sign-in form, e.g. /transfer/<id>.
+const PUBLIC_ROUTE_PREFIXES = ["/transfer/"];
export function AuthenticationGuard() {
const { user, isPending } = userStore();
@@ -33,6 +35,7 @@ export function AuthenticationGuard() {
!isCheckingPublic &&
!user &&
!PUBLIC_ROUTES.includes(pathname) &&
+ !PUBLIC_ROUTE_PREFIXES.some(prefix => pathname.startsWith(prefix)) &&
!isPublicSite &&
!hasPrivateKey
) {
diff --git a/client/src/components/DisabledOverlay.tsx b/client/src/components/DisabledOverlay.tsx
index d83e1cd74..78b232d52 100644
--- a/client/src/components/DisabledOverlay.tsx
+++ b/client/src/components/DisabledOverlay.tsx
@@ -3,6 +3,7 @@ import Link from "next/link";
import { useExtracted } from "next-intl";
import React, { ReactNode, useMemo, useRef, useEffect, useState } from "react";
import { useCurrentSite } from "../api/admin/hooks/useSites";
+import { useCanInOrg } from "../hooks/usePermissions";
import { DEFAULT_EVENT_LIMIT } from "../lib/subscription/constants";
import { Button } from "./ui/button";
import { authClient } from "../lib/auth";
@@ -89,6 +90,8 @@ export const DisabledOverlay: React.FC<DisabledOverlayProps> = ({
requiredPlan = "standard",
}) => {
const { subscription, site } = useCurrentSite();
+ // Upgrading is a billing action for the site's organization.
+ const canUpgrade = useCanInOrg("billing:manage", site?.organizationId ?? undefined);
const { data } = authClient.useSession();
@@ -209,7 +212,7 @@ export const DisabledOverlay: React.FC<DisabledOverlayProps> = ({
>
{showMessage && (
<div className="flex items-center justify-center">
- {site?.isOwner ? <OwnerMessage message={message} featurePath={featurePath} requiredPlan={requiredPlan} /> : <UserMessage message={message} featurePath={featurePath} />}
+ {canUpgrade ? <OwnerMessage message={message} featurePath={featurePath} requiredPlan={requiredPlan} /> : <UserMessage message={message} featurePath={featurePath} />}
</div>
)}
</div>
diff --git a/client/src/components/FreePlanBanner.tsx b/client/src/components/FreePlanBanner.tsx
index afbcc4960..ec7d408fe 100644
--- a/client/src/components/FreePlanBanner.tsx
+++ b/client/src/components/FreePlanBanner.tsx
@@ -2,12 +2,14 @@ import { ArrowRight } from "lucide-react";
import { useExtracted } from "next-intl";
import Link from "next/link";
import { useCurrentSite } from "../api/admin/hooks/useSites";
+import { useCanInOrg } from "../hooks/usePermissions";
import { DEFAULT_EVENT_LIMIT } from "../lib/subscription/constants";
import { Button } from "./ui/button";
export function FreePlanBanner() {
const t = useExtracted();
const { site, subscription } = useCurrentSite();
+ const canUpgrade = useCanInOrg("billing:manage", site?.organizationId ?? undefined);
if (!site) return null;
@@ -27,7 +29,7 @@ export function FreePlanBanner() {
})}
</span>
</div>
- {site.isOwner && (
+ {canUpgrade && (
<Button variant="success" size="sm" asChild>
<Link href="/subscribe">
{t("Upgrade")} <ArrowRight className="ml-1 h-3 w-3" />
diff --git a/client/src/components/IdentifiedBadge.tsx b/client/src/components/IdentifiedBadge.tsx
index 3f9e1f82f..4c561e153 100644
--- a/client/src/components/IdentifiedBadge.tsx
+++ b/client/src/components/IdentifiedBadge.tsx
@@ -3,7 +3,7 @@
import { IdCard } from "lucide-react";
import { useExtracted } from "next-intl";
import { useState } from "react";
-import { userStore } from "../lib/userStore";
+import { useCanOnSite } from "../hooks/usePermissions";
import { EditTraitsDialog } from "./EditTraitsDialog";
import { Badge } from "./ui/badge";
import { Tooltip, TooltipContent, TooltipTrigger } from "./ui/tooltip";
@@ -11,19 +11,19 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "./ui/tooltip";
interface IdentifiedBadgeProps {
className?: string;
traits?: Record<string, unknown> | null;
- // Identified user id; when set and the viewer is signed in, clicking the
- // badge opens the trait editor
+ // Identified user id; when set and the viewer may edit users (users:write),
+ // clicking the badge opens the trait editor
userId?: string;
}
export function IdentifiedBadge({ className, traits, userId }: IdentifiedBadgeProps) {
const t = useExtracted();
- const { user } = userStore();
+ const canWriteUsers = useCanOnSite("users:write");
const [editOpen, setEditOpen] = useState(false);
// Lazily mounted so lists full of badges don't each carry a dialog
const [dialogMounted, setDialogMounted] = useState(false);
- const canEdit = !!userId && !!user;
+ const canEdit = !!userId && canWriteUsers;
// Filter out null/undefined values and format for display
const traitEntries = traits
diff --git a/client/src/components/SiteSettings/GeneralTab.tsx b/client/src/components/SiteSettings/GeneralTab.tsx
index 9b714938b..7f89f7280 100644
--- a/client/src/components/SiteSettings/GeneralTab.tsx
+++ b/client/src/components/SiteSettings/GeneralTab.tsx
@@ -24,6 +24,7 @@ import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Switch } from "@/components/ui/switch";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { deleteSite, moveSite, updateSiteConfig, SiteResponse } from "@/api/admin/endpoints";
import { adminMoveSite } from "@/api/admin/endpoints/adminSites";
@@ -33,10 +34,16 @@ import { RemoteOrganizationCombobox } from "@/app/admin/components/shared/Remote
import { normalizeDomain } from "@/lib/utils";
import { SettingRow, SettingsSection, SettingsSections } from "./SettingsSection";
+import { TransferSiteSection } from "./TransferSiteSection";
interface GeneralTabProps {
siteMetadata: SiteResponse;
+ /** No sites:configure: the name, domain and privacy settings are read-only. */
disabled?: boolean;
+ /** sites:delete on this site. */
+ canDelete?: boolean;
+ /** sites:transfer on this site. */
+ canTransfer?: boolean;
onClose?: () => void;
onPublicChange?: (checked: boolean) => void;
adminMode?: boolean;
@@ -57,6 +64,8 @@ interface ToggleConfig {
export function GeneralTab({
siteMetadata,
disabled = false,
+ canDelete = false,
+ canTransfer = false,
onClose,
onPublicChange,
adminMode = false,
@@ -78,10 +87,10 @@ export function GeneralTab({
const [targetOrgName, setTargetOrgName] = useState("");
const [isMoving, setIsMoving] = useState(false);
- // Organizations the user can move the site into: those they administer,
- // excluding the site's current organization.
+ // Organizations the user can move the site into: those they may create
+ // sites in, excluding the site's current organization.
const moveTargets = (userOrganizations ?? []).filter(
- org => (org.role === "admin" || org.role === "owner") && org.id !== siteMetadata.organizationId
+ org => org.permissions?.includes("sites:create") && org.id !== siteMetadata.organizationId
);
const [toggleStates, setToggleStates] = useState({
@@ -345,7 +354,7 @@ export function GeneralTab({
))}
</SettingsSection>
- {!disabled && (adminMode || moveTargets.length > 0) && (
+ {canTransfer && (adminMode || moveTargets.length > 0) && (
<SettingsSection
title={t("Move to Organization")}
description={t(
@@ -411,6 +420,9 @@ export function GeneralTab({
</SettingsSection>
)}
+ {/* A person-to-person hand-off; the admin panel moves sites directly instead. */}
+ {canTransfer && !adminMode && <TransferSiteSection siteId={siteMetadata.siteId} />}
+
<SettingsSection>
<div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-red-200 px-4 py-3 dark:border-red-500/25">
<div>
@@ -420,12 +432,27 @@ export function GeneralTab({
</p>
</div>
<AlertDialog>
- <AlertDialogTrigger asChild>
- <Button variant="destructive" disabled={disabled}>
- <AlertTriangle className="h-4 w-4" />
- {t("Delete Site")}
- </Button>
- </AlertDialogTrigger>
+ {canDelete ? (
+ <AlertDialogTrigger asChild>
+ <Button variant="destructive">
+ <AlertTriangle className="h-4 w-4" />
+ {t("Delete Site")}
+ </Button>
+ </AlertDialogTrigger>
+ ) : (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ {/* A disabled button gets no pointer events, so the tooltip hangs off this wrapper. */}
+ <span tabIndex={0} className="inline-flex">
+ <Button variant="destructive" disabled>
+ <AlertTriangle className="h-4 w-4" />
+ {t("Delete Site")}
+ </Button>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>{t("Your role can't delete sites")}</TooltipContent>
+ </Tooltip>
+ )}
<AlertDialogContent
onEscapeKeyDown={event => {
if (isDeleting) event.preventDefault();
diff --git a/client/src/components/SiteSettings/SiteSettings.tsx b/client/src/components/SiteSettings/SiteSettings.tsx
index 7d51a5907..f48df385d 100644
--- a/client/src/components/SiteSettings/SiteSettings.tsx
+++ b/client/src/components/SiteSettings/SiteSettings.tsx
@@ -19,7 +19,7 @@ import { Button } from "@/components/ui/button";
import { Dialog, DialogClose, DialogContent, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Switch } from "@/components/ui/switch";
import { toast } from "@/components/ui/sonner";
-import { authClient } from "@/lib/auth";
+import { useSitePermissions } from "@/hooks/usePermissions";
import { cn } from "@/lib/utils";
import { ScriptBuilder } from "./ScriptBuilder";
@@ -32,7 +32,6 @@ import { EmbedTab } from "./EmbedTab";
import { DashboardEmbedTab } from "./DashboardEmbedTab";
import { UsageTab } from "./UsageTab";
import { useGetSite } from "../../api/admin/hooks/useSites";
-import { useUserOrganizations } from "../../api/admin/hooks/useOrganizations";
import { useGetSitesFromOrg } from "../../api/admin/hooks/useSites";
import { SiteResponse, updateSiteConfig } from "../../api/admin/endpoints";
import { IS_CLOUD } from "../../lib/const";
@@ -102,10 +101,9 @@ function SiteSettingsInner({
initialOpen?: boolean;
}) {
const t = useExtracted();
- const { data: session } = authClient.useSession();
- const { data: userOrganizationsData } = useUserOrganizations();
- const siteOrgMembership = userOrganizationsData?.find(org => org.id === siteMetadata.organizationId);
- const disabled = session?.user.role !== "admin" && (!siteOrgMembership?.role || siteOrgMembership.role === "member");
+ // What the viewer may change here. Controls they can't use stay visible but disabled.
+ const { can } = useSitePermissions(siteMetadata.siteId);
+ const canConfigure = can("sites:configure");
const [dialogOpen, setDialogOpen] = useState(initialOpen);
const [activeTab, setActiveTab] = useState<TabKey>("general");
@@ -213,17 +211,24 @@ function SiteSettingsInner({
<Switch
aria-label={t("Enable Embed Widget")}
checked={embedEnabled}
- disabled={togglingEmbed}
+ disabled={togglingEmbed || !canConfigure}
onCheckedChange={handleToggleEmbed}
/>
</label>
)}
</header>
<div className="flex-1 overflow-y-auto px-6 py-5">
+ {!canConfigure && activeTab !== "script" && activeTab !== "usage" && (
+ <p className="mb-4 rounded-md border border-neutral-200 px-3 py-2 text-xs text-muted-foreground dark:border-neutral-800">
+ {t("You can view these settings, but your role can't change them.")}
+ </p>
+ )}
{activeTab === "general" && (
<GeneralTab
siteMetadata={currentSiteMetadata}
- disabled={disabled}
+ disabled={!canConfigure}
+ canDelete={can("sites:delete")}
+ canTransfer={can("sites:transfer")}
onClose={() => setDialogOpen(false)}
onPublicChange={setSitePublic}
adminMode={adminMode}
@@ -232,14 +237,14 @@ function SiteSettingsInner({
{activeTab === "tracking" && (
<TrackingTab
siteMetadata={currentSiteMetadata}
- disabled={disabled}
+ disabled={!canConfigure}
adminMode={adminMode}
adminSubscription={adminOrganization?.subscription}
/>
)}
- {activeTab === "exclusions" && <ExclusionsTab siteId={siteMetadata.siteId} disabled={disabled} />}
+ {activeTab === "exclusions" && <ExclusionsTab siteId={siteMetadata.siteId} disabled={!canConfigure} />}
{activeTab === "integrations" && IS_CLOUD && (
- <IntegrationsTab disabled={disabled} siteId={siteMetadata.siteId} />
+ <IntegrationsTab disabled={!can("gsc:write")} siteId={siteMetadata.siteId} />
)}
{activeTab === "script" && (
<ScriptBuilder
@@ -252,9 +257,11 @@ function SiteSettingsInner({
<EmbedTab siteMetadata={currentSiteMetadata} embedEnabled={embedEnabled} />
)}
{activeTab === "dashboard-embed" && (
- <DashboardEmbedTab siteMetadata={currentSiteMetadata} disabled={disabled} />
+ <DashboardEmbedTab siteMetadata={currentSiteMetadata} disabled={!canConfigure} />
+ )}
+ {activeTab === "import" && (
+ <ImportManager siteId={siteMetadata.siteId} disabled={!can("imports:write")} />
)}
- {activeTab === "import" && <ImportManager siteId={siteMetadata.siteId} disabled={disabled} />}
{activeTab === "usage" && <UsageTab siteId={siteMetadata.siteId} />}
</div>
</main>
diff --git a/client/src/components/SiteSettings/TransferSiteSection.tsx b/client/src/components/SiteSettings/TransferSiteSection.tsx
new file mode 100644
index 000000000..726ab715b
--- /dev/null
+++ b/client/src/components/SiteSettings/TransferSiteSection.tsx
@@ -0,0 +1,107 @@
+"use client";
+
+import { DateTime } from "luxon";
+import { useExtracted } from "next-intl";
+import { useState } from "react";
+
+import { useCancelSiteTransfer, useCreateSiteTransfer, useSiteTransfer } from "@/api/admin/hooks/useSiteTransfers";
+import { CopyButton } from "@/components/interior/copy-button";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Skeleton } from "@/components/ui/skeleton";
+import { toast } from "@/components/ui/sonner";
+import { getTimezone } from "@/lib/store";
+
+import { SettingsSection } from "./SettingsSection";
+
+/**
+ * Hands the site to someone outside the organization: they get an emailed link,
+ * accept it into an organization they manage, and the site moves there. Render
+ * only for people with sites:transfer on the site.
+ */
+export function TransferSiteSection({ siteId }: { siteId: number }) {
+ const t = useExtracted();
+ const { data: transfer, isLoading } = useSiteTransfer(siteId);
+ const createTransfer = useCreateSiteTransfer(siteId);
+ const cancelTransfer = useCancelSiteTransfer(siteId);
+ const [email, setEmail] = useState("");
+
+ const handleSend = (event: React.FormEvent) => {
+ event.preventDefault();
+ const recipient = email.trim();
+ if (!recipient) return;
+ createTransfer.mutate(recipient, {
+ onSuccess: () => {
+ toast.success(t("Transfer sent to {email}", { email: recipient }));
+ setEmail("");
+ },
+ onError: error => toast.error(error.message || t("Failed to send the transfer")),
+ });
+ };
+
+ const handleCancel = () => {
+ cancelTransfer.mutate(undefined, {
+ onSuccess: () => toast.success(t("Transfer cancelled")),
+ onError: error => toast.error(error.message || t("Failed to cancel the transfer")),
+ });
+ };
+
+ return (
+ <SettingsSection
+ title={t("Transfer to someone else")}
+ description={t(
+ "The recipient gets an email and accepts the site into an organization they manage. It moves with all its data, except its Search Console connection."
+ )}
+ >
+ {isLoading ? (
+ <Skeleton className="h-9 w-full" />
+ ) : transfer ? (
+ <div className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-neutral-150 px-4 py-3 dark:border-neutral-800">
+ <p className="min-w-0 text-sm text-foreground">
+ {t("Pending transfer to {email} Β· expires {date}", {
+ email: transfer.recipientEmail,
+ date: DateTime.fromISO(transfer.expiresAt).setZone(getTimezone()).toLocaleString(DateTime.DATE_MED),
+ })}
+ </p>
+ <div className="flex shrink-0 gap-2">
+ <CopyButton
+ size="sm"
+ variant="outline"
+ value={transfer.url}
+ label={t("Copy link")}
+ onError={() => toast.error(t("Couldn't copy the link. Select it and copy it manually."))}
+ />
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={handleCancel}
+ loading={cancelTransfer.isPending}
+ loadingLabel={t("Cancelling...")}
+ >
+ {t("Cancel transfer")}
+ </Button>
+ </div>
+ </div>
+ ) : (
+ <form className="flex gap-2" onSubmit={handleSend}>
+ <Input
+ type="email"
+ aria-label={t("Recipient email")}
+ placeholder="[email protected]"
+ value={email}
+ onChange={event => setEmail(event.target.value)}
+ />
+ <Button
+ type="submit"
+ variant="outline"
+ loading={createTransfer.isPending}
+ loadingLabel={t("Sending...")}
+ disabled={!email.trim()}
+ >
+ {t("Send transfer")}
+ </Button>
+ </form>
+ )}
+ </SettingsSection>
+ );
+}
diff --git a/client/src/components/command-palette/CommandPalette.test.tsx b/client/src/components/command-palette/CommandPalette.test.tsx
index 31a7550d0..9c06b22ab 100644
--- a/client/src/components/command-palette/CommandPalette.test.tsx
+++ b/client/src/components/command-palette/CommandPalette.test.tsx
@@ -36,7 +36,10 @@ vi.mock("@uidotdev/usehooks", () => ({ useWindowSize: () => ({ width: 1280, heig
vi.mock("@/lib/auth", () => ({
authClient: {
- useSession: () => ({ data: mocks.signedIn ? { user: { id: "user-1" } } : null }),
+ useSession: () => ({
+ data: mocks.signedIn ? { user: { id: "user-1" }, session: { activeOrganizationId: "org-1" } } : null,
+ isPending: false,
+ }),
useActiveOrganization: () => ({ data: { id: "org-1" } }),
},
}));
@@ -58,7 +61,10 @@ vi.mock("@/api/admin/hooks/useSites", () => ({
}));
vi.mock("@/api/admin/hooks/useOrganizations", () => ({
- useUserOrganizations: () => ({ data: [{ id: "org-1", role: "owner" }] }),
+ useUserOrganizations: () => ({
+ data: [{ id: "org-1", role: "owner", permissions: ["members:manage", "teams:manage", "billing:manage"] }],
+ isLoading: false,
+ }),
}));
vi.mock("@/api/analytics/hooks/goals/useGetGoals", () => ({
diff --git a/client/src/components/command-palette/usePaletteCommands.tsx b/client/src/components/command-palette/usePaletteCommands.tsx
index 5a2800916..ff8d297ba 100644
--- a/client/src/components/command-palette/usePaletteCommands.tsx
+++ b/client/src/components/command-palette/usePaletteCommands.tsx
@@ -33,7 +33,6 @@ import { useExtracted } from "next-intl";
import { useTheme } from "next-themes";
import { usePathname, useRouter } from "next/navigation";
import type { ReactNode } from "react";
-import { useUserOrganizations } from "@/api/admin/hooks/useOrganizations";
import { useGetSite, useGetSitesFromOrg } from "@/api/admin/hooks/useSites";
import { useGetFunnels } from "@/api/analytics/hooks/funnels/useGetFunnels";
import { useGetGoals } from "@/api/analytics/hooks/goals/useGetGoals";
@@ -41,6 +40,7 @@ import { useGetDashboards } from "@/api/analytics/hooks/useDashboards";
import { HOTKEY_FOR_PRESET, PRESET_GROUPS, usePresetLabels } from "@/components/DateSelector/presets";
import { Favicon } from "@/components/Favicon";
import { useAppEnv } from "@/hooks/useIsProduction";
+import { useOrgPermissions } from "@/hooks/usePermissions";
import { authClient } from "@/lib/auth";
import { DEPLOYMENT, IS_CLOUD } from "@/lib/const";
import { getDashboardTimeForRange, setStoredDashboardDefaultTimeRange } from "@/lib/defaultTimeRange";
@@ -108,9 +108,7 @@ export function usePaletteCommands(entityCommands: PaletteCommand[]): {
const { data: activeOrganization } = authClient.useActiveOrganization();
const { data: orgSites } = useGetSitesFromOrg(activeOrganization?.id);
- const { data: userOrganizations } = useUserOrganizations();
- const role = userOrganizations?.find(org => org.id === activeOrganization?.id)?.role;
- const isAdminOrOwner = role === "admin" || role === "owner";
+ const { can } = useOrgPermissions(activeOrganization?.id);
const time = useStore(state => state.time);
const setTime = useStore(state => state.setTime);
@@ -233,38 +231,38 @@ export function usePaletteCommands(entityCommands: PaletteCommand[]): {
run: () => go("/settings/account"),
},
];
- // Same rule as the settings navigation: members can't manage the organization.
- if (isAdminOrOwner) {
- navigateCommands.push(
- {
- id: "nav:organization",
- group: "navigate",
- label: t("Organization"),
- keywords: t("settings members invitations"),
- icon: <Building2 />,
- current: pathname.startsWith("/settings/organization"),
- run: () => go("/settings/organization"),
- },
- {
- id: "nav:teams",
- group: "navigate",
- label: t("Teams"),
- icon: <Users />,
- current: pathname.startsWith("/settings/teams"),
- run: () => go("/settings/teams"),
- }
- );
- if (IS_CLOUD) {
- navigateCommands.push({
- id: "nav:billing",
- group: "navigate",
- label: t("Billing"),
- keywords: t("subscription plan invoices"),
- icon: <CreditCard />,
- current: pathname.startsWith("/settings/billing"),
- run: () => go("/settings/billing"),
- });
- }
+ // Same rules as the settings navigation.
+ if (can("members:manage")) {
+ navigateCommands.push({
+ id: "nav:organization",
+ group: "navigate",
+ label: t("Organization"),
+ keywords: t("settings members invitations"),
+ icon: <Building2 />,
+ current: pathname.startsWith("/settings/organization"),
+ run: () => go("/settings/organization"),
+ });
+ }
+ if (can("teams:manage")) {
+ navigateCommands.push({
+ id: "nav:teams",
+ group: "navigate",
+ label: t("Teams"),
+ icon: <Users />,
+ current: pathname.startsWith("/settings/teams"),
+ run: () => go("/settings/teams"),
+ });
+ }
+ if (IS_CLOUD && can("billing:manage")) {
+ navigateCommands.push({
+ id: "nav:billing",
+ group: "navigate",
+ label: t("Billing"),
+ keywords: t("subscription plan invoices"),
+ icon: <CreditCard />,
+ current: pathname.startsWith("/settings/billing"),
+ run: () => go("/settings/billing"),
+ });
}
const themeKeyword = t("Theme");
diff --git a/client/src/components/sidebar/NavigationSidebar.tsx b/client/src/components/sidebar/NavigationSidebar.tsx
index 114c89a8f..25fb486da 100644
--- a/client/src/components/sidebar/NavigationSidebar.tsx
+++ b/client/src/components/sidebar/NavigationSidebar.tsx
@@ -2,8 +2,7 @@
import { AppWindow, Building2, Combine, CreditCard, UserCircle, Users } from "lucide-react";
import { useExtracted } from "next-intl";
import { usePathname } from "next/navigation";
-import { useUserOrganizations } from "../../api/admin/hooks/useOrganizations";
-import { authClient } from "../../lib/auth";
+import { useOrgPermissions } from "../../hooks/usePermissions";
import { IS_CLOUD } from "../../lib/const";
import { OrganizationSelector } from "../OrganizationSelector";
import { Sidebar } from "./Sidebar";
@@ -11,14 +10,7 @@ import { Sidebar } from "./Sidebar";
export function NavigationSidebar() {
const t = useExtracted();
const pathname = usePathname();
- const { data: activeOrganization } = authClient.useActiveOrganization();
- const { data: userOrganizations } = useUserOrganizations();
-
- const currentMember = userOrganizations?.find(
- (org) => org.id === activeOrganization?.id
- );
- const isAdminOrOwner =
- currentMember?.role === "admin" || currentMember?.role === "owner";
+ const { can } = useOrgPermissions();
return (
<Sidebar.Root>
@@ -44,29 +36,29 @@ export function NavigationSidebar() {
href="/settings/account"
icon={<UserCircle className="w-4 h-4" />}
/>
- {isAdminOrOwner && (
- <>
- <Sidebar.Item
- label={t("Organization")}
- active={pathname === "/settings/organization"}
- href="/settings/organization"
- icon={<Building2 className="w-4 h-4" />}
- />
- <Sidebar.Item
- label={t("Teams")}
- active={pathname.startsWith("/settings/teams")}
- href="/settings/teams"
- icon={<Users className="w-4 h-4" />}
- />
- {IS_CLOUD && (
- <Sidebar.Item
- label={t("Billing")}
- active={pathname.startsWith("/settings/billing")}
- href="/settings/billing"
- icon={<CreditCard className="w-4 h-4" />}
- />
- )}
- </>
+ {can("members:manage") && (
+ <Sidebar.Item
+ label={t("Organization")}
+ active={pathname === "/settings/organization"}
+ href="/settings/organization"
+ icon={<Building2 className="w-4 h-4" />}
+ />
+ )}
+ {can("teams:manage") && (
+ <Sidebar.Item
+ label={t("Teams")}
+ active={pathname.startsWith("/settings/teams")}
+ href="/settings/teams"
+ icon={<Users className="w-4 h-4" />}
+ />
+ )}
+ {IS_CLOUD && can("billing:manage") && (
+ <Sidebar.Item
+ label={t("Billing")}
+ active={pathname.startsWith("/settings/billing")}
+ href="/settings/billing"
+ icon={<CreditCard className="w-4 h-4" />}
+ />
)}
</Sidebar.Items>
</Sidebar.Root>
diff --git a/client/src/hooks/usePermissions.ts b/client/src/hooks/usePermissions.ts
new file mode 100644
index 000000000..930d0f21b
--- /dev/null
+++ b/client/src/hooks/usePermissions.ts
@@ -0,0 +1,57 @@
+import type { OrgRole, Permission } from "@rybbit/shared";
+import { useUserOrganizations } from "../api/admin/hooks/useOrganizations";
+import { useGetSite } from "../api/admin/hooks/useSites";
+import { authClient } from "../lib/auth";
+
+/**
+ * What the signed-in user may do, as the server computed it. The client never
+ * works out permissions from role names: the server returns the permission
+ * list with each site (GET /sites/:id) and organization (GET
+ * /user/organizations), and these hooks only look things up in it. Hide or
+ * disable a control when its permission is missing β€” the server enforces the
+ * same permission regardless.
+ */
+export interface PermissionSet {
+ can: (permission: Permission) => boolean;
+ role: OrgRole | null;
+ isLoading: boolean;
+}
+
+export interface OrgPermissionSet extends PermissionSet {
+ /** Roles the user may give others (invite, change role); empty unless they manage members. */
+ assignableRoles: OrgRole[];
+}
+
+function permissionSet(permissions: readonly string[] | undefined, role: OrgRole | null, isLoading: boolean) {
+ const granted = new Set(permissions ?? []);
+ return { can: (permission: Permission) => granted.has(permission), role, isLoading };
+}
+
+/** Permissions on a site (defaults to the site in the URL/store). Empty for public and private-link viewers. */
+export function useSitePermissions(siteId?: string | number): PermissionSet {
+ const { data: site, isLoading } = useGetSite(siteId);
+ return permissionSet(site?.permissions, site?.role ?? null, isLoading);
+}
+
+/** Permissions in an organization (defaults to the active one). */
+export function useOrgPermissions(organizationId?: string): OrgPermissionSet {
+ const { data: session, isPending: isSessionPending } = authClient.useSession();
+ const { data: organizations, isLoading } = useUserOrganizations({ enabled: !!session?.user });
+ const targetId = organizationId ?? session?.session.activeOrganizationId ?? undefined;
+ const organization = organizations?.find(org => org.id === targetId);
+ return {
+ // The organization list waits on the session, so count that wait as loading too.
+ ...permissionSet(organization?.permissions, organization?.role ?? null, isSessionPending || isLoading),
+ assignableRoles: organization?.assignableRoles ?? [],
+ };
+}
+
+/** Whether the user holds a permission on a site (defaults to the current site). */
+export function useCanOnSite(permission: Permission, siteId?: string | number): boolean {
+ return useSitePermissions(siteId).can(permission);
+}
+
+/** Whether the user holds a permission in an organization (defaults to the active one). */
+export function useCanInOrg(permission: Permission, organizationId?: string): boolean {
+ return useOrgPermissions(organizationId).can(permission);
+}
diff --git a/client/src/lib/auth.ts b/client/src/lib/auth.ts
index d968aca41..501a05d83 100644
--- a/client/src/lib/auth.ts
+++ b/client/src/lib/auth.ts
@@ -14,6 +14,12 @@ const invitationSiteAccessFields = {
required: false,
defaultValue: [] as number[],
},
+ // Role on those sites (editor, member or viewer); absent means the invited role.
+ siteRole: {
+ type: "string" as const,
+ // Literal, so the invite input types the field as optional.
+ required: false as const,
+ },
};
export const authClient = createAuthClient({
diff --git a/client/src/lib/roles.test.ts b/client/src/lib/roles.test.ts
new file mode 100644
index 000000000..a6d627dd4
--- /dev/null
+++ b/client/src/lib/roles.test.ts
@@ -0,0 +1,17 @@
+import { describe, expect, it } from "vitest";
+
+import { siteRolesAbove } from "./roles";
+
+describe("siteRolesAbove", () => {
+ it("offers only the site roles that would raise the organization role, lowest first", () => {
+ expect(siteRolesAbove("viewer")).toEqual(["member", "editor"]);
+ expect(siteRolesAbove("member")).toEqual(["editor"]);
+ });
+
+ it("offers nothing to roles a site grant can't raise", () => {
+ expect(siteRolesAbove("editor")).toEqual([]);
+ expect(siteRolesAbove("admin")).toEqual([]);
+ expect(siteRolesAbove("owner")).toEqual([]);
+ expect(siteRolesAbove("unknown")).toEqual([]);
+ });
+});
diff --git a/client/src/lib/roles.ts b/client/src/lib/roles.ts
new file mode 100644
index 000000000..c7e3b7a4d
--- /dev/null
+++ b/client/src/lib/roles.ts
@@ -0,0 +1,72 @@
+"use client";
+
+import type { OrgRole, SiteGrantRole } from "@rybbit/shared";
+import { useExtracted } from "next-intl";
+
+// How organization roles are presented. What a role may do is the server's
+// answer: read it through the hooks in hooks/usePermissions.ts, never from
+// role names.
+
+type RoleName = "owner" | "admin" | "editor" | "member" | "viewer";
+
+export interface RoleInfo {
+ label: string;
+ description: string;
+}
+
+/**
+ * Owners and admins reach every site in the organization, so site restrictions
+ * don't apply to them. Presentational only: it decides whether to offer the
+ * "restrict to specific sites" option, not what anyone may do.
+ */
+export function isAdminRole(role: string | null | undefined): boolean {
+ return role === "owner" || role === "admin";
+}
+
+/** Every organization role, highest first (ORG_ROLES in @rybbit/shared, which the client imports types from only). */
+export const ORG_ROLES: readonly OrgRole[] = ["owner", "admin", "editor", "member", "viewer"];
+
+/** The roles a site grant (a member's or a team's) can carry, lowest first as site-role pickers list them. */
+export const SITE_GRANT_ROLES: readonly SiteGrantRole[] = ["viewer", "member", "editor"];
+
+/**
+ * The site roles worth offering someone with `orgRole`: a grant's role only ever
+ * raises their role on those sites, so one at or below `orgRole` would change nothing.
+ */
+export function siteRolesAbove(orgRole: string): SiteGrantRole[] {
+ const rank = ORG_ROLES.indexOf(orgRole as OrgRole);
+ return rank === -1 ? [] : SITE_GRANT_ROLES.filter(role => ORG_ROLES.indexOf(role) < rank);
+}
+
+/** A role's label and one-line description, for role pickers and member lists. Unknown roles show as-is. */
+export function useRoleInfo(): (role: string) => RoleInfo {
+ const t = useExtracted();
+ const roles: Record<RoleName, RoleInfo> = {
+ owner: {
+ label: t("Owner"),
+ description: t("Full access, including billing and deleting the organization"),
+ },
+ admin: {
+ label: t("Admin"),
+ description: t("Manages members, sites and settings, but not billing"),
+ },
+ editor: {
+ label: t("Editor"),
+ description: t(
+ "Configures sites (tracking, feature flags, experiments, imports, Search Console), but not members"
+ ),
+ },
+ member: {
+ label: t("Member"),
+ description: t(
+ "Views analytics and builds reports: goals, funnels, dashboards, their own segments and annotations"
+ ),
+ },
+ viewer: {
+ label: t("Viewer"),
+ description: t("Read-only access to analytics"),
+ },
+ };
+ return role =>
+ Object.prototype.hasOwnProperty.call(roles, role) ? roles[role as RoleName] : { label: role, description: "" };
+}
diff --git a/client/src/proxy.test.ts b/client/src/proxy.test.ts
index 377513c5a..5e3589c12 100644
--- a/client/src/proxy.test.ts
+++ b/client/src/proxy.test.ts
@@ -7,6 +7,12 @@ describe("onboarding routes", () => {
const response = await proxy(new NextRequest("https://app.rybbit.io/try?domain=acme.dev"));
expect(response.headers.get("location")).toBeNull();
});
+ it("serves site transfer links instead of treating them as site routes", async () => {
+ for (const path of ["/transfer", "/transfer/Zk3v-9Q_aBcDeFgHiJkLmNoPqRsTuVwXyZ01234567"]) {
+ const response = await proxy(new NextRequest(`https://app.rybbit.io${path}`));
+ expect(response.headers.get("location")).toBeNull();
+ }
+ });
it("preserves the OAuth claim flag when opening a private dashboard", async () => {
const response = await proxy(new NextRequest("https://app.rybbit.io/7/aaaaaaaaaaaa?claim=1"));
expect(response.headers.get("location")).toBe("https://app.rybbit.io/7/aaaaaaaaaaaa/main?claim=1");
diff --git a/client/src/proxy.ts b/client/src/proxy.ts
index f90ab5e31..3e664e365 100644
--- a/client/src/proxy.ts
+++ b/client/src/proxy.ts
@@ -39,6 +39,7 @@ export async function proxy(request: NextRequest) {
"try",
"subscribe",
"invitation",
+ "transfer",
"reset-password",
"auth",
"admin",
diff --git a/docs/content/docs/(docs)/inviting-users.mdx b/docs/content/docs/(docs)/inviting-users.mdx
index cd3401e5d..97f7bcf98 100644
--- a/docs/content/docs/(docs)/inviting-users.mdx
+++ b/docs/content/docs/(docs)/inviting-users.mdx
@@ -20,22 +20,24 @@ Go to **Settings > Organization** and click the "Invite Member" button. Enter th
<Step>
### Select the user's role
-You can assign the user one of three roles:
+You can assign any role up to your own (only owners can make owners):
-**Owners** have full access to all features including billing, organization deletion, and member management.
+- **Owner** β€” everything, including billing and deleting the organization
+- **Admin** β€” manages members, teams and sites, but not billing
+- **Editor** β€” configures sites (tracking settings, feature flags, experiments, imports, Search Console), but doesn't manage members
+- **Member** β€” views analytics and builds reports: goals, funnels, dashboards, and their own segments and annotations
+- **Viewer** β€” read-only
-**Admins** can manage members and access all sites, but cannot delete the organization or manage billing.
+See [Member Roles](/docs/organization-settings#member-roles) for the full list.
-**Members** can view analytics for assigned sites only. They cannot manage settings or other members.
+#### Restricting site access
-#### Restricting site access for members
+For editors, members and viewers you can restrict access to specific sites. Check "Restrict access to specific sites" and select the sites they should see. If you don't, they can see every site in your organization (except sites that belong to a [team](/docs/teams) they aren't on).
-When inviting a member, you can optionally restrict their access to specific sites. Check the "Restrict access to specific sites" option and select which sites the member should be able to view.
-
-If you don't enable this option, the member will have access to all sites in your organization.
+You can also pick a **role on these sites** to raise their role on the selected sites only. For example, invite a client as a **Viewer**, restricted to their own site, with **Editor** on that site: they can configure their site and nothing else. The site role only ever raises the organization role, never lowers it.
<Callout type="info">
- Site access restrictions only apply to members. Admins and owners always have full access to all sites.
+ Admins and owners always have access to every site, so site restrictions don't apply to them. A restricted member is treated as a viewer for anything that spans the whole organization, such as organization-wide segments.
</Callout>
</Step>
@@ -60,11 +62,11 @@ You can change a member's site access at any time after they've joined your orga
1. Go to **Settings > Organization**
2. Find the member in the list and click the edit (pencil) icon in the Actions column for that member
-3. Toggle "Restrict access to specific sites" and select the sites they should have access to
+3. Toggle "Restrict access to specific sites", select the sites they should have access to, and optionally a role on those sites
4. Click "Save changes"
The member will immediately only see the sites you've selected. If you disable the restriction, they'll regain access to all sites.
<Callout type="info">
- Currently, each user can only be in one organization.
+ A person can belong to several organizations, each with its own role. To hand a site over to someone so they can manage it in their own organization, [transfer the site](/docs/site-settings#transfer-site) instead.
</Callout>
diff --git a/docs/content/docs/(docs)/mcp/index.mdx b/docs/content/docs/(docs)/mcp/index.mdx
index 292937d61..461e753f8 100644
--- a/docs/content/docs/(docs)/mcp/index.mdx
+++ b/docs/content/docs/(docs)/mcp/index.mdx
@@ -150,7 +150,7 @@ Search Console tools read the Google Search Console property connected to the si
| `list_sites` | List organizations and sites the key can access (call this first) |
| `get_site` | One site's full configuration |
| `create_site` | Add a new site to an organization *(admin)* |
-| `update_site_config` | Change site settings: name, domain, tracking features, exclusions, tags *(admin)* |
+| `update_site_config` | Change site settings: name, domain, tracking features, exclusions, tags *(editor)* |
| `delete_site` | Permanently delete a site and its data *(admin, destructive)* |
### Goals & funnels
@@ -174,7 +174,7 @@ Search Console tools read the Google Search Console property connected to the si
| `get_user` | One person's profile: traits, linked devices, vitals, locations |
| `identify_user` | Link an anonymous device to your user ID and merge traits |
| `update_user_traits` | Replace a person's traits wholesale |
-| `delete_user` | GDPR erasure of one person's analytics data *(admin, destructive)* |
+| `delete_user` | GDPR erasure of one person's analytics data *(editor, destructive)* |
### Organization & teams
@@ -204,11 +204,14 @@ Analytics tools accept optional time inputs (`start_date`/`end_date` with an IAN
The MCP surface mirrors the REST API's permission model:
-- **Read tools** work for any member with access to the site.
-- **Write tools** need at least member-level site access (goals, funnels, `identify_user`, `update_user_traits`, `save_funnel`).
-- **Tools marked *(admin)*** require the API key's user to hold the **admin or owner** role in the organization; `add_member` can grant the `owner` role only from an owner's key. The REST layer enforces all of this β€” an underprivileged key gets a 403 with an explanatory message.
+- **Read tools** work for any role with access to the site, including viewers.
+- **Write tools** need the member role or above on the site (goals, funnels, `identify_user`, `update_user_traits`, `save_funnel`).
+- **Tools marked *(editor)*** need the editor role or above on the site.
+- **Tools marked *(admin)*** require the API key's user to hold the **admin or owner** role in the organization. `add_member` can't grant a role above the key's own, so only an owner's key can grant `owner`.
-To give an assistant a read-only or read-mostly view, create a **scoped** API key (see step 1): grant only the `resource:action` scopes it needs β€” e.g. `{"analytics": ["read"], "sessions": ["read"]}` for a reporting agent. The MCP tool list is filtered to those scopes, and any out-of-scope call returns `403 { "error": "Insufficient scope", "required": "goals:write" }`. Alternatively, connecting with a member-role user's key hides nothing but refuses every call requiring the admin/owner role.
+A key acts with its user's role on each site, including [site-specific roles](/docs/organization-settings#member-roles) from site restrictions and teams, and it reaches exactly the sites that user can see. The REST layer enforces all of this: an underprivileged key gets a 403 `"Insufficient role"` naming the role required.
+
+To give an assistant a read-only or read-mostly view, create a **scoped** API key (see step 1): grant only the `resource:action` scopes it needs β€” e.g. `{"analytics": ["read"], "sessions": ["read"]}` for a reporting agent. The MCP tool list is filtered to those scopes, and any out-of-scope call returns `403 { "error": "Insufficient scope", "required": "goals:write" }`. Alternatively, connect with a viewer's key: it hides nothing but refuses every write.
OAuth clients request scopes through the standard grant. Rybbit advertises the same `resource:action` scopes in its discovery metadata; a grant carrying no custom scopes (or only the standard OIDC scopes) is treated as full access, for backward compatibility.
@@ -229,7 +232,7 @@ OAuth clients request scopes through the standard grant. Rybbit advertises the s
- **401 Unauthorized:** The client did not send a Bearer credential, or the key/token is invalid, expired, or revoked. OAuth-capable clients re-authenticate automatically via the `WWW-Authenticate` challenge.
- **OAuth login loop or "table does not exist" (self-hosted):** Run `npm run db:push` in `server/` to create the OAuth tables, then retry.
-- **403 in tool results:** The key's user lacks access to that site or organization β€” or the tool requires an org admin/owner role. Check the `role` field in `list_sites`.
+- **403 in tool results:** The key's user lacks access to that site or organization, or holds too low a role for the tool (`"Insufficient role"` names the role required). Check the `role` field in `list_sites`.
- **403 "Insufficient scope":** The credential was created without the `resource:action` scope this tool needs (the `required` field names it). Use a key or OAuth grant that includes it.
- **429 Too Many Requests:** The API key exceeded its plan's rate limit.
- **404 "GSC not connected" from Search Console tools:** Connect Google Search Console for that site under Site settings > Integrations, then retry.
diff --git a/docs/content/docs/(docs)/organization-settings.mdx b/docs/content/docs/(docs)/organization-settings.mdx
index c39397fae..844c07459 100644
--- a/docs/content/docs/(docs)/organization-settings.mdx
+++ b/docs/content/docs/(docs)/organization-settings.mdx
@@ -13,11 +13,11 @@ Access organization settings by clicking on "Organization" or going to [app.rybb
### Organization Name
-Update your organization's display name. Only the organization owner can change this setting.
+Update your organization's display name. Owners and admins can change this setting.
### Delete Organization
-Permanently delete the organization and all associated data including sites, analytics, reports, and member associations.
+Permanently delete the organization and all associated data including sites, analytics, reports, and member associations. Only owners can delete an organization.
<Callout type="warn">
This action cannot be undone. You must type the organization name to confirm deletion. If you have an active subscription, you must cancel it before deleting the organization.
@@ -28,21 +28,29 @@ Permanently delete the organization and all associated data including sites, ana
View and manage all members in your organization. The members table shows:
- **Name** - Member's display name
- **Email** - Member's email address
-- **Role** - Owner, Admin, or Member
+- **Role** - Owner, Admin, Editor, Member, or Viewer
- **Site Access** - Which sites the member can access
- **Joined** - When they joined the organization
### Member Roles
-| Role | Permissions |
+Each role can do everything the roles below it can.
+
+| Role | What it adds |
|------|-------------|
-| **Owner** | Full access to all features, can manage members, billing, and delete the organization |
-| **Admin** | Can manage members and access all sites, cannot delete the organization or manage billing |
-| **Member** | Can view analytics for assigned sites only, cannot manage settings or other members |
+| **Owner** | Billing and plans, deleting the organization, making other owners |
+| **Admin** | Inviting and managing members and teams, organization API keys, creating, deleting and [transferring](/docs/site-settings#transfer-site) sites |
+| **Editor** | Site configuration: tracking settings, exclusions, public and private links, feature flags, experiments, data imports, Google Search Console, deleting session replays and tracked users, and editing anyone's segments and annotations |
+| **Member** | Building reports: goals, funnels, dashboards, and their own segments and annotations |
+| **Viewer** | Viewing analytics, sessions, replays and reports, without changing anything |
+
+Admins and owners always reach every site in the organization. Editors, members and viewers reach every site too, unless you [restrict them to specific sites](/docs/inviting-users#restricting-site-access) or the site belongs to a [team](/docs/teams) they aren't on.
+
+A member's role can also be raised on individual sites: when you restrict someone to specific sites, or add a site to a team, you can give them a higher role on just those sites. For example, a client can be a **Viewer** in your organization and an **Editor** on their own site. Nobody can give a role above their own, and only owners can make owners.
### Inviting Members
-Owners can invite new members or create user accounts. See the [Inviting Users](/docs/inviting-users) guide for detailed instructions.
+Owners and admins can invite new members or create user accounts. See the [Inviting Users](/docs/inviting-users) guide for detailed instructions. A person can belong to several organizations.
### Teams
diff --git a/docs/content/docs/(docs)/segments.mdx b/docs/content/docs/(docs)/segments.mdx
index 7783d4df4..d17400025 100644
--- a/docs/content/docs/(docs)/segments.mdx
+++ b/docs/content/docs/(docs)/segments.mdx
@@ -29,7 +29,7 @@ Every segment has:
- **Name** β€” what the group means to you, such as "Paid traffic" or "Logged-in users"
- **Filters** β€” at least one. Every filter must match; multiple values inside one filter are alternatives
-- **Available on** β€” this site only, or every site in the organization (organization-wide segments can only be created by admins and owners)
+- **Available on** β€” this site only, or every site in the organization (organization-wide segments need the editor role or above in the organization)
- **Description** β€” optional notes for your team
- **Show on the public dashboard and private links** β€” off by default
@@ -53,10 +53,13 @@ Use the **β‹―** menu on a segment in the Segments tab, or **Edit segment** from
| Role | Read and apply | Create | Edit and delete |
| --- | --- | --- | --- |
-| Owner or admin | All segments | Site and organization-wide | Any segment |
+| Owner, admin or editor | All segments | Site and organization-wide | Any segment |
| Member | All segments | Site segments | Segments they created |
+| Viewer | All segments | β€” | β€” |
| Public dashboard or private-link viewer | Segments marked as shown on the public dashboard | β€” | β€” |
+A member restricted to specific sites counts as a viewer at the organization level, so they can't create or edit organization-wide segments whatever their role on their own sites.
+
## API and MCP
Every analytics endpoint accepts a `segment_id` query parameter that is expanded server-side, ANDed with any `filters` you also pass. Segments themselves are managed through the [Segments endpoints](/docs/api/segments/list). The [MCP server](/docs/mcp) exposes `list_segments` and `apply_segment`.
diff --git a/docs/content/docs/(docs)/site-settings.mdx b/docs/content/docs/(docs)/site-settings.mdx
index c042ae253..1c5661438 100644
--- a/docs/content/docs/(docs)/site-settings.mdx
+++ b/docs/content/docs/(docs)/site-settings.mdx
@@ -119,9 +119,20 @@ Connect your Google Search Console account to see search performance data alongs
Update the domain for your site. Changing domains does not affect existing data - all historical analytics are preserved.
+## Transfer Site
+
+Admins and owners can move a site to another organization. Its analytics data, goals, funnels, dashboards, segments, annotations and settings go with it, and the tracking script keeps working unchanged. Site access granted in the old organization (restricted-member grants and team assignments) stays behind.
+
+- **To another organization you manage:** pick the organization under **Transfer Site** and confirm. You need to be an admin or owner of both organizations.
+- **To someone else:** enter their email under **Transfer to someone else**. They get an email with a link (you can also copy it and send it yourself); they open it signed in with that address (on Rybbit Cloud it must be verified; the page offers to send the verification email), choose one of their organizations, and accept. The link is valid for 7 days, and you can cancel it until it's accepted. Neither of you needs to join the other's organization.
+
+<Callout type="info">
+ When someone else accepts a transfer, the site's Google Search Console connection is removed, since it uses the sender's Google account; the new owner can connect their own. On Rybbit Cloud the receiving organization's plan must have room for another site.
+</Callout>
+
## Delete Site
-Permanently delete a site and all associated data.
+Permanently delete a site and all associated data. Only admins and owners can delete sites.
<Callout type="warn">
This action cannot be undone. All analytics data, reports, funnels, and goals will be permanently deleted.
diff --git a/docs/content/docs/(docs)/teams.mdx b/docs/content/docs/(docs)/teams.mdx
index cc82f754c..6810b2b77 100644
--- a/docs/content/docs/(docs)/teams.mdx
+++ b/docs/content/docs/(docs)/teams.mdx
@@ -13,16 +13,17 @@ Access teams by clicking on "Teams" or going to [app.rybbit.io/settings/teams](h
## How Teams Work
-A team has three things:
+A team has four things:
- **A name** β€” identifies the team (e.g. "Marketing Sites", "Client Projects")
- **Members** β€” organization members assigned to the team
- **Sites** β€” the sites that belong to the team
+- **Role on the team's sites** (optional) β€” raises the members' role on the team's sites, e.g. to **Editor**. Left empty, each member keeps their own organization role there. It never lowers anyone's role.
When a member is assigned to a team, they can access all sites within that team. Admins and owners always have access to all sites regardless of team assignments.
<Callout type="info">
- Teams are an organizational tool for admins and owners. Members with the "Member" role can only see sites that belong to their assigned teams (unless they have unrestricted access).
+ A site that belongs to a team is only visible to that team's members (plus admins and owners, and anyone explicitly granted the site). Sites in no team are visible to every unrestricted member.
</Callout>
## Creating a Team
@@ -32,7 +33,8 @@ When a member is assigned to a team, they can access all sites within that team.
3. Enter a team name
4. Select which members should belong to the team
5. Select which sites the team should have access to
-6. Click **Create Team**
+6. Optionally pick a role the team's members get on those sites
+7. Click **Create Team**
You can also create a team directly from the team filter on the home page.
@@ -64,8 +66,8 @@ When [inviting a new member](/docs/inviting-users), you can optionally assign th
## Permissions
-| Role | Can create teams | Can edit/delete teams | Can view team-restricted sites |
-|------|-----------------|----------------------|-------------------------------|
-| **Owner** | Yes | Yes | All sites |
-| **Admin** | Yes | Yes | All sites |
-| **Member** | No | No | Only sites in their assigned teams |
+| Role | Can create, edit and delete teams | Can view team-restricted sites |
+|------|----------------------------------|-------------------------------|
+| **Owner** | Yes | All sites |
+| **Admin** | Yes | All sites |
+| **Editor, Member, Viewer** | No | Only sites in their assigned teams |
diff --git a/docs/content/docs/api/annotations/create.mdx b/docs/content/docs/api/annotations/create.mdx
index 70531941b..70508ac8f 100644
--- a/docs/content/docs/api/annotations/create.mdx
+++ b/docs/content/docs/api/annotations/create.mdx
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
POST /api/sites/:site/annotations
```
-Creates an annotation. Any member with access to the site can create site annotations; organization-wide annotations (`scope: "organization"`) require an admin or owner role.
+Creates an annotation. Members and above can create site annotations; organization-wide annotations (`scope: "organization"`) need the editor role or above in the organization.
### Path Parameters
diff --git a/docs/content/docs/api/annotations/update.mdx b/docs/content/docs/api/annotations/update.mdx
index 480afc9f8..10c7e9ddd 100644
--- a/docs/content/docs/api/annotations/update.mdx
+++ b/docs/content/docs/api/annotations/update.mdx
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
PUT /api/sites/:site/annotations/:annotationId
```
-Partial update: only the fields you send change. Admins and owners can edit any annotation on their sites; members can edit only the annotations they created. Changing `scope` requires an admin or owner role.
+Partial update: only the fields you send change. Editors, admins and owners can edit any annotation on their sites; members can edit only the annotations they created. Changing `scope` needs the editor role or above in the organization.
### Path Parameters
diff --git a/docs/content/docs/api/imports/create.mdx b/docs/content/docs/api/imports/create.mdx
index 3bd4c16b3..d29055cff 100644
--- a/docs/content/docs/api/imports/create.mdx
+++ b/docs/content/docs/api/imports/create.mdx
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
POST /api/sites/:site/imports
```
-Starts a new data import from a supported platform. Requires an admin or owner API key. On Rybbit Cloud, this requires a paid plan.
+Starts a new data import from a supported platform. Requires the editor role or above on the site. On Rybbit Cloud, this requires a paid plan.
Only one concurrent import is allowed per organization. Starting a second import while one is still running returns HTTP `429`.
diff --git a/docs/content/docs/api/imports/delete.mdx b/docs/content/docs/api/imports/delete.mdx
index c911c68f7..912ddc039 100644
--- a/docs/content/docs/api/imports/delete.mdx
+++ b/docs/content/docs/api/imports/delete.mdx
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
DELETE /api/sites/:site/imports/:importId
```
-Deletes an import and all events it added. The import must be finished. Requires an admin or owner API key. On Rybbit Cloud, this requires a paid plan.
+Deletes an import and all events it added. The import must be finished. Requires the editor role or above on the site. On Rybbit Cloud, this requires a paid plan.
A still-running import cannot be deleted and returns HTTP `400`.
diff --git a/docs/content/docs/api/imports/events.mdx b/docs/content/docs/api/imports/events.mdx
index 570c12900..9b02cbc6f 100644
--- a/docs/content/docs/api/imports/events.mdx
+++ b/docs/content/docs/api/imports/events.mdx
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
POST /api/sites/:site/imports/:importId/events
```
-Uploads a batch of raw events to an in-progress import. Requires an admin or owner API key. On Rybbit Cloud, this requires a paid plan.
+Uploads a batch of raw events to an in-progress import. Requires the editor role or above on the site. On Rybbit Cloud, this requires a paid plan.
Upload events in batches. The request body limit is 50 MB, so split large exports across multiple requests. Set `isLastBatch` to `true` on the final batch to finalize the import.
diff --git a/docs/content/docs/api/imports/list.mdx b/docs/content/docs/api/imports/list.mdx
index d13bea82d..66f83a3b8 100644
--- a/docs/content/docs/api/imports/list.mdx
+++ b/docs/content/docs/api/imports/list.mdx
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
GET /api/sites/:site/imports
```
-Returns all data imports for a site with their progress counts. Requires an admin or owner API key. On Rybbit Cloud, this requires a paid plan.
+Returns all data imports for a site with their progress counts. Requires the editor role or above on the site. On Rybbit Cloud, this requires a paid plan.
### Path Parameters
diff --git a/docs/content/docs/api/organizations/add-member.mdx b/docs/content/docs/api/organizations/add-member.mdx
index 3c3696460..d34be5b12 100644
--- a/docs/content/docs/api/organizations/add-member.mdx
+++ b/docs/content/docs/api/organizations/add-member.mdx
@@ -1,6 +1,6 @@
---
title: Add Organization Member
-description: Adds a user to an organization with a specified role. The user must already exist in the system. Requires admin or owner role in the organization.
+description: Adds a user to an organization with a specified role. The user must already exist in the system. Requires admin or owner role in the organization. You cannot assign a role above your own.
full: true
method: POST
---
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
POST /api/organizations/:organizationId/members
```
-Adds a user to an organization with a specified role. The user must already exist in the system. Requires admin or owner role in the organization.
+Adds a user to an organization with a specified role. The user must already exist in the system. Requires admin or owner role in the organization. You cannot assign a role above your own.
### Path Parameters
@@ -42,7 +42,7 @@ Adds a user to an organization with a specified role. The user must already exis
role: {
description: 'Role to assign to the user',
type: 'string',
- typeDescription: '"admin" | "member" | "owner"',
+ typeDescription: '"owner" | "admin" | "editor" | "member" | "viewer"',
required: true,
},
}}
diff --git a/docs/content/docs/api/organizations/invite-member.mdx b/docs/content/docs/api/organizations/invite-member.mdx
index 3d255e0f6..d5b4cd13f 100644
--- a/docs/content/docs/api/organizations/invite-member.mdx
+++ b/docs/content/docs/api/organizations/invite-member.mdx
@@ -30,7 +30,7 @@ Sends an invitation email inviting a user to join an organization with a given r
required: true,
},
role: {
- description: 'Role(s) to assign. One of `owner`, `admin`, `member` (or an array of roles).',
+ description: 'Role to assign: `owner`, `admin`, `editor`, `member` or `viewer`. You cannot assign a role above your own.',
type: 'string | string[]',
required: true,
},
@@ -50,7 +50,7 @@ Sends an invitation email inviting a user to join an organization with a given r
required: false,
},
hasRestrictedSiteAccess: {
- description: 'Rybbit extension: restrict the invited member to specific sites. Only valid when role is `member`.',
+ description: 'Rybbit extension: restrict the invited member to specific sites. Not valid for `admin` or `owner`.',
type: 'boolean',
required: false,
},
@@ -59,10 +59,16 @@ Sends an invitation email inviting a user to join an organization with a given r
type: 'number[]',
required: false,
},
+ siteRole: {
+ description: "Rybbit extension: raises the member's role on those sites. Never lowers it.",
+ type: 'string',
+ typeDescription: '"editor" | "member" | "viewer" | null',
+ required: false,
+ },
}}
/>
-<Callout>`hasRestrictedSiteAccess` and `siteIds` are Rybbit-specific extensions to the invitation. Site-access restrictions can only be applied to invitations with the `member` role.</Callout>
+<Callout>`hasRestrictedSiteAccess`, `siteIds` and `siteRole` are Rybbit-specific extensions to the invitation. Site-access restrictions cannot be applied to `admin` or `owner` invitations, who always reach every site.</Callout>
### Response
diff --git a/docs/content/docs/api/organizations/list.mdx b/docs/content/docs/api/organizations/list.mdx
index c2a0bafe5..f06e1faec 100644
--- a/docs/content/docs/api/organizations/list.mdx
+++ b/docs/content/docs/api/organizations/list.mdx
@@ -50,7 +50,7 @@ Returns an array of organization objects.
role: {
description: 'Your role in the organization',
type: 'string',
- typeDescription: '"owner" | "admin" | "member"',
+ typeDescription: '"owner" | "admin" | "editor" | "member" | "viewer"',
},
members: {
description: 'Array of organization members',
@@ -76,7 +76,7 @@ Each member in the `members` array contains:
role: {
description: 'Member role in the organization',
type: 'string',
- typeDescription: '"owner" | "admin" | "member"',
+ typeDescription: '"owner" | "admin" | "editor" | "member" | "viewer"',
},
userId: {
description: 'User ID',
diff --git a/docs/content/docs/api/organizations/members.mdx b/docs/content/docs/api/organizations/members.mdx
index f04a5122a..579f20b25 100644
--- a/docs/content/docs/api/organizations/members.mdx
+++ b/docs/content/docs/api/organizations/members.mdx
@@ -57,7 +57,7 @@ Each member in the `data` array contains:
role: {
description: 'Member role in the organization',
type: 'string',
- typeDescription: '"owner" | "admin" | "member"',
+ typeDescription: '"owner" | "admin" | "editor" | "member" | "viewer"',
},
userId: {
description: 'User ID',
diff --git a/docs/content/docs/api/organizations/update-member-role.mdx b/docs/content/docs/api/organizations/update-member-role.mdx
index 77e57e973..f2fa8ed3d 100644
--- a/docs/content/docs/api/organizations/update-member-role.mdx
+++ b/docs/content/docs/api/organizations/update-member-role.mdx
@@ -27,7 +27,7 @@ Updates the role(s) assigned to an existing organization member.
<TypeTable
type={{
role: {
- description: 'The new role(s) to assign. One of `owner`, `admin`, `member` (or an array of roles).',
+ description: "The new role: `owner`, `admin`, `editor`, `member` or `viewer`. Requires the admin or owner role; only owners can make owners or change an owner's role.",
type: 'string | string[]',
required: true,
},
diff --git a/docs/content/docs/api/segments/create.mdx b/docs/content/docs/api/segments/create.mdx
index 04a2f77bb..c05b9f4c1 100644
--- a/docs/content/docs/api/segments/create.mdx
+++ b/docs/content/docs/api/segments/create.mdx
@@ -1,6 +1,6 @@
---
title: Create Segment
-description: Creates a saved segment. Members create site segments they own; admins and owners can also create organization-wide segments.
+description: Creates a saved segment. Members create site segments they own; editors, admins and owners can also create organization-wide segments.
full: true
method: POST
---
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
POST /api/sites/:site/segments
```
-Creates a saved segment. Members create site segments they own; admins and owners can also create organization-wide segments.
+Creates a saved segment. Members create site segments they own; editors, admins and owners can also create organization-wide segments.
### Path Parameters
@@ -50,7 +50,7 @@ Creates a saved segment. Members create site segments they own; admins and owner
required: false,
},
scope: {
- description: 'Where the segment is available. Organization-wide segments require an admin or owner',
+ description: 'Where the segment is available. Organization-wide segments need the editor role or above in the organization',
type: 'string',
typeDescription: '"site" | "organization"',
default: 'site',
diff --git a/docs/content/docs/api/segments/update.mdx b/docs/content/docs/api/segments/update.mdx
index 0f2221ea2..3ebf4f786 100644
--- a/docs/content/docs/api/segments/update.mdx
+++ b/docs/content/docs/api/segments/update.mdx
@@ -1,6 +1,6 @@
---
title: Update Segment
-description: Updates a saved segment. Admins and owners can edit any segment; members can edit segments they created. Only the fields you send change.
+description: Updates a saved segment. Editors, admins and owners can edit any segment; members can edit segments they created. Only the fields you send change.
full: true
method: PUT
---
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
PUT /api/sites/:site/segments/:segmentId
```
-Updates a saved segment. Admins and owners can edit any segment; members can edit segments they created. Only the fields you send change.
+Updates a saved segment. Editors, admins and owners can edit any segment; members can edit segments they created. Only the fields you send change.
### Path Parameters
@@ -55,7 +55,7 @@ Updates a saved segment. Admins and owners can edit any segment; members can edi
required: false,
},
scope: {
- description: 'Where the segment is available. Organization-wide segments require an admin or owner',
+ description: 'Where the segment is available. Organization-wide segments need the editor role or above in the organization',
type: 'string',
typeDescription: '"site" | "organization"',
default: 'site',
diff --git a/docs/content/docs/api/session-replay/delete.mdx b/docs/content/docs/api/session-replay/delete.mdx
index 191bdf567..b5c6c43b8 100644
--- a/docs/content/docs/api/session-replay/delete.mdx
+++ b/docs/content/docs/api/session-replay/delete.mdx
@@ -1,6 +1,6 @@
---
title: Delete Session Replay
-description: Permanently deletes a session replay recording. Requires site write access.
+description: Permanently deletes a session replay recording. Requires the editor role or above on the site.
full: true
method: DELETE
---
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
DELETE /api/sites/:site/session-replay/:sessionId
```
-Permanently deletes a session replay recording. Requires site write access.
+Permanently deletes a session replay recording. Requires the editor role or above on the site.
### Path Parameters
diff --git a/docs/content/docs/api/sites/update-config.mdx b/docs/content/docs/api/sites/update-config.mdx
index 8cb5a4723..b694f6e78 100644
--- a/docs/content/docs/api/sites/update-config.mdx
+++ b/docs/content/docs/api/sites/update-config.mdx
@@ -1,6 +1,6 @@
---
title: Update Site Config
-description: Updates site configuration settings. All fields are optional - only include the fields you want to update. Requires admin or owner role.
+description: Updates site configuration settings. All fields are optional - only include the fields you want to update. Requires the editor role or above on the site.
full: true
method: PUT
---
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
PUT /api/sites/:siteId/config
```
-Updates site configuration settings. All fields are optional - only include the fields you want to update. Requires admin or owner role.
+Updates site configuration settings. All fields are optional - only include the fields you want to update. Requires the editor role or above on the site.
### Path Parameters
diff --git a/docs/content/docs/api/sites/update-private-link.mdx b/docs/content/docs/api/sites/update-private-link.mdx
index cdc49fc04..64bc94e52 100644
--- a/docs/content/docs/api/sites/update-private-link.mdx
+++ b/docs/content/docs/api/sites/update-private-link.mdx
@@ -1,6 +1,6 @@
---
title: Update Private Link Config
-description: Generates or revokes a private link key for sharing analytics without authentication. Requires admin or owner role.
+description: Generates or revokes a private link key for sharing analytics without authentication. Requires the editor role or above on the site.
full: true
method: POST
---
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
POST /api/sites/:siteId/private-link-config
```
-Generates or revokes a private link key for sharing analytics without authentication. Requires admin or owner role.
+Generates or revokes a private link key for sharing analytics without authentication. Requires the editor role or above on the site.
### Path Parameters
diff --git a/docs/content/docs/api/teams/create.mdx b/docs/content/docs/api/teams/create.mdx
index b907f78a7..14c99c43d 100644
--- a/docs/content/docs/api/teams/create.mdx
+++ b/docs/content/docs/api/teams/create.mdx
@@ -48,6 +48,12 @@ Creates a team in an organization. Requires admin/owner role.
type: 'number[]',
required: false,
},
+ siteRole: {
+ description: "Raises the team members' role on the team's sites. Never lowers it; omit or null to leave each member's own role.",
+ type: 'string',
+ typeDescription: '"editor" | "member" | "viewer" | null',
+ required: false,
+ },
}}
/>
diff --git a/docs/content/docs/api/teams/list.mdx b/docs/content/docs/api/teams/list.mdx
index 513c57015..4ad06040c 100644
--- a/docs/content/docs/api/teams/list.mdx
+++ b/docs/content/docs/api/teams/list.mdx
@@ -17,7 +17,7 @@ GET /api/organizations/:organizationId/teams
Returns the teams in an organization, with their members and accessible sites.
-Any organization member may call this. Members who are not an admin/owner only see the teams they belong to.
+Any organization member may call this. Callers who are not an admin or owner only see the teams they belong to.
### Path Parameters
diff --git a/docs/content/docs/api/teams/update.mdx b/docs/content/docs/api/teams/update.mdx
index e830258ea..f2704018f 100644
--- a/docs/content/docs/api/teams/update.mdx
+++ b/docs/content/docs/api/teams/update.mdx
@@ -55,6 +55,12 @@ When `memberUserIds` or `siteIds` is provided, it **replaces** the team's entire
type: 'number[]',
required: false,
},
+ siteRole: {
+ description: "Raises the team members' role on the team's sites (never lowers it); null to leave each member's own role. Omit to keep the current setting.",
+ type: 'string',
+ typeDescription: '"editor" | "member" | "viewer" | null',
+ required: false,
+ },
}}
/>
diff --git a/server/drizzle/0021_site_grant_roles.sql b/server/drizzle/0021_site_grant_roles.sql
new file mode 100644
index 000000000..1e014ac23
--- /dev/null
+++ b/server/drizzle/0021_site_grant_roles.sql
@@ -0,0 +1,3 @@
+ALTER TABLE "invitation" ADD COLUMN IF NOT EXISTS "site_role" text;--> statement-breakpoint
+ALTER TABLE "member_site_access" ADD COLUMN IF NOT EXISTS "role" text;--> statement-breakpoint
+ALTER TABLE "team_site_access" ADD COLUMN IF NOT EXISTS "role" text;
diff --git a/server/drizzle/0022_site_transfers.sql b/server/drizzle/0022_site_transfers.sql
new file mode 100644
index 000000000..b71b74898
--- /dev/null
+++ b/server/drizzle/0022_site_transfers.sql
@@ -0,0 +1,28 @@
+CREATE TABLE IF NOT EXISTS "site_transfers" (
+ "id" text PRIMARY KEY NOT NULL,
+ "site_id" integer NOT NULL,
+ "source_organization_id" text NOT NULL,
+ "recipient_email" text NOT NULL,
+ "created_by" text,
+ "created_at" timestamp DEFAULT now() NOT NULL,
+ "expires_at" timestamp NOT NULL,
+ CONSTRAINT "site_transfers_site_unique" UNIQUE("site_id")
+);
+--> statement-breakpoint
+DO $$ BEGIN
+ ALTER TABLE "site_transfers" ADD CONSTRAINT "site_transfers_site_id_sites_site_id_fk" FOREIGN KEY ("site_id") REFERENCES "public"."sites"("site_id") ON DELETE cascade ON UPDATE no action;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;
+--> statement-breakpoint
+DO $$ BEGIN
+ ALTER TABLE "site_transfers" ADD CONSTRAINT "site_transfers_source_organization_id_organization_id_fk" FOREIGN KEY ("source_organization_id") REFERENCES "public"."organization"("id") ON DELETE cascade ON UPDATE no action;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;
+--> statement-breakpoint
+DO $$ BEGIN
+ ALTER TABLE "site_transfers" ADD CONSTRAINT "site_transfers_created_by_user_id_fk" FOREIGN KEY ("created_by") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;
+EXCEPTION
+ WHEN duplicate_object THEN null;
+END $$;
diff --git a/server/drizzle/meta/0021_snapshot.json b/server/drizzle/meta/0021_snapshot.json
new file mode 100644
index 000000000..193cb908b
--- /dev/null
+++ b/server/drizzle/meta/0021_snapshot.json
@@ -0,0 +1,4567 @@
+{
+ "id": "6a0f4378-a2c9-4cd9-9298-853718fba5d8",
+ "prevId": "0b0237da-9eb1-4b21-b26e-0db3bef8c568",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.account": {
+ "name": "account",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "accountId": {
+ "name": "accountId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "providerId": {
+ "name": "providerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "accessToken": {
+ "name": "accessToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refreshToken": {
+ "name": "refreshToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "idToken": {
+ "name": "idToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessTokenExpiresAt": {
+ "name": "accessTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refreshTokenExpiresAt": {
+ "name": "refreshTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "account_userId_user_id_fk": {
+ "name": "account_userId_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.active_sessions": {
+ "name": "active_sessions",
+ "schema": "",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "start_time": {
+ "name": "start_time",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "last_activity": {
+ "name": "last_activity",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.annotations": {
+ "name": "annotations",
+ "schema": "",
+ "columns": {
+ "annotation_id": {
+ "name": "annotation_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "date": {
+ "name": "date",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "end_date": {
+ "name": "end_date",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_public": {
+ "name": "is_public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "annotations_site_date_idx": {
+ "name": "annotations_site_date_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "date",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "annotations_org_date_idx": {
+ "name": "annotations_org_date_idx",
+ "columns": [
+ {
+ "expression": "organization_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "date",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "annotations_site_id_sites_site_id_fk": {
+ "name": "annotations_site_id_sites_site_id_fk",
+ "tableFrom": "annotations",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "annotations_organization_id_organization_id_fk": {
+ "name": "annotations_organization_id_organization_id_fk",
+ "tableFrom": "annotations",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "annotations_user_id_user_id_fk": {
+ "name": "annotations_user_id_user_id_fk",
+ "tableFrom": "annotations",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.apikey": {
+ "name": "apikey",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "start": {
+ "name": "start",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "prefix": {
+ "name": "prefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refillInterval": {
+ "name": "refillInterval",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refillAmount": {
+ "name": "refillAmount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastRefillAt": {
+ "name": "lastRefillAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "rateLimitEnabled": {
+ "name": "rateLimitEnabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "rateLimitTimeWindow": {
+ "name": "rateLimitTimeWindow",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rateLimitMax": {
+ "name": "rateLimitMax",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requestCount": {
+ "name": "requestCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "remaining": {
+ "name": "remaining",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastRequest": {
+ "name": "lastRequest",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "configId": {
+ "name": "configId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.cancellation_feedback": {
+ "name": "cancellation_feedback",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "reason_details": {
+ "name": "reason_details",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "retention_offer_shown": {
+ "name": "retention_offer_shown",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "retention_offer_accepted": {
+ "name": "retention_offer_accepted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "outcome": {
+ "name": "outcome",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "plan_name_at_cancellation": {
+ "name": "plan_name_at_cancellation",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "monthly_event_count_at_cancellation": {
+ "name": "monthly_event_count_at_cancellation",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.dashboards": {
+ "name": "dashboards",
+ "schema": "",
+ "columns": {
+ "dashboard_id": {
+ "name": "dashboard_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{\"cards\":[]}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "dashboards_site_id_sites_site_id_fk": {
+ "name": "dashboards_site_id_sites_site_id_fk",
+ "tableFrom": "dashboards",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "dashboards_user_id_user_id_fk": {
+ "name": "dashboards_user_id_user_id_fk",
+ "tableFrom": "dashboards",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.experiments": {
+ "name": "experiments",
+ "schema": "",
+ "columns": {
+ "experiment_id": {
+ "name": "experiment_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "feature_flag_id": {
+ "name": "feature_flag_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "primary_goal_id": {
+ "name": "primary_goal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "hypothesis": {
+ "name": "hypothesis",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'draft'"
+ },
+ "winning_variant": {
+ "name": "winning_variant",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "experiments_site_idx": {
+ "name": "experiments_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "experiments_feature_flag_idx": {
+ "name": "experiments_feature_flag_idx",
+ "columns": [
+ {
+ "expression": "feature_flag_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "experiments_primary_goal_idx": {
+ "name": "experiments_primary_goal_idx",
+ "columns": [
+ {
+ "expression": "primary_goal_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "experiments_site_id_sites_site_id_fk": {
+ "name": "experiments_site_id_sites_site_id_fk",
+ "tableFrom": "experiments",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "experiments_feature_flag_id_feature_flags_flag_id_fk": {
+ "name": "experiments_feature_flag_id_feature_flags_flag_id_fk",
+ "tableFrom": "experiments",
+ "tableTo": "feature_flags",
+ "columnsFrom": [
+ "feature_flag_id"
+ ],
+ "columnsTo": [
+ "flag_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "experiments_primary_goal_id_goals_goal_id_fk": {
+ "name": "experiments_primary_goal_id_goals_goal_id_fk",
+ "tableFrom": "experiments",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "primary_goal_id"
+ ],
+ "columnsTo": [
+ "goal_id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "experiments_site_flag_unique": {
+ "name": "experiments_site_flag_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "site_id",
+ "feature_flag_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "experiments_status_check": {
+ "name": "experiments_status_check",
+ "value": "status IN ('draft', 'running', 'paused', 'completed')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.feature_flags": {
+ "name": "feature_flags",
+ "schema": "",
+ "columns": {
+ "flag_id": {
+ "name": "flag_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "runtime": {
+ "name": "runtime",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'client'"
+ },
+ "flag_type": {
+ "name": "flag_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'boolean'"
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "variants": {
+ "name": "variants",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "rollout_percentage": {
+ "name": "rollout_percentage",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 100
+ },
+ "rules": {
+ "name": "rules",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "condition_sets": {
+ "name": "condition_sets",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "salt": {
+ "name": "salt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "md5(random()::text || clock_timestamp()::text)"
+ },
+ "version": {
+ "name": "version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "feature_flags_site_idx": {
+ "name": "feature_flags_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "feature_flags_site_id_sites_site_id_fk": {
+ "name": "feature_flags_site_id_sites_site_id_fk",
+ "tableFrom": "feature_flags",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "feature_flags_site_key_unique": {
+ "name": "feature_flags_site_key_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "site_id",
+ "key"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "feature_flags_rollout_check": {
+ "name": "feature_flags_rollout_check",
+ "value": "rollout_percentage >= 0 AND rollout_percentage <= 100"
+ },
+ "feature_flags_runtime_check": {
+ "name": "feature_flags_runtime_check",
+ "value": "runtime IN ('client', 'server', 'both')"
+ },
+ "feature_flags_type_check": {
+ "name": "feature_flags_type_check",
+ "value": "flag_type IN ('boolean', 'multivariate', 'remote_config')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.funnels": {
+ "name": "funnels",
+ "schema": "",
+ "columns": {
+ "report_id": {
+ "name": "report_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data": {
+ "name": "data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "funnels_site_id_sites_site_id_fk": {
+ "name": "funnels_site_id_sites_site_id_fk",
+ "tableFrom": "funnels",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "funnels_user_id_user_id_fk": {
+ "name": "funnels_user_id_user_id_fk",
+ "tableFrom": "funnels",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.goals": {
+ "name": "goals",
+ "schema": "",
+ "columns": {
+ "goal_id": {
+ "name": "goal_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "goal_type": {
+ "name": "goal_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "goals_site_id_sites_site_id_fk": {
+ "name": "goals_site_id_sites_site_id_fk",
+ "tableFrom": "goals",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.gsc_connections": {
+ "name": "gsc_connections",
+ "schema": "",
+ "columns": {
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "gsc_property_url": {
+ "name": "gsc_property_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "gsc_connections_site_id_sites_site_id_fk": {
+ "name": "gsc_connections_site_id_sites_site_id_fk",
+ "tableFrom": "gsc_connections",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.import_status": {
+ "name": "import_status",
+ "schema": "",
+ "columns": {
+ "import_id": {
+ "name": "import_id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "platform": {
+ "name": "platform",
+ "type": "import_platform_enum",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "imported_events": {
+ "name": "imported_events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "skipped_events": {
+ "name": "skipped_events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "invalid_events": {
+ "name": "invalid_events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "import_status_site_id_sites_site_id_fk": {
+ "name": "import_status_site_id_sites_site_id_fk",
+ "tableFrom": "import_status",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "import_status_organization_id_organization_id_fk": {
+ "name": "import_status_organization_id_organization_id_fk",
+ "tableFrom": "import_status",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.invitation": {
+ "name": "invitation",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "inviterId": {
+ "name": "inviterId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "has_restricted_site_access": {
+ "name": "has_restricted_site_access",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "site_ids": {
+ "name": "site_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "site_role": {
+ "name": "site_role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "teamId": {
+ "name": "teamId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "invitation_inviterId_user_id_fk": {
+ "name": "invitation_inviterId_user_id_fk",
+ "tableFrom": "invitation",
+ "tableTo": "user",
+ "columnsFrom": [
+ "inviterId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "invitation_organizationId_organization_id_fk": {
+ "name": "invitation_organizationId_organization_id_fk",
+ "tableFrom": "invitation",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organizationId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "invitation_teamId_team_id_fk": {
+ "name": "invitation_teamId_team_id_fk",
+ "tableFrom": "invitation",
+ "tableTo": "team",
+ "columnsFrom": [
+ "teamId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.jwks": {
+ "name": "jwks",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "publicKey": {
+ "name": "publicKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "privateKey": {
+ "name": "privateKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "alg": {
+ "name": "alg",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "crv": {
+ "name": "crv",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.lifecycle_email_log": {
+ "name": "lifecycle_email_log",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email_key": {
+ "name": "email_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "lifecycle_email_log_user_id_user_id_fk": {
+ "name": "lifecycle_email_log_user_id_user_id_fk",
+ "tableFrom": "lifecycle_email_log",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "lifecycle_email_log_user_email_key_unique": {
+ "name": "lifecycle_email_log_user_email_key_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "user_id",
+ "email_key"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.member": {
+ "name": "member",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "has_restricted_site_access": {
+ "name": "has_restricted_site_access",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "member_organizationId_organization_id_fk": {
+ "name": "member_organizationId_organization_id_fk",
+ "tableFrom": "member",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organizationId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "member_userId_user_id_fk": {
+ "name": "member_userId_user_id_fk",
+ "tableFrom": "member",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.member_site_access": {
+ "name": "member_site_access",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "member_id": {
+ "name": "member_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "member_site_access_member_idx": {
+ "name": "member_site_access_member_idx",
+ "columns": [
+ {
+ "expression": "member_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "member_site_access_site_idx": {
+ "name": "member_site_access_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "member_site_access_member_id_member_id_fk": {
+ "name": "member_site_access_member_id_member_id_fk",
+ "tableFrom": "member_site_access",
+ "tableTo": "member",
+ "columnsFrom": [
+ "member_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "member_site_access_site_id_sites_site_id_fk": {
+ "name": "member_site_access_site_id_sites_site_id_fk",
+ "tableFrom": "member_site_access",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "member_site_access_created_by_user_id_fk": {
+ "name": "member_site_access_created_by_user_id_fk",
+ "tableFrom": "member_site_access",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "member_site_access_unique": {
+ "name": "member_site_access_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "member_id",
+ "site_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthAccessToken": {
+ "name": "oauthAccessToken",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "accessToken": {
+ "name": "accessToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refreshToken": {
+ "name": "refreshToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessTokenExpiresAt": {
+ "name": "accessTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refreshTokenExpiresAt": {
+ "name": "refreshTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauthAccessToken_clientId_oauthApplication_clientId_fk": {
+ "name": "oauthAccessToken_clientId_oauthApplication_clientId_fk",
+ "tableFrom": "oauthAccessToken",
+ "tableTo": "oauthApplication",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthAccessToken_userId_user_id_fk": {
+ "name": "oauthAccessToken_userId_user_id_fk",
+ "tableFrom": "oauthAccessToken",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthAccessToken_accessToken_unique": {
+ "name": "oauthAccessToken_accessToken_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "accessToken"
+ ]
+ },
+ "oauthAccessToken_refreshToken_unique": {
+ "name": "oauthAccessToken_refreshToken_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "refreshToken"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthAccessTokenV2": {
+ "name": "oauthAccessTokenV2",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sessionId": {
+ "name": "sessionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authorizationCodeId": {
+ "name": "authorizationCodeId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resources": {
+ "name": "resources",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requestedUserInfoClaims": {
+ "name": "requestedUserInfoClaims",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refreshId": {
+ "name": "refreshId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "revoked": {
+ "name": "revoked",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "confirmation": {
+ "name": "confirmation",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "oauthAccessTokenV2_clientId_idx": {
+ "name": "oauthAccessTokenV2_clientId_idx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthAccessTokenV2_sessionId_idx": {
+ "name": "oauthAccessTokenV2_sessionId_idx",
+ "columns": [
+ {
+ "expression": "sessionId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthAccessTokenV2_userId_idx": {
+ "name": "oauthAccessTokenV2_userId_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthAccessTokenV2_authorizationCodeId_idx": {
+ "name": "oauthAccessTokenV2_authorizationCodeId_idx",
+ "columns": [
+ {
+ "expression": "authorizationCodeId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthAccessTokenV2_refreshId_idx": {
+ "name": "oauthAccessTokenV2_refreshId_idx",
+ "columns": [
+ {
+ "expression": "refreshId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauthAccessTokenV2_clientId_oauthClient_clientId_fk": {
+ "name": "oauthAccessTokenV2_clientId_oauthClient_clientId_fk",
+ "tableFrom": "oauthAccessTokenV2",
+ "tableTo": "oauthClient",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthAccessTokenV2_sessionId_session_id_fk": {
+ "name": "oauthAccessTokenV2_sessionId_session_id_fk",
+ "tableFrom": "oauthAccessTokenV2",
+ "tableTo": "session",
+ "columnsFrom": [
+ "sessionId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "oauthAccessTokenV2_userId_user_id_fk": {
+ "name": "oauthAccessTokenV2_userId_user_id_fk",
+ "tableFrom": "oauthAccessTokenV2",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthAccessTokenV2_refreshId_oauthRefreshToken_id_fk": {
+ "name": "oauthAccessTokenV2_refreshId_oauthRefreshToken_id_fk",
+ "tableFrom": "oauthAccessTokenV2",
+ "tableTo": "oauthRefreshToken",
+ "columnsFrom": [
+ "refreshId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthAccessTokenV2_token_unique": {
+ "name": "oauthAccessTokenV2_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthApplication": {
+ "name": "oauthApplication",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientSecret": {
+ "name": "clientSecret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "redirectUrls": {
+ "name": "redirectUrls",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "disabled": {
+ "name": "disabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauthApplication_userId_user_id_fk": {
+ "name": "oauthApplication_userId_user_id_fk",
+ "tableFrom": "oauthApplication",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthApplication_clientId_unique": {
+ "name": "oauthApplication_clientId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "clientId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthClient": {
+ "name": "oauthClient",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientSecret": {
+ "name": "clientSecret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "clientDiscoveryId": {
+ "name": "clientDiscoveryId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "disabled": {
+ "name": "disabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "skipConsent": {
+ "name": "skipConsent",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enableEndSession": {
+ "name": "enableEndSession",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "subjectType": {
+ "name": "subjectType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "clientCredentialsScopes": {
+ "name": "clientCredentialsScopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "uri": {
+ "name": "uri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "contacts": {
+ "name": "contacts",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tos": {
+ "name": "tos",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "policy": {
+ "name": "policy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "softwareId": {
+ "name": "softwareId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "softwareVersion": {
+ "name": "softwareVersion",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "softwareStatement": {
+ "name": "softwareStatement",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "redirectUris": {
+ "name": "redirectUris",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "postLogoutRedirectUris": {
+ "name": "postLogoutRedirectUris",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "backchannelLogoutUri": {
+ "name": "backchannelLogoutUri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "backchannelLogoutSessionRequired": {
+ "name": "backchannelLogoutSessionRequired",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tokenEndpointAuthMethod": {
+ "name": "tokenEndpointAuthMethod",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "applicationType": {
+ "name": "applicationType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "jwks": {
+ "name": "jwks",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "jwksUri": {
+ "name": "jwksUri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "grantTypes": {
+ "name": "grantTypes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "responseTypes": {
+ "name": "responseTypes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requirePKCE": {
+ "name": "requirePKCE",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "dpopBoundAccessTokens": {
+ "name": "dpopBoundAccessTokens",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "oauthClient_userId_idx": {
+ "name": "oauthClient_userId_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauthClient_userId_user_id_fk": {
+ "name": "oauthClient_userId_user_id_fk",
+ "tableFrom": "oauthClient",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthClient_clientId_unique": {
+ "name": "oauthClient_clientId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "clientId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthClientAssertion": {
+ "name": "oauthClientAssertion",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthClientResource": {
+ "name": "oauthClientResource",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "resourceId": {
+ "name": "resourceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "oauthClientResource_clientId_resourceId_uidx": {
+ "name": "oauthClientResource_clientId_resourceId_uidx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "resourceId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthClientResource_clientId_idx": {
+ "name": "oauthClientResource_clientId_idx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthClientResource_resourceId_idx": {
+ "name": "oauthClientResource_resourceId_idx",
+ "columns": [
+ {
+ "expression": "resourceId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauthClientResource_clientId_oauthClient_clientId_fk": {
+ "name": "oauthClientResource_clientId_oauthClient_clientId_fk",
+ "tableFrom": "oauthClientResource",
+ "tableTo": "oauthClient",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthClientResource_resourceId_oauthResource_identifier_fk": {
+ "name": "oauthClientResource_resourceId_oauthResource_identifier_fk",
+ "tableFrom": "oauthClientResource",
+ "tableTo": "oauthResource",
+ "columnsFrom": [
+ "resourceId"
+ ],
+ "columnsTo": [
+ "identifier"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthConsent": {
+ "name": "oauthConsent",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "consentGiven": {
+ "name": "consentGiven",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauthConsent_clientId_oauthApplication_clientId_fk": {
+ "name": "oauthConsent_clientId_oauthApplication_clientId_fk",
+ "tableFrom": "oauthConsent",
+ "tableTo": "oauthApplication",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthConsent_userId_user_id_fk": {
+ "name": "oauthConsent_userId_user_id_fk",
+ "tableFrom": "oauthConsent",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthConsentV2": {
+ "name": "oauthConsentV2",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resources": {
+ "name": "resources",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requestedUserInfoClaims": {
+ "name": "requestedUserInfoClaims",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "oauthConsentV2_clientId_idx": {
+ "name": "oauthConsentV2_clientId_idx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthConsentV2_userId_idx": {
+ "name": "oauthConsentV2_userId_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauthConsentV2_clientId_oauthClient_clientId_fk": {
+ "name": "oauthConsentV2_clientId_oauthClient_clientId_fk",
+ "tableFrom": "oauthConsentV2",
+ "tableTo": "oauthClient",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthConsentV2_userId_user_id_fk": {
+ "name": "oauthConsentV2_userId_user_id_fk",
+ "tableFrom": "oauthConsentV2",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthRefreshToken": {
+ "name": "oauthRefreshToken",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sessionId": {
+ "name": "sessionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authorizationCodeId": {
+ "name": "authorizationCodeId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resources": {
+ "name": "resources",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requestedUserInfoClaims": {
+ "name": "requestedUserInfoClaims",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "revoked": {
+ "name": "revoked",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rotatedAt": {
+ "name": "rotatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rotationReplayResponse": {
+ "name": "rotationReplayResponse",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rotationReplayExpiresAt": {
+ "name": "rotationReplayExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authTime": {
+ "name": "authTime",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "confirmation": {
+ "name": "confirmation",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "oauthRefreshToken_clientId_idx": {
+ "name": "oauthRefreshToken_clientId_idx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthRefreshToken_sessionId_idx": {
+ "name": "oauthRefreshToken_sessionId_idx",
+ "columns": [
+ {
+ "expression": "sessionId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthRefreshToken_userId_idx": {
+ "name": "oauthRefreshToken_userId_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthRefreshToken_authorizationCodeId_idx": {
+ "name": "oauthRefreshToken_authorizationCodeId_idx",
+ "columns": [
+ {
+ "expression": "authorizationCodeId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauthRefreshToken_clientId_oauthClient_clientId_fk": {
+ "name": "oauthRefreshToken_clientId_oauthClient_clientId_fk",
+ "tableFrom": "oauthRefreshToken",
+ "tableTo": "oauthClient",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthRefreshToken_sessionId_session_id_fk": {
+ "name": "oauthRefreshToken_sessionId_session_id_fk",
+ "tableFrom": "oauthRefreshToken",
+ "tableTo": "session",
+ "columnsFrom": [
+ "sessionId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "oauthRefreshToken_userId_user_id_fk": {
+ "name": "oauthRefreshToken_userId_user_id_fk",
+ "tableFrom": "oauthRefreshToken",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthRefreshToken_token_unique": {
+ "name": "oauthRefreshToken_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthResource": {
+ "name": "oauthResource",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "accessTokenTtl": {
+ "name": "accessTokenTtl",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refreshTokenTtl": {
+ "name": "refreshTokenTtl",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "signingAlgorithm": {
+ "name": "signingAlgorithm",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "signingKeyId": {
+ "name": "signingKeyId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "allowedScopes": {
+ "name": "allowedScopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "customClaims": {
+ "name": "customClaims",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "dpopBoundAccessTokensRequired": {
+ "name": "dpopBoundAccessTokensRequired",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "disabled": {
+ "name": "disabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "policyVersion": {
+ "name": "policyVersion",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 1
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthResource_identifier_unique": {
+ "name": "oauthResource_identifier_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "identifier"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.organization": {
+ "name": "organization",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "logo": {
+ "name": "logo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "monthlyEventCount": {
+ "name": "monthlyEventCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "overMonthlyLimit": {
+ "name": "overMonthlyLimit",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "approachingLimitNotifiedPeriodStart": {
+ "name": "approachingLimitNotifiedPeriodStart",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "planOverride": {
+ "name": "planOverride",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "custom_plan": {
+ "name": "custom_plan",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "organization_slug_unique": {
+ "name": "organization_slug_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "slug"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.segments": {
+ "name": "segments",
+ "schema": "",
+ "columns": {
+ "segment_id": {
+ "name": "segment_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "filters": {
+ "name": "filters",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "is_public": {
+ "name": "is_public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'segment'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "segments_organization_idx": {
+ "name": "segments_organization_idx",
+ "columns": [
+ {
+ "expression": "organization_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "segments_site_idx": {
+ "name": "segments_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "segments_organization_id_organization_id_fk": {
+ "name": "segments_organization_id_organization_id_fk",
+ "tableFrom": "segments",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "segments_site_id_sites_site_id_fk": {
+ "name": "segments_site_id_sites_site_id_fk",
+ "tableFrom": "segments",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "segments_user_id_user_id_fk": {
+ "name": "segments_user_id_user_id_fk",
+ "tableFrom": "segments",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.session": {
+ "name": "session",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ipAddress": {
+ "name": "ipAddress",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userAgent": {
+ "name": "userAgent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "impersonatedBy": {
+ "name": "impersonatedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "activeOrganizationId": {
+ "name": "activeOrganizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "activeTeamId": {
+ "name": "activeTeamId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "session_userId_user_id_fk": {
+ "name": "session_userId_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "session_token_unique": {
+ "name": "session_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.sites": {
+ "name": "sites",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "domain": {
+ "name": "domain",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "public": {
+ "name": "public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "embed_enabled": {
+ "name": "embed_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "saltUserIds": {
+ "name": "saltUserIds",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "blockBots": {
+ "name": "blockBots",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "first_party_proxy": {
+ "name": "first_party_proxy",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "excluded_ips": {
+ "name": "excluded_ips",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_countries": {
+ "name": "excluded_countries",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_paths": {
+ "name": "excluded_paths",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_hostnames": {
+ "name": "excluded_hostnames",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_user_agents": {
+ "name": "excluded_user_agents",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_asns": {
+ "name": "excluded_asns",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_query_params": {
+ "name": "excluded_query_params",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "sessionReplay": {
+ "name": "sessionReplay",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "webVitals": {
+ "name": "webVitals",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackErrors": {
+ "name": "trackErrors",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackOutbound": {
+ "name": "trackOutbound",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackUrlParams": {
+ "name": "trackUrlParams",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackInitialPageView": {
+ "name": "trackInitialPageView",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackSpaNavigation": {
+ "name": "trackSpaNavigation",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackIp": {
+ "name": "trackIp",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackButtonClicks": {
+ "name": "trackButtonClicks",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackCopy": {
+ "name": "trackCopy",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackFormInteractions": {
+ "name": "trackFormInteractions",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "api_key": {
+ "name": "api_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "private_link_key": {
+ "name": "private_link_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tags": {
+ "name": "tags",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "detected_platform": {
+ "name": "detected_platform",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "claim_expires_at": {
+ "name": "claim_expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "sites_created_by_user_id_fk": {
+ "name": "sites_created_by_user_id_fk",
+ "tableFrom": "sites",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "sites_organization_id_organization_id_fk": {
+ "name": "sites_organization_id_organization_id_fk",
+ "tableFrom": "sites",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "sites_type_check": {
+ "name": "sites_type_check",
+ "value": "\"sites\".\"type\" IS NULL OR \"sites\".\"type\" IN ('web', 'mobile')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.team": {
+ "name": "team",
+ "schema": "",
+ "columns": {
+ "memberCount": {
+ "name": "memberCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "team_organizationId_organization_id_fk": {
+ "name": "team_organizationId_organization_id_fk",
+ "tableFrom": "team",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organizationId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.teamMember": {
+ "name": "teamMember",
+ "schema": "",
+ "columns": {
+ "membershipKey": {
+ "name": "membershipKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "teamId": {
+ "name": "teamId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "teamMember_teamId_team_id_fk": {
+ "name": "teamMember_teamId_team_id_fk",
+ "tableFrom": "teamMember",
+ "tableTo": "team",
+ "columnsFrom": [
+ "teamId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "teamMember_userId_user_id_fk": {
+ "name": "teamMember_userId_user_id_fk",
+ "tableFrom": "teamMember",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "teamMember_membershipKey_unique": {
+ "name": "teamMember_membershipKey_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "membershipKey"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.team_site_access": {
+ "name": "team_site_access",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "team_site_access_team_idx": {
+ "name": "team_site_access_team_idx",
+ "columns": [
+ {
+ "expression": "team_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "team_site_access_site_idx": {
+ "name": "team_site_access_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "team_site_access_team_id_team_id_fk": {
+ "name": "team_site_access_team_id_team_id_fk",
+ "tableFrom": "team_site_access",
+ "tableTo": "team",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "team_site_access_site_id_sites_site_id_fk": {
+ "name": "team_site_access_site_id_sites_site_id_fk",
+ "tableFrom": "team_site_access",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "team_site_access_unique": {
+ "name": "team_site_access_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "team_id",
+ "site_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.telemetry": {
+ "name": "telemetry",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "instance_id": {
+ "name": "instance_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "version": {
+ "name": "version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "table_counts": {
+ "name": "table_counts",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clickhouse_size_gb": {
+ "name": "clickhouse_size_gb",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user": {
+ "name": "user",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "username": {
+ "name": "username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "emailVerified": {
+ "name": "emailVerified",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'user'"
+ },
+ "displayUsername": {
+ "name": "displayUsername",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "banned": {
+ "name": "banned",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "banReason": {
+ "name": "banReason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "banExpires": {
+ "name": "banExpires",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "overMonthlyLimit": {
+ "name": "overMonthlyLimit",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "monthlyEventCount": {
+ "name": "monthlyEventCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "sendAutoEmailReports": {
+ "name": "sendAutoEmailReports",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "scheduled_tip_email_ids": {
+ "name": "scheduled_tip_email_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_username_unique": {
+ "name": "user_username_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "username"
+ ]
+ },
+ "user_email_unique": {
+ "name": "user_email_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "email"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_aliases": {
+ "name": "user_aliases",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "anonymous_id": {
+ "name": "anonymous_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_aliases_user_idx": {
+ "name": "user_aliases_user_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_aliases_anon_idx": {
+ "name": "user_aliases_anon_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "anonymous_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_aliases_site_id_sites_site_id_fk": {
+ "name": "user_aliases_site_id_sites_site_id_fk",
+ "tableFrom": "user_aliases",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_aliases_site_anon_unique": {
+ "name": "user_aliases_site_anon_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "site_id",
+ "anonymous_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_profiles": {
+ "name": "user_profiles",
+ "schema": "",
+ "columns": {
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "traits": {
+ "name": "traits",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_profiles_site_idx": {
+ "name": "user_profiles_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_profiles_site_id_sites_site_id_fk": {
+ "name": "user_profiles_site_id_sites_site_id_fk",
+ "tableFrom": "user_profiles",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "user_profiles_site_id_user_id_pk": {
+ "name": "user_profiles_site_id_user_id_pk",
+ "columns": [
+ "site_id",
+ "user_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verification": {
+ "name": "verification",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {
+ "public.import_platform_enum": {
+ "name": "import_platform_enum",
+ "schema": "public",
+ "values": [
+ "umami",
+ "simple_analytics",
+ "plausible"
+ ]
+ }
+ },
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/server/drizzle/meta/0022_snapshot.json b/server/drizzle/meta/0022_snapshot.json
new file mode 100644
index 000000000..c4f180087
--- /dev/null
+++ b/server/drizzle/meta/0022_snapshot.json
@@ -0,0 +1,4671 @@
+{
+ "id": "17d8b70d-d08d-4c77-bf7f-fa0d06ea144b",
+ "prevId": "6a0f4378-a2c9-4cd9-9298-853718fba5d8",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.account": {
+ "name": "account",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "accountId": {
+ "name": "accountId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "providerId": {
+ "name": "providerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "accessToken": {
+ "name": "accessToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refreshToken": {
+ "name": "refreshToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "idToken": {
+ "name": "idToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessTokenExpiresAt": {
+ "name": "accessTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refreshTokenExpiresAt": {
+ "name": "refreshTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "password": {
+ "name": "password",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "account_userId_user_id_fk": {
+ "name": "account_userId_user_id_fk",
+ "tableFrom": "account",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.active_sessions": {
+ "name": "active_sessions",
+ "schema": "",
+ "columns": {
+ "session_id": {
+ "name": "session_id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "start_time": {
+ "name": "start_time",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "last_activity": {
+ "name": "last_activity",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.annotations": {
+ "name": "annotations",
+ "schema": "",
+ "columns": {
+ "annotation_id": {
+ "name": "annotation_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "date": {
+ "name": "date",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "end_date": {
+ "name": "end_date",
+ "type": "timestamp with time zone",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "is_public": {
+ "name": "is_public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "annotations_site_date_idx": {
+ "name": "annotations_site_date_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "date",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "annotations_org_date_idx": {
+ "name": "annotations_org_date_idx",
+ "columns": [
+ {
+ "expression": "organization_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "date",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "annotations_site_id_sites_site_id_fk": {
+ "name": "annotations_site_id_sites_site_id_fk",
+ "tableFrom": "annotations",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "annotations_organization_id_organization_id_fk": {
+ "name": "annotations_organization_id_organization_id_fk",
+ "tableFrom": "annotations",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "annotations_user_id_user_id_fk": {
+ "name": "annotations_user_id_user_id_fk",
+ "tableFrom": "annotations",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.apikey": {
+ "name": "apikey",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "start": {
+ "name": "start",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "prefix": {
+ "name": "prefix",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refillInterval": {
+ "name": "refillInterval",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refillAmount": {
+ "name": "refillAmount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastRefillAt": {
+ "name": "lastRefillAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "rateLimitEnabled": {
+ "name": "rateLimitEnabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "rateLimitTimeWindow": {
+ "name": "rateLimitTimeWindow",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rateLimitMax": {
+ "name": "rateLimitMax",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requestCount": {
+ "name": "requestCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "remaining": {
+ "name": "remaining",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "lastRequest": {
+ "name": "lastRequest",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "configId": {
+ "name": "configId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "permissions": {
+ "name": "permissions",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.cancellation_feedback": {
+ "name": "cancellation_feedback",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "reason": {
+ "name": "reason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "reason_details": {
+ "name": "reason_details",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "retention_offer_shown": {
+ "name": "retention_offer_shown",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "retention_offer_accepted": {
+ "name": "retention_offer_accepted",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "outcome": {
+ "name": "outcome",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "plan_name_at_cancellation": {
+ "name": "plan_name_at_cancellation",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "monthly_event_count_at_cancellation": {
+ "name": "monthly_event_count_at_cancellation",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.dashboards": {
+ "name": "dashboards",
+ "schema": "",
+ "columns": {
+ "dashboard_id": {
+ "name": "dashboard_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'{\"cards\":[]}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "dashboards_site_id_sites_site_id_fk": {
+ "name": "dashboards_site_id_sites_site_id_fk",
+ "tableFrom": "dashboards",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "dashboards_user_id_user_id_fk": {
+ "name": "dashboards_user_id_user_id_fk",
+ "tableFrom": "dashboards",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.experiments": {
+ "name": "experiments",
+ "schema": "",
+ "columns": {
+ "experiment_id": {
+ "name": "experiment_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "feature_flag_id": {
+ "name": "feature_flag_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "primary_goal_id": {
+ "name": "primary_goal_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "hypothesis": {
+ "name": "hypothesis",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'draft'"
+ },
+ "winning_variant": {
+ "name": "winning_variant",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "ended_at": {
+ "name": "ended_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "experiments_site_idx": {
+ "name": "experiments_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "experiments_feature_flag_idx": {
+ "name": "experiments_feature_flag_idx",
+ "columns": [
+ {
+ "expression": "feature_flag_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "experiments_primary_goal_idx": {
+ "name": "experiments_primary_goal_idx",
+ "columns": [
+ {
+ "expression": "primary_goal_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "experiments_site_id_sites_site_id_fk": {
+ "name": "experiments_site_id_sites_site_id_fk",
+ "tableFrom": "experiments",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "experiments_feature_flag_id_feature_flags_flag_id_fk": {
+ "name": "experiments_feature_flag_id_feature_flags_flag_id_fk",
+ "tableFrom": "experiments",
+ "tableTo": "feature_flags",
+ "columnsFrom": [
+ "feature_flag_id"
+ ],
+ "columnsTo": [
+ "flag_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "experiments_primary_goal_id_goals_goal_id_fk": {
+ "name": "experiments_primary_goal_id_goals_goal_id_fk",
+ "tableFrom": "experiments",
+ "tableTo": "goals",
+ "columnsFrom": [
+ "primary_goal_id"
+ ],
+ "columnsTo": [
+ "goal_id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "experiments_site_flag_unique": {
+ "name": "experiments_site_flag_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "site_id",
+ "feature_flag_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "experiments_status_check": {
+ "name": "experiments_status_check",
+ "value": "status IN ('draft', 'running', 'paused', 'completed')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.feature_flags": {
+ "name": "feature_flags",
+ "schema": "",
+ "columns": {
+ "flag_id": {
+ "name": "flag_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enabled": {
+ "name": "enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "runtime": {
+ "name": "runtime",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'client'"
+ },
+ "flag_type": {
+ "name": "flag_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'boolean'"
+ },
+ "payload": {
+ "name": "payload",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "variants": {
+ "name": "variants",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "rollout_percentage": {
+ "name": "rollout_percentage",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 100
+ },
+ "rules": {
+ "name": "rules",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "condition_sets": {
+ "name": "condition_sets",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "salt": {
+ "name": "salt",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "md5(random()::text || clock_timestamp()::text)"
+ },
+ "version": {
+ "name": "version",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "feature_flags_site_idx": {
+ "name": "feature_flags_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "feature_flags_site_id_sites_site_id_fk": {
+ "name": "feature_flags_site_id_sites_site_id_fk",
+ "tableFrom": "feature_flags",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "feature_flags_site_key_unique": {
+ "name": "feature_flags_site_key_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "site_id",
+ "key"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {
+ "feature_flags_rollout_check": {
+ "name": "feature_flags_rollout_check",
+ "value": "rollout_percentage >= 0 AND rollout_percentage <= 100"
+ },
+ "feature_flags_runtime_check": {
+ "name": "feature_flags_runtime_check",
+ "value": "runtime IN ('client', 'server', 'both')"
+ },
+ "feature_flags_type_check": {
+ "name": "feature_flags_type_check",
+ "value": "flag_type IN ('boolean', 'multivariate', 'remote_config')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.funnels": {
+ "name": "funnels",
+ "schema": "",
+ "columns": {
+ "report_id": {
+ "name": "report_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data": {
+ "name": "data",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "funnels_site_id_sites_site_id_fk": {
+ "name": "funnels_site_id_sites_site_id_fk",
+ "tableFrom": "funnels",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "funnels_user_id_user_id_fk": {
+ "name": "funnels_user_id_user_id_fk",
+ "tableFrom": "funnels",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.goals": {
+ "name": "goals",
+ "schema": "",
+ "columns": {
+ "goal_id": {
+ "name": "goal_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "goal_type": {
+ "name": "goal_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "config": {
+ "name": "config",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "goals_site_id_sites_site_id_fk": {
+ "name": "goals_site_id_sites_site_id_fk",
+ "tableFrom": "goals",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.gsc_connections": {
+ "name": "gsc_connections",
+ "schema": "",
+ "columns": {
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "gsc_property_url": {
+ "name": "gsc_property_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "gsc_connections_site_id_sites_site_id_fk": {
+ "name": "gsc_connections_site_id_sites_site_id_fk",
+ "tableFrom": "gsc_connections",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.import_status": {
+ "name": "import_status",
+ "schema": "",
+ "columns": {
+ "import_id": {
+ "name": "import_id",
+ "type": "uuid",
+ "primaryKey": true,
+ "notNull": true,
+ "default": "gen_random_uuid()"
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "platform": {
+ "name": "platform",
+ "type": "import_platform_enum",
+ "typeSchema": "public",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "imported_events": {
+ "name": "imported_events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "skipped_events": {
+ "name": "skipped_events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "invalid_events": {
+ "name": "invalid_events",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "completed_at": {
+ "name": "completed_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "import_status_site_id_sites_site_id_fk": {
+ "name": "import_status_site_id_sites_site_id_fk",
+ "tableFrom": "import_status",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "import_status_organization_id_organization_id_fk": {
+ "name": "import_status_organization_id_organization_id_fk",
+ "tableFrom": "import_status",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.invitation": {
+ "name": "invitation",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "inviterId": {
+ "name": "inviterId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "has_restricted_site_access": {
+ "name": "has_restricted_site_access",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "site_ids": {
+ "name": "site_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "site_role": {
+ "name": "site_role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "teamId": {
+ "name": "teamId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "invitation_inviterId_user_id_fk": {
+ "name": "invitation_inviterId_user_id_fk",
+ "tableFrom": "invitation",
+ "tableTo": "user",
+ "columnsFrom": [
+ "inviterId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "invitation_organizationId_organization_id_fk": {
+ "name": "invitation_organizationId_organization_id_fk",
+ "tableFrom": "invitation",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organizationId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "invitation_teamId_team_id_fk": {
+ "name": "invitation_teamId_team_id_fk",
+ "tableFrom": "invitation",
+ "tableTo": "team",
+ "columnsFrom": [
+ "teamId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.jwks": {
+ "name": "jwks",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "publicKey": {
+ "name": "publicKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "privateKey": {
+ "name": "privateKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "alg": {
+ "name": "alg",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "crv": {
+ "name": "crv",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.lifecycle_email_log": {
+ "name": "lifecycle_email_log",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "email_key": {
+ "name": "email_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sent_at": {
+ "name": "sent_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "lifecycle_email_log_user_id_user_id_fk": {
+ "name": "lifecycle_email_log_user_id_user_id_fk",
+ "tableFrom": "lifecycle_email_log",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "lifecycle_email_log_user_email_key_unique": {
+ "name": "lifecycle_email_log_user_email_key_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "user_id",
+ "email_key"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.member": {
+ "name": "member",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "has_restricted_site_access": {
+ "name": "has_restricted_site_access",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "member_organizationId_organization_id_fk": {
+ "name": "member_organizationId_organization_id_fk",
+ "tableFrom": "member",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organizationId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "member_userId_user_id_fk": {
+ "name": "member_userId_user_id_fk",
+ "tableFrom": "member",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.member_site_access": {
+ "name": "member_site_access",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "member_id": {
+ "name": "member_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "member_site_access_member_idx": {
+ "name": "member_site_access_member_idx",
+ "columns": [
+ {
+ "expression": "member_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "member_site_access_site_idx": {
+ "name": "member_site_access_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "member_site_access_member_id_member_id_fk": {
+ "name": "member_site_access_member_id_member_id_fk",
+ "tableFrom": "member_site_access",
+ "tableTo": "member",
+ "columnsFrom": [
+ "member_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "member_site_access_site_id_sites_site_id_fk": {
+ "name": "member_site_access_site_id_sites_site_id_fk",
+ "tableFrom": "member_site_access",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "member_site_access_created_by_user_id_fk": {
+ "name": "member_site_access_created_by_user_id_fk",
+ "tableFrom": "member_site_access",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "member_site_access_unique": {
+ "name": "member_site_access_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "member_id",
+ "site_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthAccessToken": {
+ "name": "oauthAccessToken",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "accessToken": {
+ "name": "accessToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refreshToken": {
+ "name": "refreshToken",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "accessTokenExpiresAt": {
+ "name": "accessTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "refreshTokenExpiresAt": {
+ "name": "refreshTokenExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauthAccessToken_clientId_oauthApplication_clientId_fk": {
+ "name": "oauthAccessToken_clientId_oauthApplication_clientId_fk",
+ "tableFrom": "oauthAccessToken",
+ "tableTo": "oauthApplication",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthAccessToken_userId_user_id_fk": {
+ "name": "oauthAccessToken_userId_user_id_fk",
+ "tableFrom": "oauthAccessToken",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthAccessToken_accessToken_unique": {
+ "name": "oauthAccessToken_accessToken_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "accessToken"
+ ]
+ },
+ "oauthAccessToken_refreshToken_unique": {
+ "name": "oauthAccessToken_refreshToken_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "refreshToken"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthAccessTokenV2": {
+ "name": "oauthAccessTokenV2",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sessionId": {
+ "name": "sessionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authorizationCodeId": {
+ "name": "authorizationCodeId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resources": {
+ "name": "resources",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requestedUserInfoClaims": {
+ "name": "requestedUserInfoClaims",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refreshId": {
+ "name": "refreshId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "revoked": {
+ "name": "revoked",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "confirmation": {
+ "name": "confirmation",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "oauthAccessTokenV2_clientId_idx": {
+ "name": "oauthAccessTokenV2_clientId_idx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthAccessTokenV2_sessionId_idx": {
+ "name": "oauthAccessTokenV2_sessionId_idx",
+ "columns": [
+ {
+ "expression": "sessionId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthAccessTokenV2_userId_idx": {
+ "name": "oauthAccessTokenV2_userId_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthAccessTokenV2_authorizationCodeId_idx": {
+ "name": "oauthAccessTokenV2_authorizationCodeId_idx",
+ "columns": [
+ {
+ "expression": "authorizationCodeId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthAccessTokenV2_refreshId_idx": {
+ "name": "oauthAccessTokenV2_refreshId_idx",
+ "columns": [
+ {
+ "expression": "refreshId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauthAccessTokenV2_clientId_oauthClient_clientId_fk": {
+ "name": "oauthAccessTokenV2_clientId_oauthClient_clientId_fk",
+ "tableFrom": "oauthAccessTokenV2",
+ "tableTo": "oauthClient",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthAccessTokenV2_sessionId_session_id_fk": {
+ "name": "oauthAccessTokenV2_sessionId_session_id_fk",
+ "tableFrom": "oauthAccessTokenV2",
+ "tableTo": "session",
+ "columnsFrom": [
+ "sessionId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "oauthAccessTokenV2_userId_user_id_fk": {
+ "name": "oauthAccessTokenV2_userId_user_id_fk",
+ "tableFrom": "oauthAccessTokenV2",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthAccessTokenV2_refreshId_oauthRefreshToken_id_fk": {
+ "name": "oauthAccessTokenV2_refreshId_oauthRefreshToken_id_fk",
+ "tableFrom": "oauthAccessTokenV2",
+ "tableTo": "oauthRefreshToken",
+ "columnsFrom": [
+ "refreshId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthAccessTokenV2_token_unique": {
+ "name": "oauthAccessTokenV2_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthApplication": {
+ "name": "oauthApplication",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientSecret": {
+ "name": "clientSecret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "redirectUrls": {
+ "name": "redirectUrls",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "disabled": {
+ "name": "disabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauthApplication_userId_user_id_fk": {
+ "name": "oauthApplication_userId_user_id_fk",
+ "tableFrom": "oauthApplication",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthApplication_clientId_unique": {
+ "name": "oauthApplication_clientId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "clientId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthClient": {
+ "name": "oauthClient",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientSecret": {
+ "name": "clientSecret",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "clientDiscoveryId": {
+ "name": "clientDiscoveryId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "disabled": {
+ "name": "disabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "skipConsent": {
+ "name": "skipConsent",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "enableEndSession": {
+ "name": "enableEndSession",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "subjectType": {
+ "name": "subjectType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "clientCredentialsScopes": {
+ "name": "clientCredentialsScopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "uri": {
+ "name": "uri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "icon": {
+ "name": "icon",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "contacts": {
+ "name": "contacts",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tos": {
+ "name": "tos",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "policy": {
+ "name": "policy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "softwareId": {
+ "name": "softwareId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "softwareVersion": {
+ "name": "softwareVersion",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "softwareStatement": {
+ "name": "softwareStatement",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "redirectUris": {
+ "name": "redirectUris",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "postLogoutRedirectUris": {
+ "name": "postLogoutRedirectUris",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "backchannelLogoutUri": {
+ "name": "backchannelLogoutUri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "backchannelLogoutSessionRequired": {
+ "name": "backchannelLogoutSessionRequired",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tokenEndpointAuthMethod": {
+ "name": "tokenEndpointAuthMethod",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "applicationType": {
+ "name": "applicationType",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "jwks": {
+ "name": "jwks",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "jwksUri": {
+ "name": "jwksUri",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "grantTypes": {
+ "name": "grantTypes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "responseTypes": {
+ "name": "responseTypes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requirePKCE": {
+ "name": "requirePKCE",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "dpopBoundAccessTokens": {
+ "name": "dpopBoundAccessTokens",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "oauthClient_userId_idx": {
+ "name": "oauthClient_userId_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauthClient_userId_user_id_fk": {
+ "name": "oauthClient_userId_user_id_fk",
+ "tableFrom": "oauthClient",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthClient_clientId_unique": {
+ "name": "oauthClient_clientId_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "clientId"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthClientAssertion": {
+ "name": "oauthClientAssertion",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthClientResource": {
+ "name": "oauthClientResource",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "resourceId": {
+ "name": "resourceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "oauthClientResource_clientId_resourceId_uidx": {
+ "name": "oauthClientResource_clientId_resourceId_uidx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "resourceId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthClientResource_clientId_idx": {
+ "name": "oauthClientResource_clientId_idx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthClientResource_resourceId_idx": {
+ "name": "oauthClientResource_resourceId_idx",
+ "columns": [
+ {
+ "expression": "resourceId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauthClientResource_clientId_oauthClient_clientId_fk": {
+ "name": "oauthClientResource_clientId_oauthClient_clientId_fk",
+ "tableFrom": "oauthClientResource",
+ "tableTo": "oauthClient",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthClientResource_resourceId_oauthResource_identifier_fk": {
+ "name": "oauthClientResource_resourceId_oauthResource_identifier_fk",
+ "tableFrom": "oauthClientResource",
+ "tableTo": "oauthResource",
+ "columnsFrom": [
+ "resourceId"
+ ],
+ "columnsTo": [
+ "identifier"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthConsent": {
+ "name": "oauthConsent",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "consentGiven": {
+ "name": "consentGiven",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "oauthConsent_clientId_oauthApplication_clientId_fk": {
+ "name": "oauthConsent_clientId_oauthApplication_clientId_fk",
+ "tableFrom": "oauthConsent",
+ "tableTo": "oauthApplication",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthConsent_userId_user_id_fk": {
+ "name": "oauthConsent_userId_user_id_fk",
+ "tableFrom": "oauthConsent",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthConsentV2": {
+ "name": "oauthConsentV2",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resources": {
+ "name": "resources",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requestedUserInfoClaims": {
+ "name": "requestedUserInfoClaims",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "oauthConsentV2_clientId_idx": {
+ "name": "oauthConsentV2_clientId_idx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthConsentV2_userId_idx": {
+ "name": "oauthConsentV2_userId_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauthConsentV2_clientId_oauthClient_clientId_fk": {
+ "name": "oauthConsentV2_clientId_oauthClient_clientId_fk",
+ "tableFrom": "oauthConsentV2",
+ "tableTo": "oauthClient",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthConsentV2_userId_user_id_fk": {
+ "name": "oauthConsentV2_userId_user_id_fk",
+ "tableFrom": "oauthConsentV2",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthRefreshToken": {
+ "name": "oauthRefreshToken",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clientId": {
+ "name": "clientId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "sessionId": {
+ "name": "sessionId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "referenceId": {
+ "name": "referenceId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authorizationCodeId": {
+ "name": "authorizationCodeId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "resources": {
+ "name": "resources",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "requestedUserInfoClaims": {
+ "name": "requestedUserInfoClaims",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "revoked": {
+ "name": "revoked",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rotatedAt": {
+ "name": "rotatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rotationReplayResponse": {
+ "name": "rotationReplayResponse",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "rotationReplayExpiresAt": {
+ "name": "rotationReplayExpiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "authTime": {
+ "name": "authTime",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "confirmation": {
+ "name": "confirmation",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "scopes": {
+ "name": "scopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {
+ "oauthRefreshToken_clientId_idx": {
+ "name": "oauthRefreshToken_clientId_idx",
+ "columns": [
+ {
+ "expression": "clientId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthRefreshToken_sessionId_idx": {
+ "name": "oauthRefreshToken_sessionId_idx",
+ "columns": [
+ {
+ "expression": "sessionId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthRefreshToken_userId_idx": {
+ "name": "oauthRefreshToken_userId_idx",
+ "columns": [
+ {
+ "expression": "userId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "oauthRefreshToken_authorizationCodeId_idx": {
+ "name": "oauthRefreshToken_authorizationCodeId_idx",
+ "columns": [
+ {
+ "expression": "authorizationCodeId",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "oauthRefreshToken_clientId_oauthClient_clientId_fk": {
+ "name": "oauthRefreshToken_clientId_oauthClient_clientId_fk",
+ "tableFrom": "oauthRefreshToken",
+ "tableTo": "oauthClient",
+ "columnsFrom": [
+ "clientId"
+ ],
+ "columnsTo": [
+ "clientId"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "oauthRefreshToken_sessionId_session_id_fk": {
+ "name": "oauthRefreshToken_sessionId_session_id_fk",
+ "tableFrom": "oauthRefreshToken",
+ "tableTo": "session",
+ "columnsFrom": [
+ "sessionId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "oauthRefreshToken_userId_user_id_fk": {
+ "name": "oauthRefreshToken_userId_user_id_fk",
+ "tableFrom": "oauthRefreshToken",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthRefreshToken_token_unique": {
+ "name": "oauthRefreshToken_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.oauthResource": {
+ "name": "oauthResource",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "accessTokenTtl": {
+ "name": "accessTokenTtl",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "refreshTokenTtl": {
+ "name": "refreshTokenTtl",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "signingAlgorithm": {
+ "name": "signingAlgorithm",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "signingKeyId": {
+ "name": "signingKeyId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "allowedScopes": {
+ "name": "allowedScopes",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "customClaims": {
+ "name": "customClaims",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "dpopBoundAccessTokensRequired": {
+ "name": "dpopBoundAccessTokensRequired",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "disabled": {
+ "name": "disabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "policyVersion": {
+ "name": "policyVersion",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 1
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "oauthResource_identifier_unique": {
+ "name": "oauthResource_identifier_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "identifier"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.organization": {
+ "name": "organization",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "logo": {
+ "name": "logo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "monthlyEventCount": {
+ "name": "monthlyEventCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "overMonthlyLimit": {
+ "name": "overMonthlyLimit",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "approachingLimitNotifiedPeriodStart": {
+ "name": "approachingLimitNotifiedPeriodStart",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "planOverride": {
+ "name": "planOverride",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "custom_plan": {
+ "name": "custom_plan",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "organization_slug_unique": {
+ "name": "organization_slug_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "slug"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.segments": {
+ "name": "segments",
+ "schema": "",
+ "columns": {
+ "segment_id": {
+ "name": "segment_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "filters": {
+ "name": "filters",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'[]'::jsonb"
+ },
+ "is_public": {
+ "name": "is_public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": false
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'segment'"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "segments_organization_idx": {
+ "name": "segments_organization_idx",
+ "columns": [
+ {
+ "expression": "organization_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "segments_site_idx": {
+ "name": "segments_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "segments_organization_id_organization_id_fk": {
+ "name": "segments_organization_id_organization_id_fk",
+ "tableFrom": "segments",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "segments_site_id_sites_site_id_fk": {
+ "name": "segments_site_id_sites_site_id_fk",
+ "tableFrom": "segments",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "segments_user_id_user_id_fk": {
+ "name": "segments_user_id_user_id_fk",
+ "tableFrom": "segments",
+ "tableTo": "user",
+ "columnsFrom": [
+ "user_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.session": {
+ "name": "session",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "token": {
+ "name": "token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "ipAddress": {
+ "name": "ipAddress",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userAgent": {
+ "name": "userAgent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "impersonatedBy": {
+ "name": "impersonatedBy",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "activeOrganizationId": {
+ "name": "activeOrganizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "activeTeamId": {
+ "name": "activeTeamId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "session_userId_user_id_fk": {
+ "name": "session_userId_user_id_fk",
+ "tableFrom": "session",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "session_token_unique": {
+ "name": "session_token_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "token"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.site_transfers": {
+ "name": "site_transfers",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "source_organization_id": {
+ "name": "source_organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "recipient_email": {
+ "name": "recipient_email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "site_transfers_site_id_sites_site_id_fk": {
+ "name": "site_transfers_site_id_sites_site_id_fk",
+ "tableFrom": "site_transfers",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "site_transfers_source_organization_id_organization_id_fk": {
+ "name": "site_transfers_source_organization_id_organization_id_fk",
+ "tableFrom": "site_transfers",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "source_organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "site_transfers_created_by_user_id_fk": {
+ "name": "site_transfers_created_by_user_id_fk",
+ "tableFrom": "site_transfers",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "site_transfers_site_unique": {
+ "name": "site_transfers_site_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "site_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.sites": {
+ "name": "sites",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "domain": {
+ "name": "domain",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "now()"
+ },
+ "created_by": {
+ "name": "created_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "organization_id": {
+ "name": "organization_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "public": {
+ "name": "public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "embed_enabled": {
+ "name": "embed_enabled",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "saltUserIds": {
+ "name": "saltUserIds",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "blockBots": {
+ "name": "blockBots",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "default": true
+ },
+ "first_party_proxy": {
+ "name": "first_party_proxy",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "excluded_ips": {
+ "name": "excluded_ips",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_countries": {
+ "name": "excluded_countries",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_paths": {
+ "name": "excluded_paths",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_hostnames": {
+ "name": "excluded_hostnames",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_user_agents": {
+ "name": "excluded_user_agents",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_asns": {
+ "name": "excluded_asns",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "excluded_query_params": {
+ "name": "excluded_query_params",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "sessionReplay": {
+ "name": "sessionReplay",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "webVitals": {
+ "name": "webVitals",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackErrors": {
+ "name": "trackErrors",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackOutbound": {
+ "name": "trackOutbound",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackUrlParams": {
+ "name": "trackUrlParams",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackInitialPageView": {
+ "name": "trackInitialPageView",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackSpaNavigation": {
+ "name": "trackSpaNavigation",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "trackIp": {
+ "name": "trackIp",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackButtonClicks": {
+ "name": "trackButtonClicks",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackCopy": {
+ "name": "trackCopy",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "trackFormInteractions": {
+ "name": "trackFormInteractions",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "api_key": {
+ "name": "api_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "private_link_key": {
+ "name": "private_link_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tags": {
+ "name": "tags",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ },
+ "detected_platform": {
+ "name": "detected_platform",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "claim_expires_at": {
+ "name": "claim_expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "sites_created_by_user_id_fk": {
+ "name": "sites_created_by_user_id_fk",
+ "tableFrom": "sites",
+ "tableTo": "user",
+ "columnsFrom": [
+ "created_by"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ },
+ "sites_organization_id_organization_id_fk": {
+ "name": "sites_organization_id_organization_id_fk",
+ "tableFrom": "sites",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organization_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {
+ "sites_type_check": {
+ "name": "sites_type_check",
+ "value": "\"sites\".\"type\" IS NULL OR \"sites\".\"type\" IN ('web', 'mobile')"
+ }
+ },
+ "isRLSEnabled": false
+ },
+ "public.team": {
+ "name": "team",
+ "schema": "",
+ "columns": {
+ "memberCount": {
+ "name": "memberCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 0
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "organizationId": {
+ "name": "organizationId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "team_organizationId_organization_id_fk": {
+ "name": "team_organizationId_organization_id_fk",
+ "tableFrom": "team",
+ "tableTo": "organization",
+ "columnsFrom": [
+ "organizationId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.teamMember": {
+ "name": "teamMember",
+ "schema": "",
+ "columns": {
+ "membershipKey": {
+ "name": "membershipKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "teamId": {
+ "name": "teamId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "userId": {
+ "name": "userId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "teamMember_teamId_team_id_fk": {
+ "name": "teamMember_teamId_team_id_fk",
+ "tableFrom": "teamMember",
+ "tableTo": "team",
+ "columnsFrom": [
+ "teamId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "teamMember_userId_user_id_fk": {
+ "name": "teamMember_userId_user_id_fk",
+ "tableFrom": "teamMember",
+ "tableTo": "user",
+ "columnsFrom": [
+ "userId"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "teamMember_membershipKey_unique": {
+ "name": "teamMember_membershipKey_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "membershipKey"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.team_site_access": {
+ "name": "team_site_access",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "team_id": {
+ "name": "team_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "team_site_access_team_idx": {
+ "name": "team_site_access_team_idx",
+ "columns": [
+ {
+ "expression": "team_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "team_site_access_site_idx": {
+ "name": "team_site_access_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "team_site_access_team_id_team_id_fk": {
+ "name": "team_site_access_team_id_team_id_fk",
+ "tableFrom": "team_site_access",
+ "tableTo": "team",
+ "columnsFrom": [
+ "team_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ },
+ "team_site_access_site_id_sites_site_id_fk": {
+ "name": "team_site_access_site_id_sites_site_id_fk",
+ "tableFrom": "team_site_access",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "team_site_access_unique": {
+ "name": "team_site_access_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "team_id",
+ "site_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.telemetry": {
+ "name": "telemetry",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "instance_id": {
+ "name": "instance_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "version": {
+ "name": "version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "table_counts": {
+ "name": "table_counts",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "clickhouse_size_gb": {
+ "name": "clickhouse_size_gb",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": true
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user": {
+ "name": "user",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "username": {
+ "name": "username",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "email": {
+ "name": "email",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "emailVerified": {
+ "name": "emailVerified",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'user'"
+ },
+ "displayUsername": {
+ "name": "displayUsername",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "banned": {
+ "name": "banned",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "banReason": {
+ "name": "banReason",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "banExpires": {
+ "name": "banExpires",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "overMonthlyLimit": {
+ "name": "overMonthlyLimit",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": false
+ },
+ "monthlyEventCount": {
+ "name": "monthlyEventCount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "default": 0
+ },
+ "sendAutoEmailReports": {
+ "name": "sendAutoEmailReports",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": false,
+ "default": true
+ },
+ "scheduled_tip_email_ids": {
+ "name": "scheduled_tip_email_ids",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'[]'::jsonb"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_username_unique": {
+ "name": "user_username_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "username"
+ ]
+ },
+ "user_email_unique": {
+ "name": "user_email_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "email"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_aliases": {
+ "name": "user_aliases",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "serial",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "anonymous_id": {
+ "name": "anonymous_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_aliases_user_idx": {
+ "name": "user_aliases_user_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "user_aliases_anon_idx": {
+ "name": "user_aliases_anon_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "anonymous_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_aliases_site_id_sites_site_id_fk": {
+ "name": "user_aliases_site_id_sites_site_id_fk",
+ "tableFrom": "user_aliases",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {
+ "user_aliases_site_anon_unique": {
+ "name": "user_aliases_site_anon_unique",
+ "nullsNotDistinct": false,
+ "columns": [
+ "site_id",
+ "anonymous_id"
+ ]
+ }
+ },
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.user_profiles": {
+ "name": "user_profiles",
+ "schema": "",
+ "columns": {
+ "site_id": {
+ "name": "site_id",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "traits": {
+ "name": "traits",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false,
+ "default": "'{}'::jsonb"
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "user_profiles_site_idx": {
+ "name": "user_profiles_site_idx",
+ "columns": [
+ {
+ "expression": "site_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "user_profiles_site_id_sites_site_id_fk": {
+ "name": "user_profiles_site_id_sites_site_id_fk",
+ "tableFrom": "user_profiles",
+ "tableTo": "sites",
+ "columnsFrom": [
+ "site_id"
+ ],
+ "columnsTo": [
+ "site_id"
+ ],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "user_profiles_site_id_user_id_pk": {
+ "name": "user_profiles_site_id_user_id_pk",
+ "columns": [
+ "site_id",
+ "user_id"
+ ]
+ }
+ },
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ },
+ "public.verification": {
+ "name": "verification",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "identifier": {
+ "name": "identifier",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {},
+ "checkConstraints": {},
+ "isRLSEnabled": false
+ }
+ },
+ "enums": {
+ "public.import_platform_enum": {
+ "name": "import_platform_enum",
+ "schema": "public",
+ "values": [
+ "umami",
+ "simple_analytics",
+ "plausible"
+ ]
+ }
+ },
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
\ No newline at end of file
diff --git a/server/drizzle/meta/_journal.json b/server/drizzle/meta/_journal.json
index 8bd607b8c..adfcc377c 100644
--- a/server/drizzle/meta/_journal.json
+++ b/server/drizzle/meta/_journal.json
@@ -148,6 +148,20 @@
"when": 1789189000176,
"tag": "0020_unclaimed_sites",
"breakpoints": true
+ },
+ {
+ "idx": 21,
+ "version": "7",
+ "when": 1790740950134,
+ "tag": "0021_site_grant_roles",
+ "breakpoints": true
+ },
+ {
+ "idx": 22,
+ "version": "7",
+ "when": 1790741724744,
+ "tag": "0022_site_transfers",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/server/src/api/__snapshots__/routes.test.ts.snap b/server/src/api/__snapshots__/routes.test.ts.snap
new file mode 100644
index 000000000..6c37303b5
--- /dev/null
+++ b/server/src/api/__snapshots__/routes.test.ts.snap
@@ -0,0 +1,178 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`API route table > pins the access each route requires 1`] = `
+[
+ "DELETE /api/admin/organizations/:organizationId/members/:memberId β†’ system-admin",
+ "DELETE /api/mcp β†’ public",
+ "DELETE /api/organizations/:organizationId/teams/:teamId β†’ org teams:manage [admin+]",
+ "DELETE /api/sites/:siteId β†’ site sites:delete [admin+]",
+ "DELETE /api/sites/:siteId/annotations/:annotationId β†’ site annotations:write [member+]",
+ "DELETE /api/sites/:siteId/dashboards/:dashboardId β†’ site dashboards:write [member+]",
+ "DELETE /api/sites/:siteId/experiments/:experimentId β†’ site experiments:write [editor+]",
+ "DELETE /api/sites/:siteId/feature-flags/:flagId β†’ site flags:write [editor+]",
+ "DELETE /api/sites/:siteId/funnels/:funnelId β†’ site funnels:write [member+]",
+ "DELETE /api/sites/:siteId/goals/:goalId β†’ site goals:write [member+]",
+ "DELETE /api/sites/:siteId/gsc/disconnect β†’ site gsc:write [editor+]",
+ "DELETE /api/sites/:siteId/imports/:importId β†’ site imports:write [editor+]",
+ "DELETE /api/sites/:siteId/segments/:segmentId β†’ site segments:write [member+]",
+ "DELETE /api/sites/:siteId/session-replay/:sessionId β†’ site replay:delete [editor+]",
+ "DELETE /api/sites/:siteId/transfer β†’ site sites:transfer [admin+]",
+ "DELETE /api/sites/:siteId/users/:userId β†’ site users:delete [editor+]",
+ "GET /api/admin/clickhouse-query-log β†’ system-admin",
+ "GET /api/admin/clickhouse-stats β†’ system-admin",
+ "GET /api/admin/organization-options β†’ system-admin",
+ "GET /api/admin/organizations β†’ system-admin",
+ "GET /api/admin/organizations/:organizationId/members/:memberId β†’ system-admin",
+ "GET /api/admin/service-event-count β†’ system-admin",
+ "GET /api/admin/sites β†’ system-admin",
+ "GET /api/admin/subscription-plans β†’ system-admin",
+ "GET /api/config β†’ public",
+ "GET /api/gsc/callback β†’ public",
+ "GET /api/health β†’ public",
+ "GET /api/mcp β†’ public",
+ "GET /api/org-event-count/:organizationId β†’ org analytics:read [viewer+]",
+ "GET /api/organizations β†’ public",
+ "GET /api/organizations/:organizationId/api-usage β†’ org org:read [viewer+]",
+ "GET /api/organizations/:organizationId/members β†’ org org:read [viewer+]",
+ "GET /api/organizations/:organizationId/sites β†’ org org:read [viewer+]",
+ "GET /api/organizations/:organizationId/teams β†’ org org:read [viewer+]",
+ "GET /api/site-transfers/:transferId β†’ authenticated",
+ "GET /api/site/check-install β†’ public",
+ "GET /api/site/tracking-config/:siteId β†’ public",
+ "GET /api/sites/:siteId β†’ site sites:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/annotations β†’ site annotations:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/bots/ai-summary β†’ site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/bots/by-dimension β†’ site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/bots/overview β†’ site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/bots/time-series β†’ site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/dashboards β†’ site dashboards:read [viewer+]",
+ "GET /api/sites/:siteId/dashboards/:dashboardId β†’ site dashboards:read [viewer+]",
+ "GET /api/sites/:siteId/embed-stats β†’ public",
+ "GET /api/sites/:siteId/errors/events β†’ site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/errors/names β†’ site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/errors/time-series β†’ site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/events β†’ site events:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/events/autocapture β†’ site events:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/events/autocapture-values β†’ site events:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/events/count β†’ site events:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/events/names β†’ site events:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/events/outbound β†’ site events:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/events/properties β†’ site events:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/events/time-series β†’ site events:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/excluded-asns β†’ site sites:read [viewer+]",
+ "GET /api/sites/:siteId/excluded-countries β†’ site sites:read [viewer+]",
+ "GET /api/sites/:siteId/excluded-hostnames β†’ site sites:read [viewer+]",
+ "GET /api/sites/:siteId/excluded-ips β†’ site sites:read [viewer+]",
+ "GET /api/sites/:siteId/excluded-paths β†’ site sites:read [viewer+]",
+ "GET /api/sites/:siteId/excluded-query-params β†’ site sites:read [viewer+]",
+ "GET /api/sites/:siteId/excluded-user-agents β†’ site sites:read [viewer+]",
+ "GET /api/sites/:siteId/experiments β†’ site experiments:read [viewer+]",
+ "GET /api/sites/:siteId/experiments/:experimentId/results β†’ site experiments:read [viewer+]",
+ "GET /api/sites/:siteId/export/pdf β†’ site analytics:read [viewer+]",
+ "GET /api/sites/:siteId/feature-flags β†’ site flags:read [viewer+]",
+ "GET /api/sites/:siteId/funnels β†’ site funnels:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/goals β†’ site goals:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/goals/:goalId/sessions β†’ site goals:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/goals/time-series β†’ site goals:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/gsc/connect β†’ site gsc:write [editor+]",
+ "GET /api/sites/:siteId/gsc/data β†’ site gsc:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/gsc/status β†’ site gsc:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/has-data β†’ site sites:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/imports β†’ site imports:read [editor+]",
+ "GET /api/sites/:siteId/is-public β†’ site sites:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/journeys β†’ site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/live-user-count β†’ site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/metric β†’ site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/metric-lite β†’ site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/overview β†’ site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/overview-bucketed-lite β†’ site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/overview-lite β†’ site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/overview/time-series β†’ site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/page-titles β†’ site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/performance/by-dimension β†’ site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/performance/overview β†’ site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/performance/time-series β†’ site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/private-link-config β†’ site sites:configure [editor+]",
+ "GET /api/sites/:siteId/retention β†’ site analytics:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/segments β†’ site segments:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/segments/:segmentId β†’ site segments:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/session-replay/:sessionId β†’ site replay:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/session-replay/list β†’ site replay:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/sessions β†’ site sessions:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/sessions/:sessionId β†’ site sessions:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/sessions/locations β†’ site sessions:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/transfer β†’ site sites:transfer [admin+]",
+ "GET /api/sites/:siteId/usage β†’ site sites:read [viewer+]",
+ "GET /api/sites/:siteId/user-traits/keys β†’ site users:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/user-traits/users β†’ site users:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/user-traits/values β†’ site users:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/users β†’ site users:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/users/:userId β†’ site users:read [viewer+] (or public)",
+ "GET /api/sites/:siteId/users/session-count β†’ site users:read [viewer+] (or public)",
+ "GET /api/stripe/invoices β†’ authenticated",
+ "GET /api/stripe/subscription β†’ authenticated",
+ "GET /api/user/organizations β†’ authenticated",
+ "GET /api/user/unsubscribe-marketing-oneclick β†’ public",
+ "GET /api/version β†’ public",
+ "PATCH /api/admin/organizations/:organizationId/members/:memberId β†’ system-admin",
+ "POST /api/admin/telemetry β†’ public",
+ "POST /api/as/activate β†’ authenticated",
+ "POST /api/as/webhook β†’ public",
+ "POST /api/mcp β†’ public",
+ "POST /api/organizations/:organizationId/analytics/query β†’ org sql:read [viewer+]",
+ "POST /api/organizations/:organizationId/analytics/query/generate β†’ org sql:read [viewer+]",
+ "POST /api/organizations/:organizationId/api-keys β†’ org apikeys:manage [admin+]",
+ "POST /api/organizations/:organizationId/members β†’ org members:manage [admin+]",
+ "POST /api/organizations/:organizationId/site-cards β†’ org analytics:read [viewer+]",
+ "POST /api/organizations/:organizationId/site-cards-lite β†’ org analytics:read [viewer+]",
+ "POST /api/organizations/:organizationId/sites β†’ org sites:create [admin+]",
+ "POST /api/organizations/:organizationId/teams β†’ org teams:manage [admin+]",
+ "POST /api/organizations/:organizationId/users β†’ org members:manage [admin+]",
+ "POST /api/session-replay/record/:siteId β†’ public",
+ "POST /api/site-transfers/:transferId/accept β†’ authenticated",
+ "POST /api/site-transfers/:transferId/decline β†’ authenticated",
+ "POST /api/site/:siteId/feature-flags/evaluate β†’ public",
+ "POST /api/sites/:siteId/annotations β†’ site annotations:write [member+]",
+ "POST /api/sites/:siteId/claim β†’ authenticated",
+ "POST /api/sites/:siteId/dashboards β†’ site dashboards:write [member+]",
+ "POST /api/sites/:siteId/dashboards/run-card β†’ site dashboards:read [viewer+]",
+ "POST /api/sites/:siteId/experiments β†’ site experiments:write [editor+]",
+ "POST /api/sites/:siteId/feature-flags β†’ site flags:write [editor+]",
+ "POST /api/sites/:siteId/feature-flags/evaluate β†’ site flags:read [viewer+]",
+ "POST /api/sites/:siteId/funnels β†’ site funnels:write [member+]",
+ "POST /api/sites/:siteId/funnels/:stepNumber/sessions β†’ site funnels:read [viewer+] (or public)",
+ "POST /api/sites/:siteId/funnels/analyze β†’ site funnels:read [viewer+] (or public)",
+ "POST /api/sites/:siteId/goals β†’ site goals:write [member+]",
+ "POST /api/sites/:siteId/gsc/select-property β†’ site gsc:write [editor+]",
+ "POST /api/sites/:siteId/imports β†’ site imports:write [editor+]",
+ "POST /api/sites/:siteId/imports/:importId/events β†’ site imports:write [editor+]",
+ "POST /api/sites/:siteId/private-link-config β†’ site sites:configure [editor+]",
+ "POST /api/sites/:siteId/segments β†’ site segments:write [member+]",
+ "POST /api/sites/:siteId/transfer β†’ site sites:transfer [admin+]",
+ "POST /api/sites/:siteId/users/identify β†’ site users:write [member+]",
+ "POST /api/sites/unclaimed β†’ public",
+ "POST /api/stripe/cancellation-feedback β†’ authenticated",
+ "POST /api/stripe/create-checkout-session β†’ authenticated",
+ "POST /api/stripe/create-portal-session β†’ authenticated",
+ "POST /api/stripe/preview-subscription-update β†’ authenticated",
+ "POST /api/stripe/update-subscription β†’ authenticated",
+ "POST /api/stripe/webhook β†’ public",
+ "POST /api/user/account-settings β†’ authenticated",
+ "POST /api/user/api-keys β†’ authenticated",
+ "POST /api/user/unsubscribe-marketing β†’ authenticated",
+ "POST /api/user/unsubscribe-marketing-oneclick β†’ public",
+ "PUT /api/admin/organizations/:organizationId/subscription-override β†’ system-admin",
+ "PUT /api/admin/sites/:siteId/move β†’ system-admin",
+ "PUT /api/organizations/:organizationId/members/:memberId/sites β†’ org members:manage [admin+]",
+ "PUT /api/organizations/:organizationId/teams/:teamId β†’ org teams:manage [admin+]",
+ "PUT /api/sites/:siteId/annotations/:annotationId β†’ site annotations:write [member+]",
+ "PUT /api/sites/:siteId/config β†’ site sites:configure [editor+]",
+ "PUT /api/sites/:siteId/dashboards/:dashboardId β†’ site dashboards:write [member+]",
+ "PUT /api/sites/:siteId/experiments/:experimentId β†’ site experiments:write [editor+]",
+ "PUT /api/sites/:siteId/feature-flags/:flagId β†’ site flags:write [editor+]",
+ "PUT /api/sites/:siteId/goals/:goalId β†’ site goals:write [member+]",
+ "PUT /api/sites/:siteId/move β†’ site sites:transfer [admin+]",
+ "PUT /api/sites/:siteId/segments/:segmentId β†’ site segments:write [member+]",
+ "PUT /api/sites/:siteId/users/:userId/traits β†’ site users:write [member+]",
+]
+`;
diff --git a/server/src/api/admin/adminMoveSite.ts b/server/src/api/admin/adminMoveSite.ts
index 8872c58ea..93ecabc62 100644
--- a/server/src/api/admin/adminMoveSite.ts
+++ b/server/src/api/admin/adminMoveSite.ts
@@ -47,7 +47,9 @@ export async function adminMoveSite(
return reply.status(404).send({ error: "Target organization not found" });
}
- await applySiteMove(siteId, site.organizationId, targetOrganizationId);
+ if (!(await applySiteMove(siteId, site.organizationId, targetOrganizationId))) {
+ return reply.status(409).send({ error: "The site moved while this request was in flight; reload and try again" });
+ }
return reply.status(200).send({ success: true, organizationId: targetOrganizationId });
} catch (error) {
diff --git a/server/src/api/admin/adminOrganizationManagement.test.ts b/server/src/api/admin/adminOrganizationManagement.test.ts
index cb1fedd31..6fde15e8f 100644
--- a/server/src/api/admin/adminOrganizationManagement.test.ts
+++ b/server/src/api/admin/adminOrganizationManagement.test.ts
@@ -58,6 +58,7 @@ CREATE TABLE "member_site_access" (
"id" serial PRIMARY KEY,
"member_id" text NOT NULL REFERENCES "member"("id") ON DELETE CASCADE,
"site_id" integer NOT NULL REFERENCES "sites"("site_id") ON DELETE CASCADE,
+ "role" text,
"created_at" timestamp NOT NULL DEFAULT now(),
"created_by" text
);
@@ -177,6 +178,22 @@ describe("admin member management", () => {
expect(mocks.invalidateSitesAccessCache).toHaveBeenCalledWith("u_member");
});
+ it("keeps the role a site grant carries when the admin panel saves the member", async () => {
+ await (pgClient as any).exec(`UPDATE member_site_access SET role = 'editor' WHERE member_id = 'm_member'`);
+ const reply = replyStub();
+ await updateAdminOrganizationMember(
+ requestStub({
+ params: { organizationId: "org_new", memberId: "m_member" },
+ body: { role: "viewer", hasRestrictedSiteAccess: true, siteIds: [2] },
+ }),
+ reply
+ );
+
+ expect(reply.statusCode).toBe(200);
+ const grants = await (pgClient as any).query(`SELECT site_id, role FROM member_site_access`);
+ expect(grants.rows).toEqual([{ site_id: 2, role: "editor" }]);
+ });
+
it("rejects grants for a site in another organization", async () => {
const reply = replyStub();
await updateAdminOrganizationMember(
diff --git a/server/src/api/admin/adminOrganizationManagement.ts b/server/src/api/admin/adminOrganizationManagement.ts
index 0bdb5f811..4ea2a5b7f 100644
--- a/server/src/api/admin/adminOrganizationManagement.ts
+++ b/server/src/api/admin/adminOrganizationManagement.ts
@@ -1,10 +1,11 @@
+import { isAdminRole, ORG_ROLES, SITE_GRANT_ROLES } from "@rybbit/shared";
import { and, count, desc, eq, ilike, ne, or } from "drizzle-orm";
import { FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { db } from "../../db/postgres/postgres.js";
import { member, memberSiteAccess, organization, sites, user } from "../../db/postgres/schema.js";
-import { siteIdsInOrganization } from "../../lib/access.js";
+import { grantRoleForRewrite, siteIdsInOrganization } from "../../lib/access.js";
import { invalidateSitesAccessCache } from "../../lib/auth-utils.js";
import { APPSUMO_TIER_LIMITS, getStripePrices } from "../../lib/const.js";
import { usageService } from "../../services/usageService.js";
@@ -200,12 +201,14 @@ export async function getAdminOrganizationMember(
const updateMemberSchema = z
.object({
- role: z.enum(["owner", "admin", "member"]),
+ role: z.enum(ORG_ROLES),
hasRestrictedSiteAccess: z.boolean(),
siteIds: z.array(z.number().int().positive()).max(500),
+ // Role on the granted sites; omit to keep what each grant already carries.
+ siteRole: z.enum(SITE_GRANT_ROLES).nullable().optional(),
})
.superRefine((value, ctx) => {
- if (value.role === "member" && value.hasRestrictedSiteAccess && value.siteIds.length === 0) {
+ if (!isAdminRole(value.role) && value.hasRestrictedSiteAccess && value.siteIds.length === 0) {
ctx.addIssue({ code: z.ZodIssueCode.custom, path: ["siteIds"], message: "Select at least one site" });
}
});
@@ -242,7 +245,7 @@ export async function updateAdminOrganizationMember(
return reply.status(400).send({ error: "An organization must have at least one owner" });
}
- const restricted = value.role === "member" && value.hasRestrictedSiteAccess;
+ const restricted = !isAdminRole(value.role) && value.hasRestrictedSiteAccess;
const requestedSiteIds = restricted ? [...new Set(value.siteIds)] : [];
const validSiteIds = new Set(await siteIdsInOrganization(requestedSiteIds, found.organizationId));
if (requestedSiteIds.some(siteId => !validSiteIds.has(siteId))) {
@@ -250,6 +253,8 @@ export async function updateAdminOrganizationMember(
}
await db.transaction(async tx => {
+ const roleFor = await grantRoleForRewrite(tx, found.memberId, value.siteRole);
+
await tx
.update(member)
.set({ role: value.role, hasRestrictedSiteAccess: restricted })
@@ -260,6 +265,7 @@ export async function updateAdminOrganizationMember(
requestedSiteIds.map(siteId => ({
memberId: found.memberId,
siteId,
+ role: roleFor(siteId),
createdBy: request.user?.id ?? null,
}))
);
diff --git a/server/src/api/analytics/annotations/annotationAccess.ts b/server/src/api/analytics/annotations/annotationAccess.ts
index eae87d18f..ed81b0349 100644
--- a/server/src/api/analytics/annotations/annotationAccess.ts
+++ b/server/src/api/analytics/annotations/annotationAccess.ts
@@ -2,7 +2,7 @@ import { and, eq, isNull, or, SQL } from "drizzle-orm";
import { FastifyRequest } from "fastify";
import { db } from "../../../db/postgres/postgres.js";
import { annotations, sites } from "../../../db/postgres/schema.js";
-import { getUserHasAdminAccessToSite } from "../../../lib/auth-utils.js";
+import { getUserHasOrgPermission, getUserHasSitePermission } from "../../../lib/auth-utils.js";
export type AnnotationRow = typeof annotations.$inferSelect;
@@ -37,16 +37,16 @@ export function annotationBelongsToSite(row: AnnotationRow, siteId: number, orga
}
/**
- * Admins and owners manage every annotation on their sites. Members may only
- * change what they created, and never organization-wide annotations.
+ * annotations:manage lets its holder change any annotation it covers: on the
+ * site for a site's annotations (so a per-site editor manages that site's),
+ * in the organization for organization-wide ones. Others may only change what
+ * they created, and never organization-wide annotations.
*/
-export async function canManageAnnotation(
- request: FastifyRequest,
- siteId: number,
- row: AnnotationRow
-): Promise<boolean> {
- if (await getUserHasAdminAccessToSite(request, siteId)) return true;
- if (row.siteId === null) return false;
+export async function canManageAnnotation(request: FastifyRequest, row: AnnotationRow): Promise<boolean> {
+ if (row.siteId === null) {
+ return getUserHasOrgPermission(request, row.organizationId, "annotations:manage");
+ }
+ if (await getUserHasSitePermission(request, row.siteId, "annotations:manage")) return true;
const userId = request.user?.id;
return Boolean(userId) && row.userId === userId;
}
diff --git a/server/src/api/analytics/annotations/createAnnotation.ts b/server/src/api/analytics/annotations/createAnnotation.ts
index 5124c12ee..e683a97ed 100644
--- a/server/src/api/analytics/annotations/createAnnotation.ts
+++ b/server/src/api/analytics/annotations/createAnnotation.ts
@@ -2,7 +2,7 @@ import { FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { db } from "../../../db/postgres/postgres.js";
import { annotations } from "../../../db/postgres/schema.js";
-import { getUserHasAdminAccessToSite } from "../../../lib/auth-utils.js";
+import { getUserHasOrgPermission } from "../../../lib/auth-utils.js";
import { getSiteOrganizationId, parseSiteId } from "./annotationAccess.js";
import { createAnnotationSchema } from "./annotationSchema.js";
@@ -26,9 +26,12 @@ export async function createAnnotation(
return reply.status(404).send({ error: "Site not found" });
}
- // Site access is enforced by the requireSiteAccess preHandler; any member
- // may create for the site, but organization-wide annotations are admin-only.
- if (input.scope === "organization" && !(await getUserHasAdminAccessToSite(request, siteId))) {
+ // The route guard requires annotations:write on the site; an annotation on
+ // every site of the organization needs annotations:manage in it.
+ if (
+ input.scope === "organization" &&
+ !(await getUserHasOrgPermission(request, organizationId, "annotations:manage"))
+ ) {
return reply.status(403).send({ error: "Only organization admins can create organization-wide annotations" });
}
diff --git a/server/src/api/analytics/annotations/deleteAnnotation.ts b/server/src/api/analytics/annotations/deleteAnnotation.ts
index ec92e429c..7d597654b 100644
--- a/server/src/api/analytics/annotations/deleteAnnotation.ts
+++ b/server/src/api/analytics/annotations/deleteAnnotation.ts
@@ -38,7 +38,7 @@ export async function deleteAnnotation(
return reply.status(404).send({ error: "Annotation not found" });
}
- if (!(await canManageAnnotation(request, siteId, existing))) {
+ if (!(await canManageAnnotation(request, existing))) {
return reply.status(403).send({ error: "You can only delete annotations you created" });
}
diff --git a/server/src/api/analytics/annotations/updateAnnotation.ts b/server/src/api/analytics/annotations/updateAnnotation.ts
index 92c965c03..e857f26f1 100644
--- a/server/src/api/analytics/annotations/updateAnnotation.ts
+++ b/server/src/api/analytics/annotations/updateAnnotation.ts
@@ -3,7 +3,7 @@ import { FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { db } from "../../../db/postgres/postgres.js";
import { annotations } from "../../../db/postgres/schema.js";
-import { getUserHasAdminAccessToSite } from "../../../lib/auth-utils.js";
+import { getUserHasOrgPermission } from "../../../lib/auth-utils.js";
import {
annotationBelongsToSite,
canManageAnnotation,
@@ -44,7 +44,7 @@ export async function updateAnnotation(
return reply.status(404).send({ error: "Annotation not found" });
}
- if (!(await canManageAnnotation(request, siteId, existing))) {
+ if (!(await canManageAnnotation(request, existing))) {
return reply.status(403).send({ error: "You can only edit annotations you created" });
}
@@ -59,7 +59,7 @@ export async function updateAnnotation(
if (input.scope !== undefined) {
const wantsOrgWide = input.scope === "organization";
if (wantsOrgWide !== (existing.siteId === null)) {
- if (!(await getUserHasAdminAccessToSite(request, siteId))) {
+ if (!(await getUserHasOrgPermission(request, organizationId, "annotations:manage"))) {
return reply.status(403).send({ error: "Only organization admins can change an annotation's scope" });
}
nextSiteId = wantsOrgWide ? null : siteId;
diff --git a/server/src/api/analytics/customQueryExecution.test.ts b/server/src/api/analytics/customQueryExecution.test.ts
index 84a6daf50..1ce9a5cbe 100644
--- a/server/src/api/analytics/customQueryExecution.test.ts
+++ b/server/src/api/analytics/customQueryExecution.test.ts
@@ -2,9 +2,9 @@ import { ClickHouseError } from "@clickhouse/client";
import Fastify, { FastifyInstance } from "fastify";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-const mocks = vi.hoisted(() => ({ query: vi.fn(), getSitesUserHasAccessTo: vi.fn() }));
+const mocks = vi.hoisted(() => ({ query: vi.fn(), getOrganizationSitesForCaller: vi.fn() }));
vi.mock("../../db/clickhouse/clickhouse.js", () => ({ clickhouseQuery: { query: mocks.query } }));
-vi.mock("../../lib/auth-utils.js", () => ({ getSitesUserHasAccessTo: mocks.getSitesUserHasAccessTo }));
+vi.mock("../../lib/auth-utils.js", () => ({ getOrganizationSitesForCaller: mocks.getOrganizationSitesForCaller }));
import { runCustomQuery } from "./runCustomQuery.js";
import { runDashboardCardQuery } from "./runDashboardCardQuery.js";
@@ -13,7 +13,7 @@ let app: FastifyInstance;
beforeEach(async () => {
vi.resetAllMocks();
- mocks.getSitesUserHasAccessTo.mockResolvedValue([{ siteId: 1, organizationId: "org-1" }]);
+ mocks.getOrganizationSitesForCaller.mockResolvedValue([{ siteId: 1, organizationId: "org-1" }]);
app = Fastify();
app.post<{ Params: { organizationId: string }; Body: unknown }>(
"/organizations/:organizationId/query",
diff --git a/server/src/api/analytics/dashboards/createDashboard.ts b/server/src/api/analytics/dashboards/createDashboard.ts
index 8fa0a0ac6..eeb8b8032 100644
--- a/server/src/api/analytics/dashboards/createDashboard.ts
+++ b/server/src/api/analytics/dashboards/createDashboard.ts
@@ -19,7 +19,7 @@ export async function createDashboard(
try {
const { name, config } = createDashboardSchema.parse(request.body);
- // Site access is enforced by the `authSite` (requireSiteAccess) preHandler.
+ // The route guard enforces dashboards:write on the site.
const result = await db
.insert(dashboards)
.values({
diff --git a/server/src/api/analytics/dashboards/deleteDashboard.ts b/server/src/api/analytics/dashboards/deleteDashboard.ts
index f1583a3ad..ae998c978 100644
--- a/server/src/api/analytics/dashboards/deleteDashboard.ts
+++ b/server/src/api/analytics/dashboards/deleteDashboard.ts
@@ -35,7 +35,7 @@ export async function deleteDashboard(
return reply.status(403).send({ error: "Dashboard does not belong to the specified site" });
}
- // Site access is enforced by the `authSite` (requireSiteAccess) preHandler.
+ // The route guard enforces dashboards:write on the site.
const result = await db
.delete(dashboards)
.where(eq(dashboards.dashboardId, dashboardId))
diff --git a/server/src/api/analytics/dashboards/updateDashboard.ts b/server/src/api/analytics/dashboards/updateDashboard.ts
index e718af441..104b27fec 100644
--- a/server/src/api/analytics/dashboards/updateDashboard.ts
+++ b/server/src/api/analytics/dashboards/updateDashboard.ts
@@ -36,7 +36,7 @@ export async function updateDashboard(
return reply.status(403).send({ error: "Dashboard does not belong to the specified site" });
}
- // Site access is enforced by the `authSite` (requireSiteAccess) preHandler.
+ // The route guard enforces dashboards:write on the site.
const result = await db
.update(dashboards)
.set({
diff --git a/server/src/api/analytics/generateCustomQuery.ts b/server/src/api/analytics/generateCustomQuery.ts
index 6efd9710b..cb57294e7 100644
--- a/server/src/api/analytics/generateCustomQuery.ts
+++ b/server/src/api/analytics/generateCustomQuery.ts
@@ -1,6 +1,6 @@
import { FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
-import { getSitesUserHasAccessTo } from "../../lib/auth-utils.js";
+import { getOrganizationSitesForCaller } from "../../lib/auth-utils.js";
import { OpenRouterError, callOpenRouterWithMetadata, getOpenRouterModel } from "../../lib/openrouter.js";
import { MAX_CUSTOM_QUERY_LENGTH, normalizeCustomQuery, validateScopedQuery } from "./utils/customQueryValidation.js";
import { EVENT_SCHEMA } from "./utils/eventSchema.js";
@@ -66,7 +66,9 @@ export async function generateCustomQuery(
return reply.status(400).send({ error: body.error.errors[0]?.message ?? "Invalid request body" });
}
- const userSites = await getSitesUserHasAccessTo(request);
+ // Read fresh: raw event access must not outlive a site move or a revoked
+ // grant by even the few seconds the per-worker cache holds.
+ const userSites = await getOrganizationSitesForCaller(request, request.params.organizationId);
const siteIds = userSites
.filter(site => site.organizationId === request.params.organizationId)
.map(site => site.siteId);
diff --git a/server/src/api/analytics/getSiteCards.test.ts b/server/src/api/analytics/getSiteCards.test.ts
index 1390296f5..7c697e1e8 100644
--- a/server/src/api/analytics/getSiteCards.test.ts
+++ b/server/src/api/analytics/getSiteCards.test.ts
@@ -3,7 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
checkApiKey: vi.fn(),
- getUserIsInOrg: vi.fn(),
+ getUserOrgRole: vi.fn(),
getSessionFromReq: vi.fn(),
getSitesUserHasAccessTo: vi.fn(),
siteIdsInOrganization: vi.fn(),
@@ -14,7 +14,7 @@ vi.mock("../../lib/access.js", () => ({ ...mocks }));
vi.mock("../../lib/siteConfig.js", () => ({ siteConfig: {} }));
vi.mock("../../db/clickhouse/clickhouse.js", () => ({ clickhouse: { query: mocks.query } }));
-import { requireOrgMember } from "../../lib/auth-middleware.js";
+import { requireOrgPermission } from "../../lib/auth-middleware.js";
import { getSiteCards, getSiteCardsLite } from "./getSiteCards.js";
let app: FastifyInstance;
@@ -25,7 +25,7 @@ beforeEach(async () => {
vi.resetAllMocks();
vi.spyOn(Date, "now").mockReturnValue(Date.parse("2026-09-20T20:41:33Z"));
mocks.checkApiKey.mockResolvedValue({ valid: false, role: null, statements: null });
- mocks.getUserIsInOrg.mockResolvedValue(true);
+ mocks.getUserOrgRole.mockResolvedValue("member");
mocks.getSessionFromReq.mockResolvedValue({ user: { id: "user-1" } });
mocks.getSitesUserHasAccessTo.mockResolvedValue(allIds.map(siteId => ({ siteId, organizationId: "org-1" })));
mocks.siteIdsInOrganization.mockImplementation(async ids => ids);
@@ -56,14 +56,12 @@ beforeEach(async () => {
app = Fastify();
app.post<{ Params: { organizationId: string }; Querystring: unknown; Body: unknown }>(
"/organizations/:organizationId/site-cards-lite",
- {
- preHandler: [requireOrgMember({ resource: "analytics", action: "read" })],
- },
+ { preHandler: [requireOrgPermission("analytics:read")] },
getSiteCardsLite
);
app.post<{ Params: { organizationId: string }; Querystring: unknown; Body: unknown }>(
"/organizations/:organizationId/site-cards",
- { preHandler: [requireOrgMember({ resource: "analytics", action: "read" })] },
+ { preHandler: [requireOrgPermission("analytics:read")] },
getSiteCards
);
await app.ready();
@@ -204,10 +202,15 @@ describe.each(["site-cards", "site-cards-lite"])("batched %s", endpoint => {
});
it("rejects unauthenticated callers and keys without analytics:read", async () => {
- mocks.getUserIsInOrg.mockResolvedValue(false);
+ mocks.getUserOrgRole.mockResolvedValue(null);
mocks.getSessionFromReq.mockResolvedValue(null);
- expect((await request()).statusCode).toBe(403);
- mocks.checkApiKey.mockResolvedValue({ valid: true, userId: "user-1", statements: { org: ["read"] } });
+ expect((await request()).statusCode).toBe(401);
+ mocks.checkApiKey.mockResolvedValue({
+ valid: true,
+ role: "member",
+ userId: "user-1",
+ statements: { org: ["read"] },
+ });
const denied = await request();
expect(denied.statusCode).toBe(403);
expect(denied.json().required).toBe("analytics:read");
@@ -215,9 +218,14 @@ describe.each(["site-cards", "site-cards-lite"])("batched %s", endpoint => {
});
it("supports organization-owned analytics keys without a session user", async () => {
- mocks.getUserIsInOrg.mockResolvedValue(false);
+ mocks.getUserOrgRole.mockResolvedValue(null);
mocks.getSessionFromReq.mockResolvedValue(null);
- mocks.checkApiKey.mockResolvedValue({ valid: true, organizationId: "org-1", statements: { analytics: ["read"] } });
+ mocks.checkApiKey.mockResolvedValue({
+ valid: true,
+ role: "admin",
+ organizationId: "org-1",
+ statements: { analytics: ["read"] },
+ });
expect((await request()).statusCode).toBe(200);
expect(mocks.getSitesUserHasAccessTo.mock.calls[0][0].apiKeyOrganizationId).toBe("org-1");
});
diff --git a/server/src/api/analytics/runCustomQuery.ts b/server/src/api/analytics/runCustomQuery.ts
index 7f21f2124..0bcb2e2f7 100644
--- a/server/src/api/analytics/runCustomQuery.ts
+++ b/server/src/api/analytics/runCustomQuery.ts
@@ -2,7 +2,7 @@ import { FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { clickhouseQuery } from "../../db/clickhouse/clickhouse.js";
import { QUERY_USER_LIMITS } from "../../db/clickhouse/queryLimits.js";
-import { getSitesUserHasAccessTo } from "../../lib/auth-utils.js";
+import { getOrganizationSitesForCaller } from "../../lib/auth-utils.js";
import {
MAX_CUSTOM_QUERY_LENGTH,
normalizeCustomQuery,
@@ -36,7 +36,9 @@ export async function runCustomQuery(
return reply.status(400).send({ error: validationError });
}
- const userSites = await getSitesUserHasAccessTo(request);
+ // Read fresh: raw event access must not outlive a site move or a revoked
+ // grant by even the few seconds the per-worker cache holds.
+ const userSites = await getOrganizationSitesForCaller(request, request.params.organizationId);
const accessibleSiteIds = userSites
.filter(site => site.organizationId === request.params.organizationId)
.map(site => site.siteId);
diff --git a/server/src/api/analytics/segments/createSegment.ts b/server/src/api/analytics/segments/createSegment.ts
index 2f83d1f95..22a0dc11d 100644
--- a/server/src/api/analytics/segments/createSegment.ts
+++ b/server/src/api/analytics/segments/createSegment.ts
@@ -22,15 +22,15 @@ export async function createSegment(
return reply.status(404).send({ error: "Site not found" });
}
- // Site access is enforced by the requireSiteAccess preHandler; the actor
- // is still resolved because org-wide scope is an admin decision.
- const actor = await resolveSegmentActor(request, siteId, organizationId);
+ // The route guard requires segments:write on the site; the actor is still
+ // resolved because org-wide scope needs segments:manage in the organization.
+ const actor = await resolveSegmentActor(request, siteId, organizationId, { forWrite: true });
if (!actor.hasSiteAccess) {
return reply.status(403).send({ error: "Forbidden" });
}
const orgWide = body.scope === "organization";
- if (orgWide && !actor.isAdmin) {
+ if (orgWide && !actor.canManage) {
return reply.status(403).send({ error: "Only organization admins can create organization-wide segments" });
}
diff --git a/server/src/api/analytics/segments/deleteSegment.ts b/server/src/api/analytics/segments/deleteSegment.ts
index eaf9d220d..69bcbec05 100644
--- a/server/src/api/analytics/segments/deleteSegment.ts
+++ b/server/src/api/analytics/segments/deleteSegment.ts
@@ -29,7 +29,7 @@ export async function deleteSegment(
return reply.status(404).send({ error: "Segment not found" });
}
- const actor = await resolveSegmentActor(request, siteId, loaded.organizationId);
+ const actor = await resolveSegmentActor(request, siteId, loaded.organizationId, { forWrite: true });
if (!canReadSegment(loaded.segment, actor)) {
return reply.status(404).send({ error: "Segment not found" });
}
diff --git a/server/src/api/analytics/segments/expandSegmentParam.test.ts b/server/src/api/analytics/segments/expandSegmentParam.test.ts
index db43ce95b..9eb59c79d 100644
--- a/server/src/api/analytics/segments/expandSegmentParam.test.ts
+++ b/server/src/api/analytics/segments/expandSegmentParam.test.ts
@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
const state = vi.hoisted(() => ({
loaded: null as null | { segment: any; organizationId: string },
- actor: { userId: null as string | null, hasSiteAccess: false, isAdmin: false },
+ actor: { userId: null as string | null, hasSiteAccess: false, canManage: false },
}));
vi.mock("./segmentAccess.js", async () => {
@@ -46,10 +46,17 @@ function run(
beforeEach(() => {
state.loaded = {
- segment: { segmentId: 7, siteId: 1, organizationId: "org_1", userId: "u", isPublic: false, filters: [mobile, germany] },
+ segment: {
+ segmentId: 7,
+ siteId: 1,
+ organizationId: "org_1",
+ userId: "u",
+ isPublic: false,
+ filters: [mobile, germany],
+ },
organizationId: "org_1",
};
- state.actor = { userId: "u", hasSiteAccess: true, isAdmin: false };
+ state.actor = { userId: "u", hasSiteAccess: true, canManage: false };
});
describe("mergeSegmentFilters", () => {
@@ -94,7 +101,7 @@ describe("expandSegmentParam", () => {
});
it("hides a private segment from a public-dashboard viewer but expands a public one", async () => {
- state.actor = { userId: null, hasSiteAccess: false, isAdmin: false };
+ state.actor = { userId: null, hasSiteAccess: false, canManage: false };
const privateResult = await run({ segment_id: "7" });
expect(privateResult.reply.statusCode).toBe(404);
@@ -110,7 +117,11 @@ describe("expandSegmentParam", () => {
expect(denied.reply.statusCode).toBe(403);
expect(denied.reply.payload).toEqual({ error: "Insufficient scope", required: "segments:read" });
- const allowed = await run({ segment_id: "7" }, { siteId: "1" }, { bearerAuth: true, bearerStatements: { segments: ["read"] } });
+ const allowed = await run(
+ { segment_id: "7" },
+ { siteId: "1" },
+ { bearerAuth: true, bearerStatements: { segments: ["read"] } }
+ );
expect(allowed.reply.status).not.toHaveBeenCalled();
const legacy = await run({ segment_id: "7" }, { siteId: "1" }, { bearerAuth: true, bearerStatements: null });
diff --git a/server/src/api/analytics/segments/segmentAccess.test.ts b/server/src/api/analytics/segments/segmentAccess.test.ts
index d8e444db9..0674def08 100644
--- a/server/src/api/analytics/segments/segmentAccess.test.ts
+++ b/server/src/api/analytics/segments/segmentAccess.test.ts
@@ -14,6 +14,8 @@ const state = vi.hoisted(() => ({
siteAccess: false,
membership: null as null | { role: string },
systemAdmin: false,
+ // A role on the site above the membership's, as a site grant or team gives.
+ siteRole: null as string | null,
writes: [] as Array<{ op: string; values?: unknown }>,
}));
@@ -37,7 +39,9 @@ vi.mock("../../../db/postgres/postgres.js", () => {
update: () => ({
set: (values: unknown) => {
state.writes.push({ op: "update", values });
- return { where: () => ({ returning: () => Promise.resolve([{ ...state.segments[0], ...(values as object) }]) }) };
+ return {
+ where: () => ({ returning: () => Promise.resolve([{ ...state.segments[0], ...(values as object) }]) }),
+ };
},
}),
delete: () => ({
@@ -50,14 +54,11 @@ vi.mock("../../../db/postgres/postgres.js", () => {
};
});
+// getUserOrgRole folds system-admin authority into the org role; mirror that.
vi.mock("../../../lib/auth-utils.js", () => ({
- getUserHasAccessToSite: async () => state.siteAccess,
- getIsUserAdmin: async () => state.systemAdmin,
-}));
-
-vi.mock("../../../lib/access.js", () => ({
- getOrgMembership: async () => state.membership,
- isOrgAdmin: (m: { role: string } | null) => m?.role === "admin" || m?.role === "owner",
+ getUserSiteRole: async () =>
+ state.siteAccess ? (state.systemAdmin ? "admin" : (state.siteRole ?? state.membership?.role ?? "member")) : null,
+ getUserOrgRole: async () => (state.systemAdmin ? "admin" : (state.membership?.role ?? null)),
}));
import { createSegment } from "./createSegment.js";
@@ -130,43 +131,46 @@ beforeEach(() => {
state.siteAccess = false;
state.membership = null;
state.systemAdmin = false;
+ state.siteRole = null;
state.writes = [];
});
describe("resolveSegmentActor", () => {
it("treats an organization API key as an admin of its own org only", async () => {
const own = await resolveSegmentActor(fakeRequest({ apiKeyOrganizationId: "org_1" }), 1, "org_1");
- expect(own).toEqual({ userId: null, hasSiteAccess: true, isAdmin: true });
+ expect(own).toEqual({ userId: null, hasSiteAccess: true, canManage: true, canManageSite: true });
const other = await resolveSegmentActor(fakeRequest({ apiKeyOrganizationId: "org_2" }), 1, "org_1");
- expect(other).toEqual({ userId: null, hasSiteAccess: false, isAdmin: false });
+ expect(other).toEqual({ userId: null, hasSiteAccess: false, canManage: false, canManageSite: false });
});
it("gives an anonymous viewer no access at all", async () => {
expect(await resolveSegmentActor(fakeRequest(), 1, "org_1")).toEqual({
userId: null,
hasSiteAccess: false,
- isAdmin: false,
+ canManage: false,
+ canManageSite: false,
});
});
it("marks org owners, org admins, and system admins as admins", async () => {
state.siteAccess = true;
state.membership = { role: "owner" };
- expect((await resolveSegmentActor(fakeRequest({ user: { id: "u" } }), 1, "org_1")).isAdmin).toBe(true);
+ expect((await resolveSegmentActor(fakeRequest({ user: { id: "u" } }), 1, "org_1")).canManage).toBe(true);
state.membership = { role: "member" };
- expect((await resolveSegmentActor(fakeRequest({ user: { id: "u" } }), 1, "org_1")).isAdmin).toBe(false);
+ expect((await resolveSegmentActor(fakeRequest({ user: { id: "u" } }), 1, "org_1")).canManage).toBe(false);
state.systemAdmin = true;
- expect((await resolveSegmentActor(fakeRequest({ user: { id: "u" } }), 1, "org_1")).isAdmin).toBe(true);
+ expect((await resolveSegmentActor(fakeRequest({ user: { id: "u" } }), 1, "org_1")).canManage).toBe(true);
});
});
describe("rule predicates", () => {
- const admin = { userId: "a", hasSiteAccess: true, isAdmin: true };
- const member = { userId: "member_1", hasSiteAccess: true, isAdmin: false };
- const viewer = { userId: null, hasSiteAccess: false, isAdmin: false };
+ const admin = { userId: "a", hasSiteAccess: true, canManage: true, canManageSite: true };
+ const member = { userId: "member_1", hasSiteAccess: true, canManage: false, canManageSite: false };
+ const siteEditor = { userId: "e", hasSiteAccess: true, canManage: false, canManageSite: true };
+ const viewer = { userId: null, hasSiteAccess: false, canManage: false, canManageSite: false };
it("reads: site access sees everything, viewers see public only", () => {
expect(canReadSegment({ isPublic: false }, member)).toBe(true);
@@ -175,11 +179,17 @@ describe("rule predicates", () => {
});
it("edits: admins edit anything, members only their own, viewers nothing", () => {
- expect(canEditSegment({ userId: "someone_else" }, admin)).toBe(true);
- expect(canEditSegment({ userId: "member_1" }, member)).toBe(true);
- expect(canEditSegment({ userId: "someone_else" }, member)).toBe(false);
- expect(canEditSegment({ userId: null }, member)).toBe(false);
- expect(canEditSegment({ userId: null }, viewer)).toBe(false);
+ expect(canEditSegment({ userId: "someone_else", siteId: 1 }, admin)).toBe(true);
+ expect(canEditSegment({ userId: "member_1", siteId: 1 }, member)).toBe(true);
+ expect(canEditSegment({ userId: "someone_else", siteId: 1 }, member)).toBe(false);
+ expect(canEditSegment({ userId: null, siteId: 1 }, member)).toBe(false);
+ expect(canEditSegment({ userId: null, siteId: 1 }, viewer)).toBe(false);
+ });
+
+ it("per-site editors edit the site's segments, but only org-level managers edit org-wide ones", () => {
+ expect(canEditSegment({ userId: "someone_else", siteId: 1 }, siteEditor)).toBe(true);
+ expect(canEditSegment({ userId: "e", siteId: null }, siteEditor)).toBe(false);
+ expect(canEditSegment({ userId: "someone_else", siteId: null }, admin)).toBe(true);
});
it("scopes a segment to its own site or its whole organization", () => {
diff --git a/server/src/api/analytics/segments/segmentAccess.ts b/server/src/api/analytics/segments/segmentAccess.ts
index b0884baaa..7b83fe659 100644
--- a/server/src/api/analytics/segments/segmentAccess.ts
+++ b/server/src/api/analytics/segments/segmentAccess.ts
@@ -1,10 +1,9 @@
-import type { Segment } from "@rybbit/shared";
+import { roleHasPermission, type Segment } from "@rybbit/shared";
import { and, eq, isNull, or } from "drizzle-orm";
import { FastifyRequest } from "fastify";
import { db } from "../../../db/postgres/postgres.js";
import { segments, sites } from "../../../db/postgres/schema.js";
-import { getOrgMembership, isOrgAdmin } from "../../../lib/access.js";
-import { getIsUserAdmin, getUserHasAccessToSite } from "../../../lib/auth-utils.js";
+import { getUserOrgRole, getUserSiteRole } from "../../../lib/auth-utils.js";
export type SegmentRow = typeof segments.$inferSelect;
@@ -17,11 +16,18 @@ export interface SegmentActor {
userId: string | null;
/** Session member of the site's org, a user API key with site access, or the org's own key. */
hasSiteAccess: boolean;
- /** Org admin/owner, system admin, or an organization-owned API key. */
- isAdmin: boolean;
+ /** Holds segments:manage in the organization: edits org-wide segments and creates them. */
+ canManage: boolean;
+ /** Holds segments:manage on this site: edits anyone's segments for it. */
+ canManageSite: boolean;
}
-export const NO_ACCESS_ACTOR: SegmentActor = { userId: null, hasSiteAccess: false, isAdmin: false };
+export const NO_ACCESS_ACTOR: SegmentActor = {
+ userId: null,
+ hasSiteAccess: false,
+ canManage: false,
+ canManageSite: false,
+};
export async function getSiteOrganizationId(siteId: number): Promise<string | null> {
const site = await db.query.sites.findFirst({
@@ -34,13 +40,15 @@ export async function getSiteOrganizationId(siteId: number): Promise<string | nu
export async function resolveSegmentActor(
request: FastifyRequest,
siteId: number,
- organizationId: string
+ organizationId: string,
+ // Writes decide on the role as it stands now, not this worker's cached copy.
+ { forWrite = false }: { forWrite?: boolean } = {}
): Promise<SegmentActor> {
// Organization-owned API keys carry org-admin authority over their own
// organization's sites and nothing else (see getSitesUserHasAccessTo).
if (!request.user?.id && request.apiKeyOrganizationId) {
const ownsSite = request.apiKeyOrganizationId === organizationId;
- return { userId: null, hasSiteAccess: ownsSite, isAdmin: ownsSite };
+ return { userId: null, hasSiteAccess: ownsSite, canManage: ownsSite, canManageSite: ownsSite };
}
const userId: string | null = request.user?.id ?? null;
@@ -48,13 +56,17 @@ export async function resolveSegmentActor(
return NO_ACCESS_ACTOR;
}
- const [hasSiteAccess, membership, isSystemAdmin] = await Promise.all([
- getUserHasAccessToSite(request, siteId),
- getOrgMembership(userId, organizationId),
- getIsUserAdmin(request),
+ const [siteRole, orgRole] = await Promise.all([
+ getUserSiteRole(request, siteId, { fresh: forWrite }),
+ getUserOrgRole(request, organizationId),
]);
- return { userId, hasSiteAccess, isAdmin: isSystemAdmin || isOrgAdmin(membership) };
+ return {
+ userId,
+ hasSiteAccess: siteRole !== null,
+ canManage: roleHasPermission(orgRole, "segments:manage"),
+ canManageSite: roleHasPermission(siteRole, "segments:manage"),
+ };
}
/** Anyone with site access reads every segment; everyone else reads public ones. */
@@ -62,9 +74,16 @@ export function canReadSegment(segment: Pick<SegmentRow, "isPublic">, actor: Seg
return actor.hasSiteAccess || segment.isPublic;
}
-/** Admins and owners edit any segment; members edit the ones they created. */
-export function canEditSegment(segment: Pick<SegmentRow, "userId">, actor: SegmentActor): boolean {
- if (actor.isAdmin) {
+/**
+ * segments:manage in the organization edits org-wide segments; on the site, it
+ * edits anyone's segments for that site. Otherwise people edit the site
+ * segments they created.
+ */
+export function canEditSegment(segment: Pick<SegmentRow, "userId" | "siteId">, actor: SegmentActor): boolean {
+ if (segment.siteId === null) {
+ return actor.canManage;
+ }
+ if (actor.canManageSite) {
return true;
}
return actor.hasSiteAccess && actor.userId !== null && segment.userId === actor.userId;
diff --git a/server/src/api/analytics/segments/updateSegment.ts b/server/src/api/analytics/segments/updateSegment.ts
index 8e10c0066..f0d7538b0 100644
--- a/server/src/api/analytics/segments/updateSegment.ts
+++ b/server/src/api/analytics/segments/updateSegment.ts
@@ -34,7 +34,7 @@ export async function updateSegment(
return reply.status(404).send({ error: "Segment not found" });
}
- const actor = await resolveSegmentActor(request, siteId, loaded.organizationId);
+ const actor = await resolveSegmentActor(request, siteId, loaded.organizationId, { forWrite: true });
if (!canReadSegment(loaded.segment, actor)) {
return reply.status(404).send({ error: "Segment not found" });
}
@@ -43,7 +43,7 @@ export async function updateSegment(
}
const becomesOrgWide = body.scope === "organization" && loaded.segment.siteId !== null;
- if (becomesOrgWide && !actor.isAdmin) {
+ if (becomesOrgWide && !actor.canManage) {
return reply.status(403).send({ error: "Only organization admins can share a segment with every site" });
}
diff --git a/server/src/api/as/activate.ts b/server/src/api/as/activate.ts
index 3868cc561..83cc30562 100644
--- a/server/src/api/as/activate.ts
+++ b/server/src/api/as/activate.ts
@@ -1,3 +1,4 @@
+import { roleHasPermission } from "@rybbit/shared";
import { eq, sql } from "drizzle-orm";
import { FastifyReply, FastifyRequest } from "fastify";
import { db } from "../../db/postgres/postgres.js";
@@ -107,7 +108,8 @@ export async function activateAppSumoLicense(
});
}
- // Verify user is a member of the organization
+ // A license changes the organization's plan: the same owner-only
+ // permission as every other billing action.
const member = await db.query.member.findFirst({
where: (member, { and, eq }) =>
and(eq(member.userId, session.user.id), eq(member.organizationId, organizationId)),
@@ -119,6 +121,12 @@ export async function activateAppSumoLicense(
});
}
+ if (!roleHasPermission(member.role, "billing:manage")) {
+ return reply.status(403).send({
+ error: "Only an organization owner can activate a license",
+ });
+ }
+
// Step 1: Exchange authorization code for access token
let tokenData;
try {
diff --git a/server/src/api/gsc/callback.ts b/server/src/api/gsc/callback.ts
index 5581d2c07..e473719b3 100644
--- a/server/src/api/gsc/callback.ts
+++ b/server/src/api/gsc/callback.ts
@@ -3,7 +3,7 @@ import { GSCCallbackRequest } from "./types.js";
import { gscConnections } from "../../db/postgres/schema.js";
import { eq } from "drizzle-orm";
import { getGSCProperties, verifyGSCState } from "./utils.js";
-import { getSessionFromReq, getUserHasAdminAccessToSite } from "../../lib/auth-utils.js";
+import { getSessionFromReq, getUserHasSitePermission } from "../../lib/auth-utils.js";
import { db } from "../../db/postgres/postgres.js";
interface TokenResponse {
@@ -53,7 +53,7 @@ export async function gscCallback(req: FastifyRequest<GSCCallbackRequest>, res:
// Verify the caller actually has admin access to the target site before
// writing OAuth tokens against it (prevents IDOR / connection hijack).
- const hasAccess = await getUserHasAdminAccessToSite(req, siteId);
+ const hasAccess = await getUserHasSitePermission(req, siteId, "gsc:write");
if (!hasAccess) {
return res.status(403).send({ error: "Access denied" });
}
diff --git a/server/src/api/gsc/connect.ts b/server/src/api/gsc/connect.ts
index 2975dde6a..3f8826787 100644
--- a/server/src/api/gsc/connect.ts
+++ b/server/src/api/gsc/connect.ts
@@ -1,6 +1,6 @@
import { FastifyReply, FastifyRequest } from "fastify";
import { ConnectGSCRequest } from "./types.js";
-import { getSessionFromReq, getUserHasAdminAccessToSite } from "../../lib/auth-utils.js";
+import { getSessionFromReq, getUserHasSitePermission } from "../../lib/auth-utils.js";
import { signGSCState } from "./utils.js";
/**
@@ -19,7 +19,7 @@ export async function connectGSC(req: FastifyRequest<ConnectGSCRequest>, res: Fa
// Require admin access to match the callback, which writes OAuth tokens and
// demands admin. A member who could start the flow would be stranded on a
// 403 after Google consent.
- const hasAccess = await getUserHasAdminAccessToSite(req, numericSiteId);
+ const hasAccess = await getUserHasSitePermission(req, numericSiteId, "gsc:write");
if (!hasAccess) {
return res.status(403).send({ error: "Access denied" });
}
diff --git a/server/src/api/gsc/disconnect.ts b/server/src/api/gsc/disconnect.ts
index 1eace3538..76191546f 100644
--- a/server/src/api/gsc/disconnect.ts
+++ b/server/src/api/gsc/disconnect.ts
@@ -2,7 +2,7 @@ import { FastifyReply, FastifyRequest } from "fastify";
import { DisconnectGSCRequest } from "./types.js";
import { gscConnections } from "../../db/postgres/schema.js";
import { eq } from "drizzle-orm";
-import { getUserHasAdminAccessToSite } from "../../lib/auth-utils.js";
+import { getUserHasSitePermission } from "../../lib/auth-utils.js";
import { db } from "../../db/postgres/postgres.js";
/**
@@ -20,7 +20,7 @@ export async function disconnectGSC(req: FastifyRequest<DisconnectGSCRequest>, r
// Managing (removing) a GSC connection is an admin action, consistent with
// connect/select-property.
- const hasAccess = await getUserHasAdminAccessToSite(req, numericSiteId);
+ const hasAccess = await getUserHasSitePermission(req, numericSiteId, "gsc:write");
if (!hasAccess) {
return res.status(403).send({ error: "Access denied" });
}
diff --git a/server/src/api/gsc/selectProperty.ts b/server/src/api/gsc/selectProperty.ts
index 31a7edec0..f2a504927 100644
--- a/server/src/api/gsc/selectProperty.ts
+++ b/server/src/api/gsc/selectProperty.ts
@@ -1,7 +1,7 @@
import { FastifyReply, FastifyRequest } from "fastify";
import { gscConnections } from "../../db/postgres/schema.js";
import { eq } from "drizzle-orm";
-import { getUserHasAdminAccessToSite } from "../../lib/auth-utils.js";
+import { getUserHasSitePermission } from "../../lib/auth-utils.js";
import { db } from "../../db/postgres/postgres.js";
import { getGSCProperties, refreshGSCToken } from "./utils.js";
@@ -32,7 +32,7 @@ export async function selectGSCProperty(req: FastifyRequest<SelectPropertyReques
}
// Managing the connection is an admin action, consistent with connect/disconnect.
- const hasAccess = await getUserHasAdminAccessToSite(req, numericSiteId);
+ const hasAccess = await getUserHasSitePermission(req, numericSiteId, "gsc:write");
if (!hasAccess) {
return res.status(403).send({ error: "Access denied" });
}
diff --git a/server/src/api/memberAccess/updateMemberSiteAccess.test.ts b/server/src/api/memberAccess/updateMemberSiteAccess.test.ts
index acb3247d1..4b6f001b6 100644
--- a/server/src/api/memberAccess/updateMemberSiteAccess.test.ts
+++ b/server/src/api/memberAccess/updateMemberSiteAccess.test.ts
@@ -49,6 +49,7 @@ CREATE TABLE "member_site_access" (
"id" serial PRIMARY KEY,
"member_id" text NOT NULL REFERENCES "member"("id") ON DELETE CASCADE,
"site_id" integer NOT NULL REFERENCES "sites"("site_id") ON DELETE CASCADE,
+ "role" text,
"created_at" timestamp NOT NULL DEFAULT now(),
"created_by" text REFERENCES "user"("id") ON DELETE SET NULL,
UNIQUE ("member_id", "site_id")
@@ -130,7 +131,7 @@ describe("updateMemberSiteAccess", () => {
expect(reply.body).toEqual({
memberId: "membership_member",
hasRestrictedSiteAccess: true,
- siteAccess: [{ siteId: 2, name: "One B", domain: "b.example.com" }],
+ siteAccess: [{ siteId: 2, role: null, name: "One B", domain: "b.example.com" }],
});
expect(await rows(`SELECT has_restricted_site_access FROM member WHERE id = 'membership_member'`)).toEqual([
{ has_restricted_site_access: true },
@@ -148,8 +149,8 @@ describe("updateMemberSiteAccess", () => {
await updateMemberSiteAccess(requestStub({ body: { hasRestrictedSiteAccess: true, siteIds: [1, 2] } }), reply);
expect(reply.body.siteAccess).toEqual([
- { siteId: 1, name: "One A", domain: "a.example.com" },
- { siteId: 2, name: "One B", domain: "b.example.com" },
+ { siteId: 1, role: null, name: "One A", domain: "a.example.com" },
+ { siteId: 2, role: null, name: "One B", domain: "b.example.com" },
]);
expect(await rows(`SELECT site_id FROM member_site_access ORDER BY site_id`)).toEqual([
{ site_id: 1 },
@@ -157,6 +158,58 @@ describe("updateMemberSiteAccess", () => {
]);
});
+ it("stores the role the grants carry", async () => {
+ const reply = replyStub();
+
+ await updateMemberSiteAccess(
+ requestStub({ body: { hasRestrictedSiteAccess: true, siteIds: [2], siteRole: "editor" } }),
+ reply
+ );
+
+ expect(reply.statusCode).toBe(200);
+ expect(reply.body.siteAccess).toEqual([{ siteId: 2, role: "editor", name: "One B", domain: "b.example.com" }]);
+ expect(await rows(`SELECT site_id, role FROM member_site_access`)).toEqual([{ site_id: 2, role: "editor" }]);
+ });
+
+ it("keeps the role the grants carry when the request doesn't mention it", async () => {
+ await (pgClient as any).exec(`UPDATE member_site_access SET role = 'editor' WHERE member_id = 'membership_member'`);
+ const reply = replyStub();
+
+ // Site 1 stays, site 2 is new: both carry the member's existing site role.
+ await updateMemberSiteAccess(requestStub({ body: { hasRestrictedSiteAccess: true, siteIds: [1, 2] } }), reply);
+
+ expect(reply.statusCode).toBe(200);
+ expect(await rows(`SELECT site_id, role FROM member_site_access ORDER BY site_id`)).toEqual([
+ { site_id: 1, role: "editor" },
+ { site_id: 2, role: "editor" },
+ ]);
+ });
+
+ it("clears the site role when the request sends null", async () => {
+ await (pgClient as any).exec(`UPDATE member_site_access SET role = 'editor' WHERE member_id = 'membership_member'`);
+ const reply = replyStub();
+
+ await updateMemberSiteAccess(
+ requestStub({ body: { hasRestrictedSiteAccess: true, siteIds: [1], siteRole: null } }),
+ reply
+ );
+
+ expect(await rows(`SELECT site_id, role FROM member_site_access`)).toEqual([{ site_id: 1, role: null }]);
+ });
+
+ it("refuses a grant role above editor", async () => {
+ const reply = replyStub();
+
+ await updateMemberSiteAccess(
+ requestStub({ body: { hasRestrictedSiteAccess: true, siteIds: [2], siteRole: "admin" } }),
+ reply
+ );
+
+ expect(reply.statusCode).toBe(400);
+ // The existing grant is untouched.
+ expect(await rows(`SELECT site_id, role FROM member_site_access`)).toEqual([{ site_id: 1, role: null }]);
+ });
+
it("can restrict a member to no sites", async () => {
const reply = replyStub();
@@ -232,6 +285,21 @@ describe("updateMemberSiteAccess", () => {
expect(mocks.invalidateSitesAccessCache).not.toHaveBeenCalled();
});
+ it("clears a restriction left over from before a promotion", async () => {
+ await (pgClient as any).exec(`
+ UPDATE member SET role = 'admin' WHERE id = 'membership_member';
+ `);
+ const reply = replyStub();
+
+ await updateMemberSiteAccess(requestStub({ body: { hasRestrictedSiteAccess: false, siteIds: [] } }), reply);
+
+ expect(reply.statusCode).toBe(200);
+ expect(await rows(`SELECT has_restricted_site_access FROM member WHERE id = 'membership_member'`)).toEqual([
+ { has_restricted_site_access: false },
+ ]);
+ expect(await rows(`SELECT * FROM member_site_access`)).toEqual([]);
+ });
+
it("rejects foreign and nonexistent site IDs without changing existing access", async () => {
const reply = replyStub();
await (pgClient as any).exec(`UPDATE member SET has_restricted_site_access = false WHERE id = 'membership_member'`);
diff --git a/server/src/api/memberAccess/updateMemberSiteAccess.ts b/server/src/api/memberAccess/updateMemberSiteAccess.ts
index 12b59f829..730aeef55 100644
--- a/server/src/api/memberAccess/updateMemberSiteAccess.ts
+++ b/server/src/api/memberAccess/updateMemberSiteAccess.ts
@@ -1,9 +1,10 @@
+import { isAdminRole, isSiteGrantRole, SITE_GRANT_ROLES } from "@rybbit/shared";
import { and, eq } from "drizzle-orm";
import { FastifyReply, FastifyRequest } from "fastify";
import { db } from "../../db/postgres/postgres.js";
import { member, memberSiteAccess, sites, user } from "../../db/postgres/schema.js";
-import { siteIdsInOrganization } from "../../lib/access.js";
+import { grantRoleForRewrite, siteIdsInOrganization } from "../../lib/access.js";
import { invalidateSitesAccessCache } from "../../lib/auth-utils.js";
interface UpdateMemberSiteAccessParams {
@@ -14,6 +15,8 @@ interface UpdateMemberSiteAccessParams {
interface UpdateMemberSiteAccessBody {
hasRestrictedSiteAccess: boolean;
siteIds: number[];
+ /** Role on the granted sites (editor, member or viewer); null for none; omit to keep what the grants carry. */
+ siteRole?: string | null;
}
export async function updateMemberSiteAccess(
@@ -25,8 +28,13 @@ export async function updateMemberSiteAccess(
) {
const { organizationId, memberId } = request.params;
const { hasRestrictedSiteAccess, siteIds } = request.body;
+ const requestedSiteRole = request.body.siteRole;
const currentUserId = request.user?.id;
+ if (requestedSiteRole != null && !isSiteGrantRole(requestedSiteRole)) {
+ return reply.status(400).send({ error: `siteRole must be one of: ${SITE_GRANT_ROLES.join(", ")}` });
+ }
+
try {
// Get the member record
const memberRecord = await db
@@ -46,8 +54,9 @@ export async function updateMemberSiteAccess(
const memberData = memberRecord[0];
- // Don't allow restricting admin or owner roles
- if (memberData.role === "admin" || memberData.role === "owner") {
+ // Admins and owners reach every site: they can't be restricted, but a
+ // restriction left over from before a promotion can be cleared.
+ if (isAdminRole(memberData.role) && hasRestrictedSiteAccess) {
return reply.status(400).send({
error: "Cannot restrict site access for admin or owner roles",
});
@@ -66,6 +75,7 @@ export async function updateMemberSiteAccess(
}
await db.transaction(async tx => {
+ const roleFor = await grantRoleForRewrite(tx, memberId, requestedSiteRole);
await tx.update(member).set({ hasRestrictedSiteAccess }).where(eq(member.id, memberId));
await tx.delete(memberSiteAccess).where(eq(memberSiteAccess.memberId, memberId));
@@ -74,6 +84,7 @@ export async function updateMemberSiteAccess(
siteIds.map(siteId => ({
memberId,
siteId,
+ role: roleFor(siteId),
createdBy: currentUserId || null,
}))
);
@@ -87,6 +98,7 @@ export async function updateMemberSiteAccess(
const updatedSiteAccess = await db
.select({
siteId: memberSiteAccess.siteId,
+ role: memberSiteAccess.role,
siteName: sites.name,
siteDomain: sites.domain,
})
@@ -99,6 +111,7 @@ export async function updateMemberSiteAccess(
hasRestrictedSiteAccess,
siteAccess: updatedSiteAccess.map(record => ({
siteId: record.siteId,
+ role: record.role,
name: record.siteName,
domain: record.siteDomain,
})),
diff --git a/server/src/api/routes.test.ts b/server/src/api/routes.test.ts
new file mode 100644
index 000000000..7b62a64c1
--- /dev/null
+++ b/server/src/api/routes.test.ts
@@ -0,0 +1,73 @@
+import Fastify, { type RouteOptions } from "fastify";
+import { describe, expect, it, vi } from "vitest";
+
+// Cloud-only SDK clients are constructed at import time; they need a key to
+// construct, never to register a route.
+vi.hoisted(() => {
+ process.env.RESEND_API_KEY ||= "re_test";
+ process.env.STRIPE_SECRET_KEY ||= "sk_test";
+});
+// Load the real route table with the infrastructure clients stubbed: no
+// database, cache or auth provider is contacted β€” the test only registers
+// routes and reads what each one declares.
+vi.mock("../db/postgres/postgres.js", () => ({ db: {}, sql: {} }));
+vi.mock("../db/redis/redis.js", () => ({
+ dashboardCacheRedis: { status: "end", eval: vi.fn() },
+ apiRateLimitRedis: { status: "end", eval: vi.fn() },
+}));
+vi.mock("../lib/auth.js", () => ({ auth: { api: {} } }));
+
+vi.mock("../lib/const.js", async importOriginal => ({
+ ...(await importOriginal<typeof import("../lib/const.js")>()),
+ // Register the cloud-only billing routes too.
+ IS_CLOUD: true,
+}));
+
+import { PERMISSIONS } from "@rybbit/shared";
+import type { RouteAccess } from "../lib/auth-middleware.js";
+import { apiRoutes } from "./routes.js";
+
+async function collectRoutes() {
+ const routes: { method: string; url: string; access: RouteAccess | undefined }[] = [];
+ const app = Fastify();
+ app.addHook("onRoute", (route: RouteOptions) => {
+ for (const method of [route.method].flat()) {
+ if (method === "HEAD") continue;
+ routes.push({ method, url: route.url, access: route.config?.access });
+ }
+ });
+ await app.register(apiRoutes, { prefix: "/api" });
+ await app.ready();
+ await app.close();
+ return routes;
+}
+
+const describeAccess = (access: RouteAccess | undefined) => {
+ if (!access) return "UNDECLARED";
+ if (typeof access === "string") return access;
+ const minRole = PERMISSIONS[access.permission].minRole;
+ if (access.level === "site") {
+ return `site ${access.permission} [${minRole}+]${access.allowPublic ? " (or public)" : ""}`;
+ }
+ return `org ${access.permission} [${minRole}+]`;
+};
+
+describe("API route table", () => {
+ it("declares who may call every route", async () => {
+ const routes = await collectRoutes();
+
+ expect(routes.length).toBeGreaterThan(100);
+ expect(routes.filter(route => !route.access)).toEqual([]);
+ });
+
+ // The whole access matrix in one reviewable place: any change to who may
+ // call an endpoint shows up as a diff here.
+ it("pins the access each route requires", async () => {
+ const routes = await collectRoutes();
+ const table = routes
+ .map(route => `${route.method.padEnd(6)} ${route.url} β†’ ${describeAccess(route.access)}`)
+ .sort();
+
+ expect(table).toMatchSnapshot();
+ });
+});
diff --git a/server/src/api/routes.ts b/server/src/api/routes.ts
new file mode 100644
index 000000000..64138b206
--- /dev/null
+++ b/server/src/api/routes.ts
@@ -0,0 +1,561 @@
+import { createHash } from "node:crypto";
+import type { Permission } from "@rybbit/shared";
+import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
+import {
+ adminMoveSite,
+ collectTelemetry,
+ deleteAdminOrganizationMember,
+ getAdminOrganizationMember,
+ getAdminOrganizationOptions,
+ getAdminOrganizations,
+ getAdminSubscriptionPlans,
+ getAdminServiceEventCount,
+ getAdminSites,
+ getClickhouseStats,
+ getClickhouseQueryLog,
+ updateAdminOrganizationMember,
+ updateAdminSubscriptionOverride,
+} from "./admin/index.js";
+import {
+ createAnnotation,
+ createDashboard,
+ createSegment,
+ createFunnel,
+ createGoal,
+ deleteAnnotation,
+ deleteDashboard,
+ deleteSegment,
+ deleteFunnel,
+ deleteGoal,
+ deleteUser,
+ generatePdfReport,
+ getAnnotations,
+ getDashboard,
+ getDashboards,
+ getSegment,
+ getSegments,
+ getBotAiSummary,
+ getBotDimension,
+ getBotOverview,
+ getBotTimeSeries,
+ getErrorBucketed,
+ getErrorEvents,
+ getErrorNames,
+ generateCustomQuery,
+ getEventBucketed,
+ getEventNames,
+ getAutocaptureEvents,
+ getAutocaptureValues,
+ getEventProperties,
+ getEvents,
+ getFunnel,
+ getFunnelStepSessions,
+ getFunnels,
+ getGoalSessions,
+ getGoalTimeSeries,
+ getGoals,
+ getJourneys,
+ getLiveUsercount,
+ getMetric,
+ getMetricLite,
+ getOrgEventCount,
+ getOutboundLinks,
+ getOverview,
+ getOverviewBucketed,
+ getOverviewBucketedLite,
+ getOverviewLite,
+ getSiteCardsLite,
+ getSiteCards,
+ getPageTitles,
+ getPerformanceByDimension,
+ getPerformanceOverview,
+ getPerformanceTimeSeries,
+ getRetention,
+ getSession,
+ getSessionLocations,
+ getSessions,
+ getSiteEventCount,
+ getUserInfo,
+ getUserSessionCount,
+ getUserTraitKeys,
+ getUserTraitValueUsers,
+ getUserTraitValues,
+ getUsers,
+ identifyUser,
+ runCustomQuery,
+ runDashboardCardQuery,
+ updateAnnotation,
+ updateDashboard,
+ updateSegment,
+ expandSegmentParam,
+ updateGoal,
+ updateUserTraits,
+} from "./analytics/index.js";
+import { getConfig, getVersion } from "./getConfig.js";
+import {
+ createExperiment,
+ deleteExperiment,
+ getExperimentResults,
+ getExperiments,
+ updateExperiment,
+} from "./experiments/index.js";
+import {
+ createFeatureFlag,
+ deleteFeatureFlag,
+ evaluateFeatureFlags,
+ evaluateServerFeatureFlags,
+ getFeatureFlags,
+ updateFeatureFlag,
+} from "./featureFlags/index.js";
+import { connectGSC, disconnectGSC, getGSCData, getGSCStatus, gscCallback, selectGSCProperty } from "./gsc/index.js";
+import { updateMemberSiteAccess } from "./memberAccess/index.js";
+import { listTeams, createTeam, updateTeam, deleteTeam } from "./teams/index.js";
+import {
+ deleteSessionReplay,
+ getSessionReplayEvents,
+ getSessionReplays,
+ recordSessionReplay,
+} from "./sessionReplay/index.js";
+import {
+ addSite,
+ batchImportEvents,
+ claimSite,
+ createUnclaimedSite,
+ createSiteImport,
+ deleteSite,
+ deleteSiteImport,
+ getEmbedStats,
+ getSite,
+ getSiteExcludedCountries,
+ getSiteExcludedHostnames,
+ getSiteExcludedIPs,
+ getSiteExcludedPaths,
+ getSiteExcludedUserAgents,
+ getSiteExcludedASNs,
+ getSiteExcludedQueryParams,
+ getSiteHasData,
+ checkInstall,
+ getSiteImports,
+ getSiteIsPublic,
+ getSiteUsage,
+ getSitePrivateLinkConfig,
+ getSitesFromOrg,
+ getTrackingConfig,
+ moveSite,
+ updateSiteConfig,
+ updateSitePrivateLinkConfig,
+} from "./sites/index.js";
+import {
+ createCheckoutSession,
+ createPortalSession,
+ getInvoices,
+ getSubscription,
+ handleWebhook,
+ previewSubscriptionUpdate,
+ submitCancellationFeedback,
+ updateSubscription,
+} from "./stripe/index.js";
+import {
+ addUserToOrganization,
+ createOrgApiKey,
+ createUserApiKey,
+ createUserInOrganization,
+ getMyOrganizations,
+ getOrgApiUsage,
+ getUserOrganizations,
+ listOrganizationMembers,
+ oneClickUnsubscribeMarketing,
+ unsubscribeMarketing,
+ updateAccountSettings,
+} from "./user/index.js";
+import { createDashboardCache } from "./analytics/utils/dashboardCache.js";
+import { validateHttpTimeParams } from "./analytics/utils/query-validation.js";
+import { handleAppSumoWebhook, activateAppSumoLicense } from "./as/index.js";
+import { unclaimedSiteRouteOptions } from "./sites/createUnclaimedSite.js";
+import {
+ acceptSiteTransfer,
+ cancelSiteTransfer,
+ createSiteTransfer,
+ declineSiteTransfer,
+ getIncomingSiteTransfer,
+ getSiteTransfer,
+} from "./sites/siteTransfers.js";
+import { dashboardCacheRedis } from "../db/redis/redis.js";
+import {
+ assertRouteAccessDeclared,
+ requireAdmin,
+ requireAuth,
+ requireOrgPermission,
+ requireSitePermission,
+ resolveSiteId,
+ type RouteAccess,
+ type RouteScope,
+} from "../lib/auth-middleware.js";
+import { IS_CLOUD } from "../lib/const.js";
+import { mcpRoutes } from "../mcp/index.js";
+
+// Reject requests whose shared time query params are present but invalid.
+// Historically they were silently dropped, so endpoints ran over all time and
+// returned wrong data with a 200. Absent params (all-time mode) stay valid.
+const validateTimeParams = async (request: FastifyRequest, reply: FastifyReply) => {
+ const error = validateHttpTimeParams(request.query);
+ if (error) {
+ return reply.status(400).send({ error });
+ }
+};
+
+// Route access. Every /api route declares who may call it (config.access) and
+// the onRoute check below refuses to boot a route that doesn't, so a new
+// endpoint cannot ship without an explicit decision.
+//
+// Site and organization routes name a Permission (@rybbit/shared
+// permissions.ts): the caller's role on that site or organization must hold it,
+// and a bearer credential (API key, OAuth token) must also carry the
+// permission's scope. Cookie sessions are never scope-limited.
+//
+// Cast as any to work around Fastify's type inference limitations with preHandler
+//
+// validateTimeParams is on every chain rather than only the ones that currently
+// host a time-taking route: absent params always pass, and the two chains that
+// went without it were how /org-event-count and /admin/service-event-count came
+// to answer a malformed date with all-time data and a 200.
+// expandSegmentParam turns a `segment_id` query param into `filters` after the
+// access guard has run, so every analytics endpoint accepts a saved segment
+// with no per-endpoint change. It is a no-op when the param is absent.
+const site = (permission: Permission, options: { allowPublic?: boolean; validateTime?: boolean } = {}) => ({
+ preHandler: [
+ resolveSiteId,
+ requireSitePermission(permission, { allowPublic: options.allowPublic }),
+ ...(options.validateTime === false ? [] : [validateTimeParams]),
+ expandSegmentParam,
+ ] as any,
+ config: { access: { level: "site", permission, allowPublic: !!options.allowPublic } as RouteAccess },
+});
+const publicSite = (permission: Permission) => site(permission, { allowPublic: true });
+const org = (permission: Permission) => ({
+ preHandler: [requireOrgPermission(permission), validateTimeParams] as any,
+ config: { access: { level: "org", permission } as RouteAccess },
+});
+// User-level surfaces with no site or organization in the path.
+const authenticated = (scope: RouteScope) => ({
+ preHandler: [requireAuth(scope), validateTimeParams] as any,
+ config: { access: "authenticated" as RouteAccess },
+});
+const systemAdmin = {
+ preHandler: [requireAdmin, validateTimeParams] as any,
+ config: { access: "system-admin" as RouteAccess },
+};
+// No guard: tracking, webhooks, signed links, and handlers that authenticate
+// the caller themselves.
+const publicRoute = { config: { access: "public" as RouteAccess } };
+
+const dashboardCacheSeconds = Number(process.env.DASHBOARD_CACHE_TTL_SECONDS ?? 30);
+const cacheDashboard = createDashboardCache({
+ redis: dashboardCacheRedis,
+ namespace: createHash("sha256")
+ .update(JSON.stringify([process.env.CLICKHOUSE_HOST, process.env.CLICKHOUSE_DB]))
+ .digest("hex"),
+ ttlMs: (Number.isFinite(dashboardCacheSeconds) ? Math.max(0, Math.min(30, dashboardCacheSeconds)) : 30) * 1000,
+});
+
+// Reused chains
+const publicAnalyticsRead = publicSite("analytics:read");
+const cachedAnalyticsRead = cacheDashboard(publicAnalyticsRead);
+const publicSessionsRead = publicSite("sessions:read");
+const publicEventsRead = publicSite("events:read");
+const cachedEventsRead = cacheDashboard(publicEventsRead);
+const publicUsersRead = publicSite("users:read");
+const publicFunnelsRead = publicSite("funnels:read");
+const publicGoalsRead = publicSite("goals:read");
+const publicSitesRead = publicSite("sites:read");
+const publicReplayRead = publicSite("replay:read");
+const publicGscRead = publicSite("gsc:read");
+// Annotations validate their own optional start/end bounds (either may stand
+// alone), so the shared time validator is left off this chain.
+const publicAnnotationsRead = site("annotations:read", { allowPublic: true, validateTime: false });
+const publicSegmentsRead = publicSite("segments:read");
+
+// User-authored SQL fans out real ClickHouse work per call (a dashboard runs
+// one query per card), and /generate spends OpenRouter credit. Cap per user.
+const customQueryRateLimit = { max: 60, timeWindow: "1 minute" };
+const generateQueryRateLimit = { max: 20, timeWindow: "1 minute" };
+const withRateLimit = <T extends { preHandler: unknown; config?: object }>(
+ opts: T,
+ limit: { max: number; timeWindow: string }
+) => ({
+ ...opts,
+ config: { ...opts.config, rateLimit: limit },
+});
+
+// Domain-specific route plugins
+async function analyticsRoutes(fastify: FastifyInstance) {
+ // WEB & PRODUCT ANALYTICS
+
+ // This endpoint gets called a lot so we don't want to log it
+ fastify.get("/sites/:siteId/live-user-count", { logLevel: "silent", ...publicAnalyticsRead }, getLiveUsercount);
+ fastify.get("/sites/:siteId/overview", cachedAnalyticsRead, getOverview);
+ fastify.get("/sites/:siteId/overview/time-series", cachedAnalyticsRead, getOverviewBucketed);
+ fastify.get("/sites/:siteId/overview-lite", cachedAnalyticsRead, getOverviewLite);
+ fastify.get("/sites/:siteId/overview-bucketed-lite", cachedAnalyticsRead, getOverviewBucketedLite);
+ fastify.get("/sites/:siteId/metric-lite", cachedAnalyticsRead, getMetricLite);
+ fastify.get("/sites/:siteId/metric", cachedAnalyticsRead, getMetric);
+ fastify.get("/sites/:siteId/page-titles", cachedAnalyticsRead, getPageTitles);
+ fastify.get("/sites/:siteId/errors/names", publicAnalyticsRead, getErrorNames);
+ fastify.get("/sites/:siteId/errors/events", publicAnalyticsRead, getErrorEvents);
+ fastify.get("/sites/:siteId/errors/time-series", publicAnalyticsRead, getErrorBucketed);
+ fastify.get("/sites/:siteId/retention", publicAnalyticsRead, getRetention);
+ fastify.get("/sites/:siteId/has-data", publicSitesRead, getSiteHasData);
+ fastify.get("/sites/:siteId/is-public", publicSitesRead, getSiteIsPublic);
+ fastify.get("/sites/:siteId/sessions", publicSessionsRead, getSessions);
+ fastify.get("/sites/:siteId/sessions/:sessionId", publicSessionsRead, getSession);
+ fastify.get("/sites/:siteId/events", publicEventsRead, getEvents);
+ fastify.get("/sites/:siteId/events/time-series", publicEventsRead, getEventBucketed);
+ fastify.get("/sites/:siteId/events/count", publicEventsRead, getSiteEventCount);
+ fastify.get("/sites/:siteId/users", publicUsersRead, getUsers);
+
+ fastify.get("/sites/:siteId/users/session-count", publicUsersRead, getUserSessionCount);
+ fastify.get("/sites/:siteId/users/:userId", publicUsersRead, getUserInfo);
+ fastify.post("/sites/:siteId/users/identify", site("users:write"), identifyUser);
+ fastify.put("/sites/:siteId/users/:userId/traits", site("users:write"), updateUserTraits);
+ fastify.delete("/sites/:siteId/users/:userId", site("users:delete"), deleteUser);
+ fastify.get("/sites/:siteId/user-traits/keys", publicUsersRead, getUserTraitKeys);
+ fastify.get("/sites/:siteId/user-traits/values", publicUsersRead, getUserTraitValues);
+ fastify.get("/sites/:siteId/user-traits/users", publicUsersRead, getUserTraitValueUsers);
+ fastify.get("/sites/:siteId/sessions/locations", publicSessionsRead, getSessionLocations);
+ fastify.get("/sites/:siteId/funnels", publicFunnelsRead, getFunnels);
+ fastify.get("/sites/:siteId/journeys", publicAnalyticsRead, getJourneys);
+ fastify.post("/sites/:siteId/funnels/analyze", publicFunnelsRead, getFunnel);
+ fastify.post("/sites/:siteId/funnels/:stepNumber/sessions", publicFunnelsRead, getFunnelStepSessions);
+ fastify.post("/sites/:siteId/funnels", site("funnels:write"), createFunnel);
+ fastify.delete("/sites/:siteId/funnels/:funnelId", site("funnels:write"), deleteFunnel);
+ fastify.get("/sites/:siteId/goals", publicGoalsRead, getGoals);
+ fastify.get("/sites/:siteId/goals/time-series", publicGoalsRead, getGoalTimeSeries);
+ fastify.get("/sites/:siteId/goals/:goalId/sessions", publicGoalsRead, getGoalSessions);
+ fastify.post("/sites/:siteId/goals", site("goals:write"), createGoal);
+ fastify.delete("/sites/:siteId/goals/:goalId", site("goals:write"), deleteGoal);
+ fastify.put("/sites/:siteId/goals/:goalId", site("goals:write"), updateGoal);
+ // Timeline annotations. Read is public-guarded so public dashboards and
+ // private links get the annotations marked public; writes need site access.
+ fastify.get("/sites/:siteId/annotations", publicAnnotationsRead, getAnnotations);
+ fastify.post("/sites/:siteId/annotations", site("annotations:write"), createAnnotation);
+ fastify.put("/sites/:siteId/annotations/:annotationId", site("annotations:write"), updateAnnotation);
+ fastify.delete("/sites/:siteId/annotations/:annotationId", site("annotations:write"), deleteAnnotation);
+ fastify.get("/sites/:siteId/dashboards", site("dashboards:read"), getDashboards);
+ fastify.get("/sites/:siteId/dashboards/:dashboardId", site("dashboards:read"), getDashboard);
+ fastify.post("/sites/:siteId/dashboards", site("dashboards:write"), createDashboard);
+ fastify.put("/sites/:siteId/dashboards/:dashboardId", site("dashboards:write"), updateDashboard);
+ fastify.delete("/sites/:siteId/dashboards/:dashboardId", site("dashboards:write"), deleteDashboard);
+
+ // Saved segments. Reads allow public/private-link viewers (they only see
+ // public segments); writes need site access and are further gated per row.
+ fastify.get("/sites/:siteId/segments", publicSegmentsRead, getSegments);
+ fastify.get("/sites/:siteId/segments/:segmentId", publicSegmentsRead, getSegment);
+ fastify.post("/sites/:siteId/segments", site("segments:write"), createSegment);
+ fastify.put("/sites/:siteId/segments/:segmentId", site("segments:write"), updateSegment);
+ fastify.delete("/sites/:siteId/segments/:segmentId", site("segments:write"), deleteSegment);
+ fastify.post(
+ "/sites/:siteId/dashboards/run-card",
+ withRateLimit(site("dashboards:read"), customQueryRateLimit),
+ runDashboardCardQuery
+ );
+ fastify.get("/sites/:siteId/feature-flags", site("flags:read"), getFeatureFlags);
+ fastify.post("/sites/:siteId/feature-flags", site("flags:write"), createFeatureFlag);
+ fastify.put("/sites/:siteId/feature-flags/:flagId", site("flags:write"), updateFeatureFlag);
+ fastify.delete("/sites/:siteId/feature-flags/:flagId", site("flags:write"), deleteFeatureFlag);
+ fastify.post("/sites/:siteId/feature-flags/evaluate", site("flags:read"), evaluateServerFeatureFlags);
+ fastify.post("/site/:siteId/feature-flags/evaluate", publicRoute, evaluateFeatureFlags);
+ fastify.get("/sites/:siteId/experiments", site("experiments:read"), getExperiments);
+ fastify.post("/sites/:siteId/experiments", site("experiments:write"), createExperiment);
+ fastify.put("/sites/:siteId/experiments/:experimentId", site("experiments:write"), updateExperiment);
+ fastify.delete("/sites/:siteId/experiments/:experimentId", site("experiments:write"), deleteExperiment);
+ fastify.get("/sites/:siteId/experiments/:experimentId/results", site("experiments:read"), getExperimentResults);
+ fastify.get("/sites/:siteId/events/names", cachedEventsRead, getEventNames);
+ fastify.get("/sites/:siteId/events/properties", publicEventsRead, getEventProperties);
+ fastify.get("/sites/:siteId/events/autocapture", cachedEventsRead, getAutocaptureEvents);
+ fastify.get("/sites/:siteId/events/autocapture-values", publicEventsRead, getAutocaptureValues);
+ fastify.get("/sites/:siteId/events/outbound", cachedEventsRead, getOutboundLinks);
+ fastify.get("/org-event-count/:organizationId", org("analytics:read"), getOrgEventCount);
+ fastify.post(
+ "/organizations/:organizationId/analytics/query",
+ withRateLimit(org("sql:read"), customQueryRateLimit),
+ runCustomQuery
+ );
+ fastify.post(
+ "/organizations/:organizationId/analytics/query/generate",
+ withRateLimit(org("sql:read"), generateQueryRateLimit),
+ generateCustomQuery
+ );
+ fastify.get("/sites/:siteId/performance/overview", publicAnalyticsRead, getPerformanceOverview);
+ fastify.get("/sites/:siteId/performance/time-series", publicAnalyticsRead, getPerformanceTimeSeries);
+ fastify.get("/sites/:siteId/performance/by-dimension", publicAnalyticsRead, getPerformanceByDimension);
+ fastify.get("/sites/:siteId/bots/overview", publicAnalyticsRead, getBotOverview);
+ fastify.get("/sites/:siteId/bots/time-series", publicAnalyticsRead, getBotTimeSeries);
+ fastify.get("/sites/:siteId/bots/by-dimension", publicAnalyticsRead, getBotDimension);
+ fastify.get("/sites/:siteId/bots/ai-summary", publicAnalyticsRead, getBotAiSummary);
+ fastify.get("/sites/:siteId/export/pdf", site("analytics:read"), generatePdfReport);
+}
+
+async function sessionReplayRoutes(fastify: FastifyInstance) {
+ // Session Replay
+ fastify.post("/session-replay/record/:siteId", publicRoute, recordSessionReplay); // Public - tracking endpoint
+ fastify.get("/sites/:siteId/session-replay/list", publicReplayRead, getSessionReplays);
+ fastify.get("/sites/:siteId/session-replay/:sessionId", publicReplayRead, getSessionReplayEvents);
+ fastify.delete("/sites/:siteId/session-replay/:sessionId", site("replay:delete"), deleteSessionReplay);
+}
+
+async function sitesRoutes(fastify: FastifyInstance) {
+ // Sites
+ fastify.get("/sites/:siteId", publicSitesRead, getSite);
+ fastify.put("/sites/:siteId/config", site("sites:configure"), updateSiteConfig);
+ fastify.put("/sites/:siteId/move", site("sites:transfer"), moveSite);
+ fastify.delete("/sites/:siteId", site("sites:delete"), deleteSite);
+ // Handing a site to someone outside the organization (see siteTransfers.ts).
+ fastify.post("/sites/:siteId/transfer", site("sites:transfer"), createSiteTransfer);
+ fastify.get("/sites/:siteId/transfer", site("sites:transfer"), getSiteTransfer);
+ fastify.delete("/sites/:siteId/transfer", site("sites:transfer"), cancelSiteTransfer);
+ // The recipient's side: the handler checks the signed-in user is the recipient.
+ fastify.get("/site-transfers/:transferId", authenticated("deny-scoped"), getIncomingSiteTransfer);
+ fastify.post("/site-transfers/:transferId/accept", authenticated("deny-scoped"), acceptSiteTransfer);
+ fastify.post("/site-transfers/:transferId/decline", authenticated("deny-scoped"), declineSiteTransfer);
+ fastify.get("/sites/:siteId/private-link-config", site("sites:configure"), getSitePrivateLinkConfig);
+ fastify.post("/sites/:siteId/private-link-config", site("sites:configure"), updateSitePrivateLinkConfig);
+ fastify.get("/site/tracking-config/:siteId", publicRoute, getTrackingConfig); // Public - used by tracking script
+ fastify.get("/site/check-install", publicRoute, checkInstall); // Public (HMAC-signed) - linked from lifecycle emails
+ fastify.get("/sites/:siteId/embed-stats", { ...publicRoute, preHandler: [resolveSiteId] as any }, getEmbedStats); // Public - widget endpoint (handler checks site is public)
+ fastify.get("/sites/:siteId/excluded-ips", site("sites:read"), getSiteExcludedIPs);
+ fastify.get("/sites/:siteId/excluded-countries", site("sites:read"), getSiteExcludedCountries);
+ fastify.get("/sites/:siteId/excluded-paths", site("sites:read"), getSiteExcludedPaths);
+ fastify.get("/sites/:siteId/excluded-hostnames", site("sites:read"), getSiteExcludedHostnames);
+ fastify.get("/sites/:siteId/excluded-user-agents", site("sites:read"), getSiteExcludedUserAgents);
+ fastify.get("/sites/:siteId/excluded-asns", site("sites:read"), getSiteExcludedASNs);
+ fastify.get("/sites/:siteId/excluded-query-params", site("sites:read"), getSiteExcludedQueryParams);
+
+ // Site Usage
+ fastify.get("/sites/:siteId/usage", site("sites:read"), getSiteUsage);
+
+ // Site Imports
+ fastify.get("/sites/:siteId/imports", site("imports:read"), getSiteImports);
+ fastify.post("/sites/:siteId/imports", site("imports:write"), createSiteImport);
+ fastify.post(
+ "/sites/:siteId/imports/:importId/events",
+ { ...site("imports:write"), bodyLimit: 50 * 1024 * 1024 },
+ batchImportEvents
+ );
+ fastify.delete("/sites/:siteId/imports/:importId", site("imports:write"), deleteSiteImport);
+}
+
+async function organizationsRoutes(fastify: FastifyInstance) {
+ // Organizations
+ fastify.get("/organizations", publicRoute, getMyOrganizations); // Resolves the caller itself
+ fastify.get("/organizations/:organizationId/sites", org("org:read"), getSitesFromOrg);
+ fastify.post("/organizations/:organizationId/site-cards-lite", org("analytics:read"), getSiteCardsLite);
+ fastify.post("/organizations/:organizationId/site-cards", org("analytics:read"), getSiteCards);
+ fastify.post("/organizations/:organizationId/sites", org("sites:create"), addSite);
+ // Landing-page domain input: creates an owner-less site reachable only by
+ // its private link key. Public, so cap creations per IP.
+ fastify.post(
+ "/sites/unclaimed",
+ { ...unclaimedSiteRouteOptions, config: { ...unclaimedSiteRouteOptions.config, access: "public" as RouteAccess } },
+ createUnclaimedSite
+ );
+ fastify.post(
+ "/sites/:siteId/claim",
+ { ...authenticated({ resource: "sites", action: "write" }), bodyLimit: 1024 },
+ claimSite
+ ); // The handler checks the caller administers the target organization
+ fastify.get("/organizations/:organizationId/members", org("org:read"), listOrganizationMembers);
+ fastify.post("/organizations/:organizationId/members", org("members:manage"), addUserToOrganization);
+ fastify.post("/organizations/:organizationId/users", org("members:manage"), createUserInOrganization);
+
+ // Member site access management (admin/owner only)
+ fastify.put("/organizations/:organizationId/members/:memberId/sites", org("members:manage"), updateMemberSiteAccess);
+}
+
+async function teamsRoutes(fastify: FastifyInstance) {
+ // Teams
+ fastify.get("/organizations/:organizationId/teams", org("org:read"), listTeams);
+ fastify.post("/organizations/:organizationId/teams", org("teams:manage"), createTeam);
+ fastify.put("/organizations/:organizationId/teams/:teamId", org("teams:manage"), updateTeam);
+ fastify.delete("/organizations/:organizationId/teams/:teamId", org("teams:manage"), deleteTeam);
+}
+
+async function userRoutes(fastify: FastifyInstance) {
+ // User
+ fastify.get("/config", publicRoute, getConfig); // Public - returns app config
+ fastify.get("/version", publicRoute, getVersion); // Public - returns app version
+ fastify.get("/user/organizations", authenticated({ resource: "org", action: "read" }), getUserOrganizations);
+ fastify.post("/user/account-settings", authenticated("deny-scoped"), updateAccountSettings);
+ fastify.post("/user/unsubscribe-marketing", authenticated("deny-scoped"), unsubscribeMarketing);
+ fastify.get("/user/unsubscribe-marketing-oneclick", publicRoute, oneClickUnsubscribeMarketing); // Public - for link clicks
+ fastify.post("/user/unsubscribe-marketing-oneclick", publicRoute, oneClickUnsubscribeMarketing); // Public - for List-Unsubscribe header
+ fastify.post("/user/api-keys", authenticated("deny-scoped"), createUserApiKey);
+ fastify.post("/organizations/:organizationId/api-keys", org("apikeys:manage"), createOrgApiKey);
+ fastify.get("/organizations/:organizationId/api-usage", org("org:read"), getOrgApiUsage);
+}
+
+async function gscRoutes(fastify: FastifyInstance) {
+ // GOOGLE SEARCH CONSOLE
+ fastify.get("/sites/:siteId/gsc/connect", site("gsc:write"), connectGSC);
+ fastify.get("/gsc/callback", publicRoute, gscCallback); // Public - OAuth callback
+ fastify.get("/sites/:siteId/gsc/status", publicGscRead, getGSCStatus);
+ fastify.delete("/sites/:siteId/gsc/disconnect", site("gsc:write"), disconnectGSC);
+ fastify.post("/sites/:siteId/gsc/select-property", site("gsc:write"), selectGSCProperty);
+ fastify.get("/sites/:siteId/gsc/data", publicGscRead, getGSCData);
+}
+
+async function stripeAdminRoutes(fastify: FastifyInstance) {
+ // ClickHouse stats (available for all admins)
+ fastify.get("/admin/clickhouse-stats", systemAdmin, getClickhouseStats);
+ fastify.get("/admin/clickhouse-query-log", systemAdmin, getClickhouseQueryLog);
+ fastify.get("/admin/sites", systemAdmin, getAdminSites);
+ fastify.put("/admin/sites/:siteId/move", systemAdmin, adminMoveSite);
+ fastify.get("/admin/organizations", systemAdmin, getAdminOrganizations);
+ fastify.get("/admin/organization-options", systemAdmin, getAdminOrganizationOptions);
+ fastify.get("/admin/subscription-plans", systemAdmin, getAdminSubscriptionPlans);
+ fastify.put(
+ "/admin/organizations/:organizationId/subscription-override",
+ systemAdmin,
+ updateAdminSubscriptionOverride
+ );
+ fastify.get("/admin/organizations/:organizationId/members/:memberId", systemAdmin, getAdminOrganizationMember);
+ fastify.patch("/admin/organizations/:organizationId/members/:memberId", systemAdmin, updateAdminOrganizationMember);
+ fastify.delete("/admin/organizations/:organizationId/members/:memberId", systemAdmin, deleteAdminOrganizationMember);
+ fastify.get("/admin/service-event-count", systemAdmin, getAdminServiceEventCount);
+ fastify.post("/admin/telemetry", publicRoute, collectTelemetry); // Public - telemetry collection
+
+ // STRIPE & ADMIN
+ if (IS_CLOUD) {
+ // Stripe Routes
+ fastify.post("/stripe/create-checkout-session", authenticated("deny-scoped"), createCheckoutSession);
+ fastify.post("/stripe/create-portal-session", authenticated("deny-scoped"), createPortalSession);
+ fastify.post("/stripe/preview-subscription-update", authenticated("deny-scoped"), previewSubscriptionUpdate);
+ fastify.post("/stripe/update-subscription", authenticated("deny-scoped"), updateSubscription);
+ fastify.get("/stripe/subscription", authenticated("deny-scoped"), getSubscription);
+ fastify.get("/stripe/invoices", authenticated("deny-scoped"), getInvoices);
+ fastify.post("/stripe/cancellation-feedback", authenticated("deny-scoped"), submitCancellationFeedback);
+ fastify.post("/stripe/webhook", { config: { rawBody: true, access: "public" as RouteAccess } }, handleWebhook); // Public - Stripe webhook
+
+ // AppSumo Routes
+ fastify.post("/as/activate", authenticated("deny-scoped"), activateAppSumoLicense);
+ fastify.post("/as/webhook", publicRoute, handleAppSumoWebhook); // Public - AppSumo webhook
+ }
+}
+
+// Main API routes plugin - registers all domain plugins
+export async function apiRoutes(fastify: FastifyInstance) {
+ fastify.addHook("onRoute", assertRouteAccessDeclared);
+ await fastify.register(analyticsRoutes);
+ await fastify.register(sessionReplayRoutes);
+ await fastify.register(sitesRoutes);
+ await fastify.register(organizationsRoutes);
+ await fastify.register(teamsRoutes);
+ await fastify.register(userRoutes);
+ await fastify.register(gscRoutes);
+ await fastify.register(stripeAdminRoutes);
+ await fastify.register(mcpRoutes);
+
+ // Health check
+ fastify.get("/health", { logLevel: "silent", ...publicRoute }, (_: FastifyRequest, reply: FastifyReply) =>
+ reply.send("OK")
+ );
+}
diff --git a/server/src/api/sites/applySiteMove.ts b/server/src/api/sites/applySiteMove.ts
index c6abc1615..714c4522e 100644
--- a/server/src/api/sites/applySiteMove.ts
+++ b/server/src/api/sites/applySiteMove.ts
@@ -1,10 +1,39 @@
-import { eq } from "drizzle-orm";
+import { and, eq, isNull } from "drizzle-orm";
import { db } from "../../db/postgres/postgres.js";
-import { memberSiteAccess, segments, sites, teamSiteAccess } from "../../db/postgres/schema.js";
+import {
+ annotations,
+ importStatus,
+ memberSiteAccess,
+ segments,
+ sites,
+ siteTransfers,
+ teamSiteAccess,
+} from "../../db/postgres/schema.js";
import type { SiteTransaction } from "../../services/sites/withOrganizationSiteLock.js";
-import { invalidateSitesAccessCache } from "../../lib/auth-utils.js";
+import { invalidateOrganizationSitesCache, invalidateSitesAccessCache } from "../../lib/auth-utils.js";
import { usageService } from "../../services/usageService.js";
+/**
+ * Lock a site's row for the rest of the transaction and read the organization
+ * it is in now. Anything that authorizes a change of ownership (moving it,
+ * handing it over) must check the caller against this organization, under
+ * this lock β€” authorization done before it can be overtaken by a concurrent
+ * move. Lock order everywhere: organization row, then site row, then transfer
+ * rows.
+ */
+export async function lockSiteOwnership(
+ tx: SiteTransaction,
+ siteId: number
+): Promise<{ organizationId: string | null; domain: string } | null> {
+ const [site] = await tx
+ .select({ organizationId: sites.organizationId, domain: sites.domain })
+ .from(sites)
+ .where(eq(sites.siteId, siteId))
+ .limit(1)
+ .for("update");
+ return site ?? null;
+}
+
/**
* Reassigns a site to a different organization and clears the access grants
* (restricted member access and team access) tied to the old organization,
@@ -12,6 +41,11 @@ import { usageService } from "../../services/usageService.js";
* sites-access cache for members of both organizations so the change is
* reflected immediately.
*
+ * The move only happens while the site still belongs to
+ * `sourceOrganizationId` β€” a compare-and-swap on the site row, which also
+ * serializes concurrent moves of the same site. Returns false, changing
+ * nothing, when another move got there first.
+ *
* Permission checks are the caller's responsibility.
*/
export async function applySiteMove(
@@ -19,12 +53,21 @@ export async function applySiteMove(
sourceOrganizationId: string | null,
targetOrganizationId: string,
transaction?: SiteTransaction
-) {
+): Promise<boolean> {
const move = async (tx: SiteTransaction) => {
- await tx
+ const moved = await tx
.update(sites)
.set({ organizationId: targetOrganizationId, updatedAt: new Date().toISOString() })
- .where(eq(sites.siteId, siteId));
+ .where(
+ and(
+ eq(sites.siteId, siteId),
+ sourceOrganizationId === null ? isNull(sites.organizationId) : eq(sites.organizationId, sourceOrganizationId)
+ )
+ )
+ .returning({ siteId: sites.siteId });
+ if (moved.length === 0) {
+ return false;
+ }
await tx.delete(memberSiteAccess).where(eq(memberSiteAccess.siteId, siteId));
await tx.delete(teamSiteAccess).where(eq(teamSiteAccess.siteId, siteId));
// Site-specific segments travel with the site; they are looked up by
@@ -32,18 +75,29 @@ export async function applySiteMove(
// hide them from the moved site and let the old org's deletion cascade
// over them. Org-wide segments (null site_id) stay with their org.
await tx.update(segments).set({ organizationId: targetOrganizationId }).where(eq(segments.siteId, siteId));
+ // Same for the site's own annotations (org-wide ones stay) and its import
+ // history, which carry the organization for access checks and cascades.
+ await tx.update(annotations).set({ organizationId: targetOrganizationId }).where(eq(annotations.siteId, siteId));
+ await tx.update(importStatus).set({ organizationId: targetOrganizationId }).where(eq(importStatus.siteId, siteId));
+ // A pending hand-over was authorized by the old organization.
+ await tx.delete(siteTransfers).where(eq(siteTransfers.siteId, siteId));
+ return true;
};
- if (transaction) await move(transaction);
- else {
- await db.transaction(move);
+ if (transaction) return move(transaction);
+ const moved = await db.transaction(move);
+ if (moved) {
await invalidateSiteMoveAccess(sourceOrganizationId, targetOrganizationId);
}
+ return moved;
}
// Call after the enclosing transaction commits so no request can repopulate
// the old access list between invalidation and commit.
export async function invalidateSiteMoveAccess(sourceOrganizationId: string | null, targetOrganizationId: string) {
const orgIds = sourceOrganizationId ? [sourceOrganizationId, targetOrganizationId] : [targetOrganizationId];
+ for (const organizationId of orgIds) {
+ invalidateOrganizationSitesCache(organizationId);
+ }
const affectedMembers = await db.query.member.findMany({
where: (m, { inArray }) => inArray(m.organizationId, orgIds),
columns: { userId: true },
diff --git a/server/src/api/sites/claimSite.ts b/server/src/api/sites/claimSite.ts
index ef7d30e77..c59e9ddda 100644
--- a/server/src/api/sites/claimSite.ts
+++ b/server/src/api/sites/claimSite.ts
@@ -1,6 +1,7 @@
+import { roleHasPermission } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
-import { getOrgMembership, isOrgAdmin } from "../../lib/access.js";
+import { getOrgMembership } from "../../lib/access.js";
import { invalidateSitesAccessCache } from "../../lib/auth-utils.js";
import { SiteLifecycleError, siteConfigurationLifecycle } from "../../services/sites/siteConfigurationLifecycle.js";
@@ -38,7 +39,7 @@ export async function claimSite(
const { privateLinkKey, organizationId } = parsed.data;
const membership = await getOrgMembership(userId, organizationId);
- if (!isOrgAdmin(membership)) {
+ if (!roleHasPermission(membership?.role, "sites:create")) {
return reply.status(403).send({ error: "You must be an admin of the organization to claim a site into it" });
}
diff --git a/server/src/api/sites/getSite.ts b/server/src/api/sites/getSite.ts
index a99894f97..fa5ef1f69 100644
--- a/server/src/api/sites/getSite.ts
+++ b/server/src/api/sites/getSite.ts
@@ -3,7 +3,8 @@ import { eq } from "drizzle-orm";
import { FastifyReply, FastifyRequest } from "fastify";
import { db } from "../../db/postgres/postgres.js";
import { organization, sites } from "../../db/postgres/schema.js";
-import { getUserHasAdminAccessToSite } from "../../lib/auth-utils.js";
+import { isAdminRole, permissionsForRole } from "@rybbit/shared";
+import { getUserSiteRole } from "../../lib/auth-utils.js";
import { getBestSubscription, siteRequiresPlan } from "../../lib/subscriptionUtils.js";
/**
@@ -42,8 +43,9 @@ export async function getSite(request: FastifyRequest<GetSiteParams>, reply: Fas
return reply.status(404).send({ error: "Site not found" });
}
- const [isOwner, requiresPlan] = await Promise.all([
- getUserHasAdminAccessToSite(request, site.siteId),
+ // The caller's role on the site; null for public and private-link viewers.
+ const [role, requiresPlan] = await Promise.all([
+ getUserSiteRole(request, site.siteId),
getSiteRequiresPlan(site),
]);
@@ -64,7 +66,10 @@ export async function getSite(request: FastifyRequest<GetSiteParams>, reply: Fas
blockBots: site.blockBots,
firstPartyProxy: site.firstPartyProxy,
trackIp: site.trackIp,
- isOwner: isOwner,
+ isOwner: isAdminRole(role),
+ role,
+ // What that role allows here (a bearer credential's scopes may narrow it).
+ permissions: permissionsForRole(role),
requiresPlan,
// Analytics features
sessionReplay: site.sessionReplay,
diff --git a/server/src/api/sites/getSitesFromOrg.ts b/server/src/api/sites/getSitesFromOrg.ts
index adcb4893f..5552a3cec 100644
--- a/server/src/api/sites/getSitesFromOrg.ts
+++ b/server/src/api/sites/getSitesFromOrg.ts
@@ -1,11 +1,11 @@
+import { isAdminRole, permissionsForRole } from "@rybbit/shared";
import { eq } from "drizzle-orm";
import { FastifyRequest, FastifyReply } from "fastify";
import { clickhouse } from "../../db/clickhouse/clickhouse.js";
import { db } from "../../db/postgres/postgres.js";
-import { sites, organization, team, teamSiteAccess } from "../../db/postgres/schema.js";
+import { organization, team, teamSiteAccess } from "../../db/postgres/schema.js";
import { DEFAULT_EVENT_LIMIT, IS_CLOUD, LITE_DASHBOARD } from "../../lib/const.js";
-import { getUserIdFromRequest } from "../../lib/auth-utils.js";
-import { filterSitesByMemberAccess, getOrgMembership } from "../../lib/access.js";
+import { getOrganizationSitesForCaller } from "../../lib/auth-utils.js";
import { processResults } from "../analytics/utils/utils.js";
import { siteRequiresPlan } from "../../lib/subscriptionUtils.js";
import { getSubscriptionInner } from "../stripe/getSubscription.js";
@@ -22,29 +22,13 @@ export async function getSitesFromOrg(
try {
const { organizationId } = req.params;
- // Use session user ID, falling back to API key user ID
- const userId = req.user?.id ?? (await getUserIdFromRequest(req));
-
- // Run all database queries concurrently
- const [memberRecord, allSitesData, orgInfo] = await Promise.all([
- getOrgMembership(userId, organizationId),
- db.select().from(sites).where(eq(sites.organizationId, organizationId)),
+ // The organization's sites the caller can reach, each with their role on
+ // it β€” member and team restrictions already applied.
+ const [sitesData, orgInfo] = await Promise.all([
+ getOrganizationSitesForCaller(req, organizationId),
db.select().from(organization).where(eq(organization.id, organizationId)).limit(1),
]);
- // Filter sites based on member's access restrictions and teams
- let sitesData = allSitesData;
-
- if (memberRecord?.role === "member" && userId) {
- sitesData = await filterSitesByMemberAccess(
- allSitesData,
- organizationId,
- userId,
- memberRecord.id,
- memberRecord.hasRestrictedSiteAccess
- );
- }
-
// Query session counts for the sites
const sessionCountMap = new Map<number, number>();
@@ -103,12 +87,16 @@ export async function getSitesFromOrg(
// apiKey and privateLinkKey are secrets (ingestion auth / private-link
// dashboard access) and must not be exposed to org members here β€” the
// client reads them from the admin-gated per-site endpoints instead.
- const enhancedSitesData = sitesData.map(({ apiKey, privateLinkKey, ...site }) => ({
+ const enhancedSitesData = sitesData.map(({ apiKey, privateLinkKey, accessRole, ...site }) => ({
...site,
type: site.type || "web",
domain: site.domain || "",
sessionsLast24Hours: sessionCountMap.get(site.siteId) || 0,
- isOwner: memberRecord?.role !== "member",
+ isOwner: isAdminRole(accessRole),
+ // The caller's role on this site and what it allows (a bearer
+ // credential's scopes may narrow that further).
+ role: accessRole,
+ permissions: permissionsForRole(accessRole),
teams: siteTeamMap.get(site.siteId) || [],
requiresPlan: siteRequiresPlan(subscription, site.createdAt),
}));
@@ -118,6 +106,9 @@ export async function getSitesFromOrg(
return res.status(200).send({
organization: orgInfo[0] || null,
+ // The caller's role in the organization, from the route guard.
+ role: req.accessRole ?? null,
+ permissions: permissionsForRole(req.accessRole),
sites: enhancedSitesData,
subscription: {
monthlyEventCount,
diff --git a/server/src/api/sites/moveSite.test.ts b/server/src/api/sites/moveSite.test.ts
index ce40ca68b..80fdaefe6 100644
--- a/server/src/api/sites/moveSite.test.ts
+++ b/server/src/api/sites/moveSite.test.ts
@@ -6,11 +6,15 @@ const state = vi.hoisted(() => ({
targetOrg: null as Record<string, unknown> | null,
targetMembership: null as { role: string } | null,
targetOrgSiteCount: 0,
+ // The caller's role in the site's current organization, re-checked under the site lock.
+ sourceRole: "admin" as string | null,
+ // The site's organization as the lock reads it (a concurrent move changes it).
+ lockedOrganizationId: "org_source" as string | null,
}));
const mocks = vi.hoisted(() => ({
getSubscriptionInner: vi.fn(),
- applySiteMove: vi.fn(async () => {}),
+ applySiteMove: vi.fn(async () => true),
}));
// The membership check now goes through the shared Site Access module.
@@ -18,10 +22,20 @@ vi.mock("../../lib/access.js", async importOriginal => {
const actual = await importOriginal<typeof import("../../lib/access.js")>();
return {
...actual,
- getOrgMembership: vi.fn(async () => state.targetMembership as any),
+ // The target check, and the re-check against the site's current (source)
+ // organization under the site lock.
+ getOrgMembership: vi.fn(async (_userId: string, organizationId: string) =>
+ organizationId === "org_source"
+ ? state.sourceRole && { role: state.sourceRole, hasRestrictedSiteAccess: false }
+ : (state.targetMembership as any)
+ ),
};
});
+vi.mock("../../lib/auth-utils.js", () => ({
+ getIsUserAdmin: vi.fn(async () => false),
+}));
+
vi.mock("../../db/postgres/postgres.js", () => ({
db: {
execute: vi.fn(async () => []),
@@ -58,6 +72,10 @@ vi.mock("../stripe/getSubscription.js", () => ({
vi.mock("./applySiteMove.js", () => ({
applySiteMove: mocks.applySiteMove,
invalidateSiteMoveAccess: vi.fn(async () => {}),
+ // The site row lock reads the organization the site is in at that moment.
+ lockSiteOwnership: vi.fn(async () =>
+ state.site ? { organizationId: state.lockedOrganizationId, domain: "example.com" } : null
+ ),
}));
import { moveSite } from "./moveSite.js";
@@ -95,6 +113,8 @@ beforeEach(() => {
state.targetOrg = { id: "org_target", name: "Target Org" };
state.targetMembership = { role: "admin" };
state.targetOrgSiteCount = 0;
+ state.sourceRole = "admin";
+ state.lockedOrganizationId = "org_source";
mocks.getSubscriptionInner.mockResolvedValue({ planName: "pro-1m", status: "active", siteLimit: null });
});
@@ -156,6 +176,28 @@ describe("moveSite β€” target-organization authorization (sole gate)", () => {
});
describe("moveSite β€” target-organization site limit (cloud)", () => {
+ it("re-checks the caller against the site's organization under the site lock", async () => {
+ // The guard passed, but by the time the lock is held the caller is no
+ // longer an admin where the site is.
+ state.sourceRole = "member";
+ const reply = replyStub();
+
+ await moveSite(makeRequest(), reply);
+
+ expect(reply.statusCode).toBe(403);
+ expect(mocks.applySiteMove).not.toHaveBeenCalled();
+ });
+
+ it("refuses when the site moved between the guard and the lock", async () => {
+ state.lockedOrganizationId = "org_elsewhere";
+ const reply = replyStub();
+
+ await moveSite(makeRequest(), reply);
+
+ expect(reply.statusCode).toBe(409);
+ expect(mocks.applySiteMove).not.toHaveBeenCalled();
+ });
+
it("rejects the move when the target org is at its site limit", async () => {
mocks.getSubscriptionInner.mockResolvedValue({ planName: "standard-250k", status: "active", siteLimit: 5 });
state.targetOrgSiteCount = 5;
diff --git a/server/src/api/sites/moveSite.ts b/server/src/api/sites/moveSite.ts
index 5e8b480cd..057eaed32 100644
--- a/server/src/api/sites/moveSite.ts
+++ b/server/src/api/sites/moveSite.ts
@@ -1,13 +1,14 @@
+import { higherRole, roleHasPermission } from "@rybbit/shared";
import { eq } from "drizzle-orm";
import { FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { db } from "../../db/postgres/postgres.js";
import { organization, sites } from "../../db/postgres/schema.js";
-import { getOrgMembership, isOrgAdmin } from "../../lib/access.js";
-import { IS_CLOUD } from "../../lib/const.js";
-import { getSubscriptionInner } from "../stripe/getSubscription.js";
+import { effectiveOrgRole, getOrgMembership } from "../../lib/access.js";
+import { getIsUserAdmin } from "../../lib/auth-utils.js";
import { withOrganizationSiteLock } from "../../services/sites/withOrganizationSiteLock.js";
-import { applySiteMove, invalidateSiteMoveAccess } from "./applySiteMove.js";
+import { applySiteMove, invalidateSiteMoveAccess, lockSiteOwnership } from "./applySiteMove.js";
+import { getPlanSiteLimit, targetSiteLimitError } from "./siteLimit.js";
const moveSiteSchema = z.object({
organizationId: z.string().min(1),
@@ -58,7 +59,7 @@ export async function moveSite(
if (!targetMembership) {
return reply.status(403).send({ error: "You are not a member of the target organization" });
}
- if (!isOrgAdmin(targetMembership)) {
+ if (!roleHasPermission(targetMembership.role, "sites:create")) {
return reply.status(403).send({ error: "You must be an admin or owner of the target organization" });
}
@@ -72,29 +73,40 @@ export async function moveSite(
return reply.status(404).send({ error: "Target organization not found" });
}
- const capacityError = await withOrganizationSiteLock(targetOrganizationId, async tx => {
- // Enforce the target organization's site limit on cloud.
- if (IS_CLOUD) {
- const subscription = await getSubscriptionInner(targetOrganizationId);
- const siteLimit = subscription?.siteLimit ?? null;
- if (siteLimit !== null) {
- const existingSites = await tx
- .select({ siteId: sites.siteId })
- .from(sites)
- .where(eq(sites.organizationId, targetOrganizationId));
- if (existingSites.length >= siteLimit) {
- return `The target organization has reached its limit of ${siteLimit} website${
- siteLimit === 1 ? "" : "s"
- }. Please upgrade it to add more.`;
- }
- }
+ // Resolved before the transaction: it must not wait on a second connection.
+ const [isSystemAdmin, siteLimit] = await Promise.all([
+ request.bearerAuth ? false : getIsUserAdmin(request),
+ getPlanSiteLimit(targetOrganizationId),
+ ]);
+
+ const failure = await withOrganizationSiteLock(targetOrganizationId, async tx => {
+ // The route guard checked the caller against the site's organization as
+ // it was when the request arrived; check again against the one it is in
+ // now, holding the site row so a concurrent move can't slip between.
+ const current = await lockSiteOwnership(tx, siteId);
+ if (!current || current.organizationId !== sourceOrganizationId) {
+ return { status: 409, error: "The site moved while this request was in flight; reload and try again" };
+ }
+ const sourceRole = sourceOrganizationId
+ ? higherRole(
+ effectiveOrgRole(await getOrgMembership(userId, sourceOrganizationId, tx)),
+ isSystemAdmin ? "admin" : null
+ )
+ : null;
+ if (!roleHasPermission(sourceRole, "sites:transfer")) {
+ return { status: 403, error: "Forbidden" };
}
- await applySiteMove(siteId, sourceOrganizationId, targetOrganizationId, tx);
+ const limitError = await targetSiteLimitError(tx, targetOrganizationId, siteLimit);
+ if (limitError) return { status: 403, error: limitError };
+
+ if (!(await applySiteMove(siteId, sourceOrganizationId, targetOrganizationId, tx))) {
+ return { status: 409, error: "The site moved while this request was in flight; reload and try again" };
+ }
return null;
});
- if (capacityError) return reply.status(403).send({ error: capacityError });
+ if (failure) return reply.status(failure.status).send({ error: failure.error });
await invalidateSiteMoveAccess(sourceOrganizationId, targetOrganizationId);
return reply.status(200).send({ success: true, organizationId: targetOrganizationId });
} catch (error) {
diff --git a/server/src/api/sites/siteLimit.ts b/server/src/api/sites/siteLimit.ts
new file mode 100644
index 000000000..a526b3df5
--- /dev/null
+++ b/server/src/api/sites/siteLimit.ts
@@ -0,0 +1,44 @@
+import { eq } from "drizzle-orm";
+import { sites } from "../../db/postgres/schema.js";
+import { IS_CLOUD } from "../../lib/const.js";
+import type { SiteTransaction } from "../../services/sites/withOrganizationSiteLock.js";
+import { getSubscriptionInner } from "../stripe/getSubscription.js";
+
+/**
+ * The plan's site limit for an organization (null when it has none, or on
+ * self-hosted instances). Resolve it BEFORE opening the locked transaction:
+ * the subscription lookup uses its own connections, and a transaction that
+ * waits on a second pooled connection can exhaust the pool.
+ */
+export async function getPlanSiteLimit(organizationId: string): Promise<number | null> {
+ if (!IS_CLOUD) {
+ return null;
+ }
+ const subscription = await getSubscriptionInner(organizationId);
+ return subscription?.siteLimit ?? null;
+}
+
+/**
+ * Why the target organization cannot take one more site under `siteLimit`, or
+ * null when it can. Call inside withOrganizationSiteLock(targetOrganizationId)
+ * so the count can't race.
+ */
+export async function targetSiteLimitError(
+ tx: SiteTransaction,
+ targetOrganizationId: string,
+ siteLimit: number | null
+): Promise<string | null> {
+ if (siteLimit === null) {
+ return null;
+ }
+ const existingSites = await tx
+ .select({ siteId: sites.siteId })
+ .from(sites)
+ .where(eq(sites.organizationId, targetOrganizationId));
+ if (existingSites.length < siteLimit) {
+ return null;
+ }
+ return `The target organization has reached its limit of ${siteLimit} website${
+ siteLimit === 1 ? "" : "s"
+ }. Please upgrade it to add more.`;
+}
diff --git a/server/src/api/sites/siteTransfers.test.ts b/server/src/api/sites/siteTransfers.test.ts
new file mode 100644
index 000000000..b449d2899
--- /dev/null
+++ b/server/src/api/sites/siteTransfers.test.ts
@@ -0,0 +1,376 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+
+const state = vi.hoisted(() => ({ isCloud: false, siteLimit: null as number | null }));
+const mocks = vi.hoisted(() => ({
+ sendSiteTransferEmail: vi.fn(async () => {}),
+ invalidateSitesAccessCache: vi.fn(),
+ invalidateOrganizationSitesCache: vi.fn(),
+}));
+
+vi.mock("../../db/postgres/postgres.js", async () => {
+ const { PGlite } = await import("@electric-sql/pglite");
+ const { drizzle } = await import("drizzle-orm/pglite");
+ const schema = await import("../../db/postgres/schema.js");
+ const client = new PGlite();
+ return { db: drizzle(client, { schema }), sql: client };
+});
+vi.mock("../../lib/auth-utils.js", () => ({
+ invalidateSitesAccessCache: mocks.invalidateSitesAccessCache,
+ invalidateOrganizationSitesCache: mocks.invalidateOrganizationSitesCache,
+ getIsUserAdmin: vi.fn(async () => false),
+}));
+vi.mock("../../lib/email/email.js", () => ({ sendSiteTransferEmail: mocks.sendSiteTransferEmail }));
+vi.mock("../../lib/const.js", async importOriginal => ({
+ ...(await importOriginal<typeof import("../../lib/const.js")>()),
+ get IS_CLOUD() {
+ return state.isCloud;
+ },
+}));
+vi.mock("../stripe/getSubscription.js", () => ({
+ getSubscriptionInner: vi.fn(async () => ({ siteLimit: state.siteLimit })),
+}));
+
+import { sql as pgClient } from "../../db/postgres/postgres.js";
+import {
+ acceptSiteTransfer,
+ cancelSiteTransfer,
+ createSiteTransfer,
+ declineSiteTransfer,
+ getIncomingSiteTransfer,
+ getSiteTransfer,
+} from "./siteTransfers.js";
+
+// Only the columns these handlers and applySiteMove touch.
+const DDL = `
+CREATE TABLE "organization" ("id" text PRIMARY KEY, "name" text NOT NULL);
+CREATE TABLE "user" ("id" text PRIMARY KEY, "email" text NOT NULL, "emailVerified" boolean NOT NULL DEFAULT false);
+CREATE TABLE "sites" (
+ "site_id" serial PRIMARY KEY,
+ "name" text NOT NULL,
+ "domain" text NOT NULL,
+ "organization_id" text REFERENCES "organization"("id"),
+ "updated_at" timestamp
+);
+CREATE TABLE "member" (
+ "id" text PRIMARY KEY,
+ "organizationId" text NOT NULL,
+ "userId" text NOT NULL,
+ "role" text NOT NULL,
+ "createdAt" timestamp NOT NULL DEFAULT now(),
+ "has_restricted_site_access" boolean NOT NULL DEFAULT false
+);
+CREATE TABLE "member_site_access" ("id" serial PRIMARY KEY, "member_id" text NOT NULL, "site_id" integer NOT NULL);
+CREATE TABLE "team_site_access" ("id" serial PRIMARY KEY, "team_id" text NOT NULL, "site_id" integer NOT NULL);
+CREATE TABLE "segments" ("segment_id" serial PRIMARY KEY, "organization_id" text NOT NULL, "site_id" integer);
+CREATE TABLE "annotations" ("id" serial PRIMARY KEY, "organization_id" text NOT NULL, "site_id" integer);
+CREATE TABLE "import_status" ("import_id" text PRIMARY KEY, "organization_id" text NOT NULL, "site_id" integer NOT NULL);
+CREATE TABLE "gsc_connections" ("site_id" integer PRIMARY KEY, "access_token" text NOT NULL);
+CREATE TABLE "site_transfers" (
+ "id" text PRIMARY KEY,
+ "site_id" integer NOT NULL UNIQUE REFERENCES "sites"("site_id") ON DELETE CASCADE,
+ "source_organization_id" text NOT NULL,
+ "recipient_email" text NOT NULL,
+ "created_by" text,
+ "created_at" timestamp NOT NULL DEFAULT now(),
+ "expires_at" timestamp NOT NULL
+);
+`;
+
+function replyStub() {
+ const reply: any = { statusCode: 200 };
+ reply.status = (code: number) => {
+ reply.statusCode = code;
+ return reply;
+ };
+ reply.send = (body: unknown) => {
+ reply.body = body;
+ return reply;
+ };
+ return reply;
+}
+
+const request = (overrides: Record<string, unknown> = {}) =>
+ ({ params: {}, body: {}, user: { id: "barnaby" }, log: { error: vi.fn() }, ...overrides }) as any;
+
+async function rows(query: string) {
+ return (await (pgClient as any).query(query)).rows;
+}
+
+async function startTransfer(email = "[email protected]") {
+ const reply = replyStub();
+ await createSiteTransfer(request({ params: { siteId: "1" }, body: { email } }), reply);
+ return reply;
+}
+
+beforeAll(async () => {
+ await (pgClient as any).exec(DDL);
+});
+
+afterAll(async () => {
+ await (pgClient as any).close();
+});
+
+beforeEach(async () => {
+ vi.clearAllMocks();
+ state.isCloud = false;
+ state.siteLimit = null;
+ await (pgClient as any).exec(`
+ TRUNCATE "site_transfers", "gsc_connections", "import_status", "annotations", "segments",
+ "team_site_access", "member_site_access", "member", "sites", "user", "organization" RESTART IDENTITY;
+ INSERT INTO "organization" VALUES ('org_agency', 'Parcero'), ('org_client', 'TAY'), ('org_other', 'Other');
+ INSERT INTO "user" VALUES
+ ('barnaby', '[email protected]', true), ('tay', '[email protected]', true), ('mallory', '[email protected]', true);
+ INSERT INTO "sites" ("name", "domain", "organization_id") VALUES ('TAY', 'tay.example.org', 'org_agency');
+ INSERT INTO "member" ("id", "organizationId", "userId", "role") VALUES
+ ('m_barnaby', 'org_agency', 'barnaby', 'owner'),
+ ('m_tay_client', 'org_client', 'tay', 'owner'),
+ ('m_tay_other', 'org_other', 'tay', 'member'),
+ ('m_tay_agency', 'org_agency', 'tay', 'viewer');
+ INSERT INTO "member_site_access" ("member_id", "site_id") VALUES ('m_tay_agency', 1);
+ INSERT INTO "segments" ("organization_id", "site_id") VALUES ('org_agency', 1), ('org_agency', NULL);
+ INSERT INTO "annotations" ("organization_id", "site_id") VALUES ('org_agency', 1), ('org_agency', NULL);
+ INSERT INTO "import_status" VALUES ('imp_1', 'org_agency', 1);
+ INSERT INTO "gsc_connections" VALUES (1, 'barnabys-google-token');
+ `);
+});
+
+describe("starting a transfer", () => {
+ it("records one pending transfer, emails the recipient and returns the link", async () => {
+ const reply = await startTransfer(" [email protected] ");
+
+ expect(reply.statusCode).toBe(201);
+ expect(reply.body).toMatchObject({ recipientEmail: "[email protected]", url: expect.stringContaining("/transfer/") });
+ expect(mocks.sendSiteTransferEmail).toHaveBeenCalledWith(
+ expect.objectContaining({ email: "[email protected]", sentBy: "[email protected]", siteDomain: "tay.example.org" })
+ );
+ expect(await rows(`SELECT site_id, source_organization_id, created_by FROM site_transfers`)).toEqual([
+ { site_id: 1, source_organization_id: "org_agency", created_by: "barnaby" },
+ ]);
+ });
+
+ it("replaces the previous transfer, revoking its link", async () => {
+ const first = await startTransfer("[email protected]");
+ await startTransfer("[email protected]");
+
+ expect(await rows(`SELECT id, recipient_email FROM site_transfers`)).toEqual([
+ { id: expect.not.stringMatching(first.body.id), recipient_email: "[email protected]" },
+ ]);
+ });
+
+ it("still returns the link when the email cannot be sent", async () => {
+ mocks.sendSiteTransferEmail.mockRejectedValueOnce(new Error("no email on this instance"));
+
+ const reply = await startTransfer();
+
+ expect(reply.statusCode).toBe(201);
+ expect(reply.body.url).toContain(reply.body.id);
+ });
+
+ it("re-checks the sender against the organization the site is in now", async () => {
+ // The site was handed to org_client after the sender's request passed the
+ // guard: the sender has no role there, so they can't send it anywhere.
+ await (pgClient as any).exec(`UPDATE sites SET organization_id = 'org_client'`);
+
+ const reply = await startTransfer("[email protected]");
+
+ expect(reply.statusCode).toBe(403);
+ expect(await rows(`SELECT * FROM site_transfers`)).toEqual([]);
+ });
+
+ it("refuses organization keys, which act for no person", async () => {
+ const reply = replyStub();
+ await createSiteTransfer(
+ request({ params: { siteId: "1" }, body: { email: "[email protected]" }, user: undefined }),
+ reply
+ );
+
+ expect(reply.statusCode).toBe(401);
+ });
+
+ it("shows and cancels the pending transfer", async () => {
+ await startTransfer();
+
+ const shown = replyStub();
+ await getSiteTransfer(request({ params: { siteId: "1" } }), shown);
+ expect(shown.body.transfer).toMatchObject({ recipientEmail: "[email protected]" });
+
+ await cancelSiteTransfer(request({ params: { siteId: "1" } }), replyStub());
+ const after = replyStub();
+ await getSiteTransfer(request({ params: { siteId: "1" } }), after);
+ expect(after.body).toEqual({ transfer: null });
+ });
+});
+
+describe("the recipient", () => {
+ it("sees the offer only from the account it was sent to (email compared case-insensitively)", async () => {
+ const { body } = await startTransfer();
+
+ const asTay = replyStub();
+ await getIncomingSiteTransfer(request({ params: { transferId: body.id }, user: { id: "tay" } }), asTay);
+ expect(asTay.statusCode).toBe(200);
+ expect(asTay.body).toMatchObject({
+ site: { siteId: 1, domain: "tay.example.org" },
+ sourceOrganizationName: "Parcero",
+ sentBy: "[email protected]",
+ });
+
+ const asMallory = replyStub();
+ await getIncomingSiteTransfer(request({ params: { transferId: body.id }, user: { id: "mallory" } }), asMallory);
+ expect(asMallory.statusCode).toBe(403);
+ // Enough to tell them which account to use, not enough to register it.
+ expect(asMallory.body).toMatchObject({ reason: "wrong_account", recipientEmailHint: "tβ€’β€’@example.org" });
+ expect(JSON.stringify(asMallory.body)).not.toContain("[email protected]");
+
+ const signedOut = replyStub();
+ await getIncomingSiteTransfer(request({ params: { transferId: body.id }, user: undefined }), signedOut);
+ expect(signedOut.statusCode).toBe(401);
+ });
+
+ it("moves the site, its own segments, annotations and imports into their organization", async () => {
+ const { body } = await startTransfer();
+ const reply = replyStub();
+
+ await acceptSiteTransfer(
+ request({ params: { transferId: body.id }, body: { organizationId: "org_client" }, user: { id: "tay" } }),
+ reply
+ );
+
+ expect(reply.statusCode).toBe(200);
+ expect(await rows(`SELECT organization_id FROM sites`)).toEqual([{ organization_id: "org_client" }]);
+ expect(await rows(`SELECT organization_id FROM segments ORDER BY site_id NULLS LAST`)).toEqual([
+ { organization_id: "org_client" },
+ { organization_id: "org_agency" },
+ ]);
+ expect(await rows(`SELECT organization_id FROM annotations ORDER BY site_id NULLS LAST`)).toEqual([
+ { organization_id: "org_client" },
+ { organization_id: "org_agency" },
+ ]);
+ expect(await rows(`SELECT organization_id FROM import_status`)).toEqual([{ organization_id: "org_client" }]);
+ // Access granted by the old organization, the transfer itself, and the
+ // sender's Search Console credentials all stay behind.
+ expect(await rows(`SELECT * FROM member_site_access`)).toEqual([]);
+ expect(await rows(`SELECT * FROM site_transfers`)).toEqual([]);
+ expect(await rows(`SELECT * FROM gsc_connections`)).toEqual([]);
+ // Organization keys of both sides stop seeing the old site list.
+ expect(mocks.invalidateOrganizationSitesCache).toHaveBeenCalledWith("org_agency");
+ expect(mocks.invalidateOrganizationSitesCache).toHaveBeenCalledWith("org_client");
+ });
+
+ it("can only move the site into an organization they administer", async () => {
+ const { body } = await startTransfer();
+ const reply = replyStub();
+
+ await acceptSiteTransfer(
+ request({ params: { transferId: body.id }, body: { organizationId: "org_other" }, user: { id: "tay" } }),
+ reply
+ );
+
+ expect(reply.statusCode).toBe(403);
+ expect(await rows(`SELECT organization_id FROM sites`)).toEqual([{ organization_id: "org_agency" }]);
+ });
+
+ it("cannot be accepted by anyone else holding the link", async () => {
+ const { body } = await startTransfer();
+ await (pgClient as any).exec(
+ `INSERT INTO "member" ("id", "organizationId", "userId", "role") VALUES ('m_mallory', 'org_other', 'mallory', 'owner')`
+ );
+ const reply = replyStub();
+
+ await acceptSiteTransfer(
+ request({ params: { transferId: body.id }, body: { organizationId: "org_other" }, user: { id: "mallory" } }),
+ reply
+ );
+
+ expect(reply.statusCode).toBe(403);
+ expect(await rows(`SELECT organization_id FROM sites`)).toEqual([{ organization_id: "org_agency" }]);
+ });
+
+ it("on cloud, needs the recipient's address to be verified", async () => {
+ state.isCloud = true;
+ const { body } = await startTransfer();
+ await (pgClient as any).exec(`UPDATE "user" SET "emailVerified" = false WHERE id = 'tay'`);
+ const reply = replyStub();
+
+ await acceptSiteTransfer(
+ request({ params: { transferId: body.id }, body: { organizationId: "org_client" }, user: { id: "tay" } }),
+ reply
+ );
+
+ expect(reply.statusCode).toBe(403);
+ expect(reply.body).toMatchObject({ reason: "email_unverified" });
+ expect(await rows(`SELECT organization_id FROM sites`)).toEqual([{ organization_id: "org_agency" }]);
+ });
+
+ it("lets only one of two concurrent accepts move the site", async () => {
+ const { body } = await startTransfer();
+ await (pgClient as any).exec(
+ `INSERT INTO "member" ("id", "organizationId", "userId", "role") VALUES ('m_tay_other_owner', 'org_other', 'tay', 'owner')
+ ON CONFLICT DO NOTHING; UPDATE "member" SET role = 'owner' WHERE id = 'm_tay_other'`
+ );
+ const accept = (organizationId: string) => {
+ const reply = replyStub();
+ return acceptSiteTransfer(
+ request({ params: { transferId: body.id }, body: { organizationId }, user: { id: "tay" } }),
+ reply
+ ).then(() => reply);
+ };
+
+ const replies = await Promise.all([accept("org_client"), accept("org_other")]);
+
+ expect(replies.map(reply => reply.statusCode).sort()).toEqual([200, 404]);
+ const winner = replies.find(reply => reply.statusCode === 200)!.body.organizationId;
+ expect(await rows(`SELECT organization_id FROM sites`)).toEqual([{ organization_id: winner }]);
+ });
+
+ it("is refused once the site has moved by other means", async () => {
+ const { body } = await startTransfer();
+ await (pgClient as any).exec(`UPDATE sites SET organization_id = 'org_other'`);
+ const reply = replyStub();
+
+ await acceptSiteTransfer(
+ request({ params: { transferId: body.id }, body: { organizationId: "org_client" }, user: { id: "tay" } }),
+ reply
+ );
+
+ expect(reply.statusCode).toBe(409);
+ expect(await rows(`SELECT organization_id FROM sites`)).toEqual([{ organization_id: "org_other" }]);
+ });
+
+ it("is refused after the link expires", async () => {
+ const { body } = await startTransfer();
+ await (pgClient as any).exec(`UPDATE site_transfers SET expires_at = now() - interval '1 minute'`);
+ const reply = replyStub();
+
+ await acceptSiteTransfer(
+ request({ params: { transferId: body.id }, body: { organizationId: "org_client" }, user: { id: "tay" } }),
+ reply
+ );
+
+ expect(reply.statusCode).toBe(404);
+ });
+
+ it("respects the receiving organization's site limit on cloud", async () => {
+ state.isCloud = true;
+ state.siteLimit = 0;
+ const { body } = await startTransfer();
+ const reply = replyStub();
+
+ await acceptSiteTransfer(
+ request({ params: { transferId: body.id }, body: { organizationId: "org_client" }, user: { id: "tay" } }),
+ reply
+ );
+
+ expect(reply.statusCode).toBe(403);
+ expect(await rows(`SELECT organization_id FROM sites`)).toEqual([{ organization_id: "org_agency" }]);
+ expect(await rows(`SELECT count(*)::int AS n FROM site_transfers`)).toEqual([{ n: 1 }]);
+ });
+
+ it("can decline, which removes the transfer", async () => {
+ const { body } = await startTransfer();
+
+ await declineSiteTransfer(request({ params: { transferId: body.id }, user: { id: "tay" } }), replyStub());
+
+ expect(await rows(`SELECT * FROM site_transfers`)).toEqual([]);
+ expect(await rows(`SELECT organization_id FROM sites`)).toEqual([{ organization_id: "org_agency" }]);
+ });
+});
diff --git a/server/src/api/sites/siteTransfers.ts b/server/src/api/sites/siteTransfers.ts
new file mode 100644
index 000000000..4d9beb2fe
--- /dev/null
+++ b/server/src/api/sites/siteTransfers.ts
@@ -0,0 +1,375 @@
+import { randomBytes } from "node:crypto";
+import { higherRole, roleHasPermission } from "@rybbit/shared";
+import { eq } from "drizzle-orm";
+import { FastifyReply, FastifyRequest } from "fastify";
+import { z } from "zod";
+import { db } from "../../db/postgres/postgres.js";
+import { gscConnections, organization, sites, siteTransfers, user } from "../../db/postgres/schema.js";
+import { effectiveOrgRole, getOrgMembership } from "../../lib/access.js";
+import { getIsUserAdmin } from "../../lib/auth-utils.js";
+import { IS_CLOUD } from "../../lib/const.js";
+import { sendSiteTransferEmail } from "../../lib/email/email.js";
+import { claimExpiryIso as utcIso } from "../../services/sites/claimExpiry.js";
+import { withOrganizationSiteLock } from "../../services/sites/withOrganizationSiteLock.js";
+import { applySiteMove, invalidateSiteMoveAccess, lockSiteOwnership } from "./applySiteMove.js";
+import { getPlanSiteLimit, targetSiteLimitError } from "./siteLimit.js";
+
+/**
+ * Handing a site to someone outside its organization.
+ *
+ * An admin of the site's organization names a recipient by email (the
+ * sites:transfer permission, enforced by the route guard). The recipient opens
+ * the emailed link, signed in with that email address, and picks an
+ * organization where they hold sites:create; the site then moves exactly as
+ * PUT /sites/:siteId/move moves it. Neither side needs a seat in the other's
+ * organization.
+ *
+ * The transfer id is the secret in the link β€” like an invitation id, it is
+ * only ever sent to the recipient's inbox (and shown to the sender so they can
+ * pass it on themselves when the instance cannot send email).
+ */
+
+const TRANSFER_TTL_MS = 7 * 24 * 60 * 60 * 1000;
+
+const createTransferSchema = z.object({
+ email: z.string().trim().toLowerCase().email(),
+});
+
+const acceptTransferSchema = z.object({
+ organizationId: z.string().min(1),
+});
+
+type TransferRow = typeof siteTransfers.$inferSelect;
+
+const transferUrl = (transferId: string) => `${process.env.BASE_URL ?? ""}/transfer/${transferId}`;
+
+// Postgres hands timestamps back without a zone; they are UTC.
+const isExpired = (transfer: Pick<TransferRow, "expiresAt">) => Date.parse(utcIso(transfer.expiresAt)!) <= Date.now();
+
+function serializeForSender(transfer: TransferRow) {
+ return {
+ id: transfer.id,
+ recipientEmail: transfer.recipientEmail,
+ createdAt: utcIso(transfer.createdAt),
+ expiresAt: utcIso(transfer.expiresAt),
+ url: transferUrl(transfer.id),
+ };
+}
+
+function parseSiteId(raw: string): number | null {
+ const siteId = Number(raw);
+ return Number.isInteger(siteId) && siteId > 0 ? siteId : null;
+}
+
+// ---- Sender (site admin) ----------------------------------------------------
+
+/** POST /sites/:siteId/transfer β€” start (or replace) the site's pending transfer. */
+export async function createSiteTransfer(
+ request: FastifyRequest<{ Params: { siteId: string }; Body: unknown }>,
+ reply: FastifyReply
+) {
+ const siteId = parseSiteId(request.params.siteId);
+ if (!siteId) {
+ return reply.status(400).send({ error: "Invalid site ID" });
+ }
+ const parsed = createTransferSchema.safeParse(request.body);
+ if (!parsed.success) {
+ return reply.status(400).send({ error: "A valid recipient email is required" });
+ }
+ // Like moving a site, handing it over is a person's decision: an
+ // organization-owned API key carries no user and cannot start one.
+ if (!request.user?.id) {
+ return reply.status(401).send({ error: "Transfers must be started by a signed-in user" });
+ }
+
+ const senderId = request.user.id;
+
+ try {
+ // Which organization row to lock; re-checked once the locks are held.
+ const unlocked = await db.query.sites.findFirst({
+ where: eq(sites.siteId, siteId),
+ columns: { organizationId: true },
+ });
+ if (!unlocked?.organizationId) {
+ return reply.status(404).send({ error: "Site not found" });
+ }
+ const sourceOrganizationId = unlocked.organizationId;
+ // Resolved before the transaction: it must not wait on a second connection.
+ const isSystemAdmin = !request.bearerAuth && (await getIsUserAdmin(request));
+
+ // Lock order for every ownership change: organization row, site row,
+ // transfer rows.
+ const outcome = await withOrganizationSiteLock(sourceOrganizationId, async tx => {
+ // The route guard checked the caller against the site's organization
+ // as it was when the request arrived; check again against the one it is
+ // in now, holding the site row so it can't move until this commits.
+ const site = await lockSiteOwnership(tx, siteId);
+ if (!site?.organizationId) {
+ return { ok: false as const, status: 404, error: "Site not found" };
+ }
+ if (site.organizationId !== sourceOrganizationId) {
+ return {
+ ok: false as const,
+ status: 409,
+ error: "The site moved while this request was in flight; reload and try again",
+ };
+ }
+ const role = higherRole(
+ effectiveOrgRole(await getOrgMembership(senderId, sourceOrganizationId, tx)),
+ isSystemAdmin ? "admin" : null
+ );
+ if (!roleHasPermission(role, "sites:transfer")) {
+ return { ok: false as const, status: 403, error: "Forbidden" };
+ }
+
+ const transfer: TransferRow = {
+ id: randomBytes(24).toString("base64url"),
+ siteId,
+ sourceOrganizationId: site.organizationId,
+ recipientEmail: parsed.data.email,
+ createdBy: senderId,
+ createdAt: new Date().toISOString(),
+ expiresAt: new Date(Date.now() + TRANSFER_TTL_MS).toISOString(),
+ };
+ // One pending transfer per site: a new one replaces (and so revokes) the old.
+ await tx.delete(siteTransfers).where(eq(siteTransfers.siteId, siteId));
+ await tx.insert(siteTransfers).values(transfer);
+ return { ok: true as const, transfer, siteDomain: site.domain };
+ });
+
+ if (!outcome.ok) {
+ return reply.status(outcome.status).send({ error: outcome.error });
+ }
+ const { transfer, siteDomain } = outcome;
+ const sourceOrg = await db.query.organization.findFirst({
+ where: eq(organization.id, transfer.sourceOrganizationId),
+ columns: { name: true },
+ });
+
+ const sender = await db.query.user.findFirst({ where: eq(user.id, senderId), columns: { email: true } });
+ try {
+ await sendSiteTransferEmail({
+ email: transfer.recipientEmail,
+ sentBy: sender?.email ?? sourceOrg?.name ?? "A Rybbit user",
+ siteDomain,
+ organizationName: sourceOrg?.name ?? "",
+ transferLink: transferUrl(transfer.id),
+ });
+ } catch (error) {
+ // The link is still returned for the sender to pass on themselves.
+ request.log.error({ err: error, siteId }, "Could not send site transfer email");
+ }
+
+ return reply.status(201).send(serializeForSender(transfer));
+ } catch (error) {
+ request.log.error({ err: error, siteId }, "Error creating site transfer");
+ return reply.status(500).send({ error: "Failed to start the transfer" });
+ }
+}
+
+/** GET /sites/:siteId/transfer β€” the site's pending transfer, or null. */
+export async function getSiteTransfer(request: FastifyRequest<{ Params: { siteId: string } }>, reply: FastifyReply) {
+ const siteId = parseSiteId(request.params.siteId);
+ if (!siteId) {
+ return reply.status(400).send({ error: "Invalid site ID" });
+ }
+ const transfer = await db.query.siteTransfers.findFirst({ where: eq(siteTransfers.siteId, siteId) });
+ return reply.send({ transfer: transfer && !isExpired(transfer) ? serializeForSender(transfer) : null });
+}
+
+/** DELETE /sites/:siteId/transfer β€” cancel the site's pending transfer. */
+export async function cancelSiteTransfer(request: FastifyRequest<{ Params: { siteId: string } }>, reply: FastifyReply) {
+ const siteId = parseSiteId(request.params.siteId);
+ if (!siteId) {
+ return reply.status(400).send({ error: "Invalid site ID" });
+ }
+ await db.delete(siteTransfers).where(eq(siteTransfers.siteId, siteId));
+ return reply.send({ success: true });
+}
+
+// ---- Recipient ----------------------------------------------------------------
+
+type RecipientLookup =
+ | { ok: true; transfer: TransferRow; userId: string }
+ | { ok: false; status: number; body: Record<string, unknown> };
+
+/** "[email protected]" β†’ "tβ€’β€’@example.org": enough to recognise, not to register. */
+function maskEmail(email: string): string {
+ const [local, domain] = email.split("@");
+ return `${local.slice(0, 1)}${"β€’".repeat(Math.max(1, Math.min(local.length - 1, 3)))}@${domain ?? ""}`;
+}
+
+/**
+ * The pending transfer, provided the signed-in user is the person it was sent
+ * to. The id alone is not enough: it must be opened from an account that holds
+ * the recipient's address β€” verified, where this instance can send the
+ * verification email (otherwise anyone holding a leaked link could register
+ * the address and accept).
+ */
+async function loadTransferForRecipient(request: FastifyRequest, transferId: string): Promise<RecipientLookup> {
+ const userId = request.user?.id;
+ if (!userId) {
+ return { ok: false, status: 401, body: { error: "Sign in to view this transfer" } };
+ }
+
+ const transfer = await db.query.siteTransfers.findFirst({ where: eq(siteTransfers.id, transferId) });
+ if (!transfer || isExpired(transfer)) {
+ return { ok: false, status: 404, body: { error: "This transfer link is no longer valid" } };
+ }
+
+ const recipient = await db.query.user.findFirst({
+ where: eq(user.id, userId),
+ columns: { email: true, emailVerified: true },
+ });
+ if (recipient?.email.toLowerCase() !== transfer.recipientEmail.toLowerCase()) {
+ return {
+ ok: false,
+ status: 403,
+ body: {
+ error: "This transfer was sent to a different email address",
+ reason: "wrong_account",
+ recipientEmailHint: maskEmail(transfer.recipientEmail),
+ },
+ };
+ }
+ if (IS_CLOUD && !recipient.emailVerified) {
+ return {
+ ok: false,
+ status: 403,
+ body: { error: "Verify your email address to accept this transfer", reason: "email_unverified" },
+ };
+ }
+
+ return { ok: true, transfer, userId };
+}
+
+/** GET /site-transfers/:transferId β€” what the recipient is being offered. */
+export async function getIncomingSiteTransfer(
+ request: FastifyRequest<{ Params: { transferId: string } }>,
+ reply: FastifyReply
+) {
+ try {
+ const lookup = await loadTransferForRecipient(request, request.params.transferId);
+ if (!lookup.ok) {
+ return reply.status(lookup.status).send(lookup.body);
+ }
+ const { transfer } = lookup;
+
+ const [site, sourceOrg, sender] = await Promise.all([
+ db.query.sites.findFirst({ where: eq(sites.siteId, transfer.siteId), columns: { name: true, domain: true } }),
+ db.query.organization.findFirst({
+ where: eq(organization.id, transfer.sourceOrganizationId),
+ columns: { name: true },
+ }),
+ transfer.createdBy
+ ? db.query.user.findFirst({ where: eq(user.id, transfer.createdBy), columns: { email: true } })
+ : undefined,
+ ]);
+
+ return reply.send({
+ id: transfer.id,
+ site: { siteId: transfer.siteId, name: site?.name ?? "", domain: site?.domain ?? "" },
+ sourceOrganizationId: transfer.sourceOrganizationId,
+ sourceOrganizationName: sourceOrg?.name ?? "",
+ sentBy: sender?.email ?? null,
+ expiresAt: utcIso(transfer.expiresAt),
+ });
+ } catch (error) {
+ request.log.error({ err: error }, "Error loading site transfer");
+ return reply.status(500).send({ error: "Failed to load the transfer" });
+ }
+}
+
+/** POST /site-transfers/:transferId/accept β€” move the site into one of the recipient's organizations. */
+export async function acceptSiteTransfer(
+ request: FastifyRequest<{ Params: { transferId: string }; Body: unknown }>,
+ reply: FastifyReply
+) {
+ const parsed = acceptTransferSchema.safeParse(request.body);
+ if (!parsed.success) {
+ return reply.status(400).send({ error: "organizationId is required" });
+ }
+ const targetOrganizationId = parsed.data.organizationId;
+
+ try {
+ const lookup = await loadTransferForRecipient(request, request.params.transferId);
+ if (!lookup.ok) {
+ return reply.status(lookup.status).send(lookup.body);
+ }
+ const { transfer, userId } = lookup;
+
+ // The same gate as creating a site in that organization.
+ const membership = await getOrgMembership(userId, targetOrganizationId);
+ if (!roleHasPermission(effectiveOrgRole(membership), "sites:create")) {
+ return reply
+ .status(403)
+ .send({ error: "You must be an admin or owner of the organization you move the site into" });
+ }
+ if (targetOrganizationId === transfer.sourceOrganizationId) {
+ return reply.status(400).send({ error: "The site is already in this organization" });
+ }
+
+ // Resolved before the transaction: it must not wait on a second connection.
+ const siteLimit = await getPlanSiteLimit(targetOrganizationId);
+
+ const outcome = await withOrganizationSiteLock(targetOrganizationId, async tx => {
+ // Lock the site, then the transfer (the order every ownership change
+ // uses): a concurrent accept, cancel, replacement or move waits here, and
+ // afterwards finds the transfer gone or the site moved.
+ await lockSiteOwnership(tx, transfer.siteId);
+ const [current] = await tx
+ .select()
+ .from(siteTransfers)
+ .where(eq(siteTransfers.id, transfer.id))
+ .limit(1)
+ .for("update");
+ if (!current || isExpired(current)) {
+ return { status: 404, error: "This transfer link is no longer valid" };
+ }
+
+ const limitError = await targetSiteLimitError(tx, targetOrganizationId, siteLimit);
+ if (limitError) {
+ return { status: 403, error: limitError };
+ }
+
+ // Moves only while the site is still in the organization the transfer
+ // was sent from, and deletes the transfer.
+ if (!(await applySiteMove(transfer.siteId, current.sourceOrganizationId, targetOrganizationId, tx))) {
+ await tx.delete(siteTransfers).where(eq(siteTransfers.id, transfer.id));
+ return { status: 409, error: "The site has moved since this transfer was sent" };
+ }
+ // The Search Console connection holds the sender's Google credentials;
+ // it does not go to someone else's organization.
+ await tx.delete(gscConnections).where(eq(gscConnections.siteId, transfer.siteId));
+ return null;
+ });
+
+ if (outcome) {
+ return reply.status(outcome.status).send({ error: outcome.error });
+ }
+
+ await invalidateSiteMoveAccess(transfer.sourceOrganizationId, targetOrganizationId);
+ return reply.send({ success: true, siteId: transfer.siteId, organizationId: targetOrganizationId });
+ } catch (error) {
+ request.log.error({ err: error }, "Error accepting site transfer");
+ return reply.status(500).send({ error: "Failed to accept the transfer" });
+ }
+}
+
+/** POST /site-transfers/:transferId/decline β€” the recipient turns the transfer down. */
+export async function declineSiteTransfer(
+ request: FastifyRequest<{ Params: { transferId: string } }>,
+ reply: FastifyReply
+) {
+ try {
+ const lookup = await loadTransferForRecipient(request, request.params.transferId);
+ if (!lookup.ok) {
+ return reply.status(lookup.status).send(lookup.body);
+ }
+ await db.delete(siteTransfers).where(eq(siteTransfers.id, lookup.transfer.id));
+ return reply.send({ success: true });
+ } catch (error) {
+ request.log.error({ err: error }, "Error declining site transfer");
+ return reply.status(500).send({ error: "Failed to decline the transfer" });
+ }
+}
diff --git a/server/src/api/stripe/createCheckoutSession.ts b/server/src/api/stripe/createCheckoutSession.ts
index 844ec08f2..1b40842cf 100644
--- a/server/src/api/stripe/createCheckoutSession.ts
+++ b/server/src/api/stripe/createCheckoutSession.ts
@@ -1,9 +1,10 @@
+import { roleHasPermission } from "@rybbit/shared";
import { eq } from "drizzle-orm";
import { FastifyReply, FastifyRequest } from "fastify";
import Stripe from "stripe";
import { db } from "../../db/postgres/postgres.js";
import { organization, user as userSchema } from "../../db/postgres/schema.js";
-import { getOrgMembership, isOrgOwner } from "../../lib/access.js";
+import { getOrgMembership } from "../../lib/access.js";
import { stripe } from "../../lib/stripe.js";
import { hasHadStripeSubscription } from "../../lib/subscriptionUtils.js";
@@ -35,7 +36,7 @@ export async function createCheckoutSession(
// 1. Verify user has permission to manage billing for this organization
const membership = await getOrgMembership(userId, organizationId);
- if (!isOrgOwner(membership)) {
+ if (!roleHasPermission(membership?.role, "billing:manage")) {
return reply.status(403).send({
error: "Only organization owners can manage billing",
});
diff --git a/server/src/api/stripe/createPortalSession.ts b/server/src/api/stripe/createPortalSession.ts
index 256aaba0e..2b18b6338 100644
--- a/server/src/api/stripe/createPortalSession.ts
+++ b/server/src/api/stripe/createPortalSession.ts
@@ -1,9 +1,10 @@
+import { roleHasPermission } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
import { stripe } from "../../lib/stripe.js";
import { db } from "../../db/postgres/postgres.js";
import { organization } from "../../db/postgres/schema.js";
import { eq } from "drizzle-orm";
-import { getOrgMembership, isOrgOwner } from "../../lib/access.js";
+import { getOrgMembership } from "../../lib/access.js";
import Stripe from "stripe";
interface PortalRequestBody {
@@ -30,7 +31,7 @@ export async function createPortalSession(request: FastifyRequest<{ Body: Portal
// 1. Verify user has permission to manage billing for this organization
const membership = await getOrgMembership(userId, organizationId);
- if (!isOrgOwner(membership)) {
+ if (!roleHasPermission(membership?.role, "billing:manage")) {
return reply.status(403).send({
error: "Only organization owners can manage billing",
});
diff --git a/server/src/api/stripe/getInvoices.ts b/server/src/api/stripe/getInvoices.ts
index f947fc6db..16eebb0c3 100644
--- a/server/src/api/stripe/getInvoices.ts
+++ b/server/src/api/stripe/getInvoices.ts
@@ -1,8 +1,9 @@
+import { roleHasPermission } from "@rybbit/shared";
import { eq } from "drizzle-orm";
import { FastifyReply, FastifyRequest } from "fastify";
import { db } from "../../db/postgres/postgres.js";
import { organization } from "../../db/postgres/schema.js";
-import { getOrgMembership, isOrgOwner } from "../../lib/access.js";
+import { getOrgMembership } from "../../lib/access.js";
import { stripe } from "../../lib/stripe.js";
export async function getInvoices(
@@ -32,7 +33,7 @@ export async function getInvoices(
// Verify user has permission to manage billing for this organization
const membership = await getOrgMembership(userId, organizationId);
- if (!isOrgOwner(membership)) {
+ if (!roleHasPermission(membership?.role, "billing:manage")) {
return reply.status(403).send({ error: "Only organization owners can manage billing" });
}
diff --git a/server/src/api/stripe/previewSubscriptionUpdate.ts b/server/src/api/stripe/previewSubscriptionUpdate.ts
index dfdc87ac3..2690ce961 100644
--- a/server/src/api/stripe/previewSubscriptionUpdate.ts
+++ b/server/src/api/stripe/previewSubscriptionUpdate.ts
@@ -1,9 +1,10 @@
+import { roleHasPermission } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
import { stripe } from "../../lib/stripe.js";
import { db } from "../../db/postgres/postgres.js";
import { organization } from "../../db/postgres/schema.js";
import { eq } from "drizzle-orm";
-import { getOrgMembership, isOrgOwner } from "../../lib/access.js";
+import { getOrgMembership } from "../../lib/access.js";
import Stripe from "stripe";
interface PreviewSubscriptionBody {
@@ -32,7 +33,7 @@ export async function previewSubscriptionUpdate(
// 1. Verify user has permission to manage billing for this organization
const membership = await getOrgMembership(userId, organizationId);
- if (!isOrgOwner(membership)) {
+ if (!roleHasPermission(membership?.role, "billing:manage")) {
return reply.status(403).send({
error: "Only organization owners can manage billing",
});
diff --git a/server/src/api/stripe/submitCancellationFeedback.ts b/server/src/api/stripe/submitCancellationFeedback.ts
index 3e248270a..58bc20576 100644
--- a/server/src/api/stripe/submitCancellationFeedback.ts
+++ b/server/src/api/stripe/submitCancellationFeedback.ts
@@ -1,7 +1,8 @@
+import { roleHasPermission } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
import { db } from "../../db/postgres/postgres.js";
import { cancellationFeedback } from "../../db/postgres/schema.js";
-import { getOrgMembership, isOrgOwner } from "../../lib/access.js";
+import { getOrgMembership } from "../../lib/access.js";
interface CancellationFeedbackBody {
organizationId: string;
@@ -45,7 +46,7 @@ export async function submitCancellationFeedback(
// Verify user has permission (owner only)
const membership = await getOrgMembership(userId, organizationId);
- if (!isOrgOwner(membership)) {
+ if (!roleHasPermission(membership?.role, "billing:manage")) {
return reply.status(403).send({
error: "Only organization owners can submit cancellation feedback",
});
diff --git a/server/src/api/stripe/updateSubscription.ts b/server/src/api/stripe/updateSubscription.ts
index f2b54846c..6fcea5504 100644
--- a/server/src/api/stripe/updateSubscription.ts
+++ b/server/src/api/stripe/updateSubscription.ts
@@ -1,9 +1,10 @@
+import { roleHasPermission } from "@rybbit/shared";
import { FastifyReply, FastifyRequest } from "fastify";
import { stripe } from "../../lib/stripe.js";
import { db } from "../../db/postgres/postgres.js";
import { organization } from "../../db/postgres/schema.js";
import { eq } from "drizzle-orm";
-import { getOrgMembership, isOrgOwner } from "../../lib/access.js";
+import { getOrgMembership } from "../../lib/access.js";
import Stripe from "stripe";
import { invalidateStripeSubscriptionCache } from "../../lib/subscriptionUtils.js";
@@ -33,7 +34,7 @@ export async function updateSubscription(
// 1. Verify user has permission to manage billing for this organization
const membership = await getOrgMembership(userId, organizationId);
- if (!isOrgOwner(membership)) {
+ if (!roleHasPermission(membership?.role, "billing:manage")) {
return reply.status(403).send({
error: "Only organization owners can manage billing",
});
diff --git a/server/src/api/teams/createTeam.ts b/server/src/api/teams/createTeam.ts
index a9b38b2d6..3c5e3fe65 100644
--- a/server/src/api/teams/createTeam.ts
+++ b/server/src/api/teams/createTeam.ts
@@ -1,3 +1,4 @@
+import { isSiteGrantRole, SITE_GRANT_ROLES } from "@rybbit/shared";
import { eq, and, inArray } from "drizzle-orm";
import { FastifyReply, FastifyRequest } from "fastify";
import { db } from "../../db/postgres/postgres.js";
@@ -9,6 +10,8 @@ interface CreateTeamBody {
name: string;
memberUserIds?: string[];
siteIds?: number[];
+ /** Role the team's members get on its sites (editor, member or viewer); omit or null for each member's organization role. */
+ siteRole?: string | null;
}
export async function createTeam(
@@ -26,6 +29,11 @@ export async function createTeam(
return reply.status(400).send({ error: "Team name is required" });
}
+ const siteRole = request.body.siteRole ?? null;
+ if (siteRole !== null && !isSiteGrantRole(siteRole)) {
+ return reply.status(400).send({ error: `siteRole must be one of: ${SITE_GRANT_ROLES.join(", ")}` });
+ }
+
try {
// Validate memberUserIds are org members
if (memberUserIds && memberUserIds.length > 0) {
@@ -90,6 +98,7 @@ export async function createTeam(
siteIds.map(siteId => ({
teamId,
siteId,
+ role: siteRole,
}))
);
}
@@ -110,6 +119,7 @@ export async function createTeam(
updatedAt: now,
members: memberUserIds || [],
siteIds: siteIds || [],
+ siteRole,
});
} catch (error) {
request.log.error({ err: error }, "Error creating team");
diff --git a/server/src/api/teams/listTeams.ts b/server/src/api/teams/listTeams.ts
index 3f9d78e99..990446bce 100644
--- a/server/src/api/teams/listTeams.ts
+++ b/server/src/api/teams/listTeams.ts
@@ -1,8 +1,9 @@
+import { roleHasPermission } from "@rybbit/shared";
import { eq, inArray } from "drizzle-orm";
import { FastifyReply, FastifyRequest } from "fastify";
import { db } from "../../db/postgres/postgres.js";
import { team, teamMember, teamSiteAccess, sites, user } from "../../db/postgres/schema.js";
-import { getOrgMembership, isOrgAdmin } from "../../lib/access.js";
+import { effectiveOrgRole, getOrgMembership } from "../../lib/access.js";
import { getUserIdFromRequest } from "../../lib/auth-utils.js";
export async function listTeams(
@@ -15,8 +16,11 @@ export async function listTeams(
const { organizationId } = request.params;
const userId = request.user?.id ?? (await getUserIdFromRequest(request));
- // Get user's membership in this org
- const isAdminOrOwner = isOrgAdmin(await getOrgMembership(userId, organizationId));
+ // Team managers see every team; everyone else sees the teams they are on.
+ const isAdminOrOwner = roleHasPermission(
+ effectiveOrgRole(await getOrgMembership(userId, organizationId)),
+ "teams:manage"
+ );
// Get all teams in the org
let teamsData = await db.select().from(team).where(eq(team.organizationId, organizationId));
@@ -56,6 +60,7 @@ export async function listTeams(
siteId: sites.siteId,
domain: sites.domain,
name: sites.name,
+ role: teamSiteAccess.role,
})
.from(teamSiteAccess)
.innerJoin(sites, eq(teamSiteAccess.siteId, sites.siteId))
@@ -74,12 +79,18 @@ export async function listTeams(
membersMap.set(m.teamId, existing);
}
- const sitesMap = new Map<string, { siteId: number; domain: string; name: string }[]>();
+ const sitesMap = new Map<string, { siteId: number; domain: string; name: string; role: string | null }[]>();
for (const s of sitesData) {
const existing = sitesMap.get(s.teamId) || [];
- existing.push({ siteId: s.siteId, domain: s.domain, name: s.name });
+ existing.push({ siteId: s.siteId, domain: s.domain, name: s.name, role: s.role });
sitesMap.set(s.teamId, existing);
}
+ // The role every one of a team's site grants carries; null when they carry
+ // none (each member's organization role applies) or differ.
+ const sharedSiteRole = (teamId: string) => {
+ const roles = new Set((sitesMap.get(teamId) || []).map(site => site.role));
+ return roles.size === 1 ? [...roles][0] : null;
+ };
return reply.send({
teams: teamsData.map(t => ({
@@ -90,6 +101,7 @@ export async function listTeams(
updatedAt: t.updatedAt,
members: membersMap.get(t.id) || [],
sites: sitesMap.get(t.id) || [],
+ siteRole: sharedSiteRole(t.id),
})),
});
} catch (error) {
diff --git a/server/src/api/teams/teams.test.ts b/server/src/api/teams/teams.test.ts
index fedea1f9f..88f322f84 100644
--- a/server/src/api/teams/teams.test.ts
+++ b/server/src/api/teams/teams.test.ts
@@ -69,6 +69,7 @@ CREATE TABLE "team_site_access" (
"id" serial PRIMARY KEY,
"team_id" text NOT NULL REFERENCES "team"("id") ON DELETE CASCADE,
"site_id" integer NOT NULL REFERENCES "sites"("site_id") ON DELETE CASCADE,
+ "role" text,
"created_at" timestamp NOT NULL DEFAULT now(),
UNIQUE ("team_id", "site_id")
);
@@ -169,6 +170,25 @@ describe("createTeam", () => {
expect(mocks.invalidateSitesAccessCache.mock.calls).toEqual([["member_1"], ["member_2"]]);
});
+ it("gives the team's site grants the requested role", async () => {
+ const reply = replyStub();
+
+ await createTeam(requestStub({ body: { name: "Clients", siteIds: [1], siteRole: "editor" } }), reply);
+
+ expect(reply.statusCode).toBe(201);
+ expect(reply.body).toMatchObject({ siteRole: "editor" });
+ expect(await rows(`SELECT site_id, role FROM team_site_access`)).toEqual([{ site_id: 1, role: "editor" }]);
+ });
+
+ it("refuses a team site role above editor", async () => {
+ const reply = replyStub();
+
+ await createTeam(requestStub({ body: { name: "Clients", siteIds: [1], siteRole: "owner" } }), reply);
+
+ expect(reply.statusCode).toBe(400);
+ expect(await rows(`SELECT * FROM team`)).toEqual([]);
+ });
+
it("rejects blank names before querying or writing", async () => {
const reply = replyStub();
const selectSpy = vi.spyOn(db, "select");
@@ -258,8 +278,8 @@ describe("listTeams", () => {
{ userId: "member_2", userName: "Member Two", userEmail: "[email protected]" },
]),
sites: expect.arrayContaining([
- { siteId: 1, domain: "a.example.com", name: "One A" },
- { siteId: 2, domain: "b.example.com", name: "One B" },
+ { siteId: 1, domain: "a.example.com", name: "One A", role: null },
+ { siteId: 2, domain: "b.example.com", name: "One B", role: null },
]),
}),
expect.objectContaining({
@@ -349,6 +369,35 @@ describe("updateTeam", () => {
expect(mocks.invalidateSitesAccessCache.mock.calls).toEqual(expect.arrayContaining([["member_1"], ["member_2"]]));
});
+ it("keeps the team's site role when its sites are replaced", async () => {
+ await (pgClient as any).exec(`UPDATE team_site_access SET role = 'viewer' WHERE team_id = 'team_a'`);
+ const reply = replyStub();
+
+ await updateTeam(
+ requestStub({ params: { organizationId: "org_1", teamId: "team_a" }, body: { siteIds: [1, 2] } }),
+ reply
+ );
+
+ expect(reply.statusCode).toBe(200);
+ expect(await rows(`SELECT site_id, role FROM team_site_access ORDER BY site_id`)).toEqual([
+ { site_id: 1, role: "viewer" },
+ { site_id: 2, role: "viewer" },
+ ]);
+ });
+
+ it("changes the site role alone, and refreshes the members' access", async () => {
+ const reply = replyStub();
+
+ await updateTeam(
+ requestStub({ params: { organizationId: "org_1", teamId: "team_a" }, body: { siteRole: "editor" } }),
+ reply
+ );
+
+ expect(reply.statusCode).toBe(200);
+ expect(await rows(`SELECT site_id, role FROM team_site_access`)).toEqual([{ site_id: 1, role: "editor" }]);
+ expect(mocks.invalidateSitesAccessCache).toHaveBeenCalledWith("member_1");
+ });
+
it("preserves members and sites when those fields are omitted", async () => {
const reply = replyStub();
diff --git a/server/src/api/teams/updateTeam.ts b/server/src/api/teams/updateTeam.ts
index 04b5e4e41..b42e0b8d9 100644
--- a/server/src/api/teams/updateTeam.ts
+++ b/server/src/api/teams/updateTeam.ts
@@ -1,3 +1,4 @@
+import { isSiteGrantRole, SITE_GRANT_ROLES } from "@rybbit/shared";
import { eq, and, inArray } from "drizzle-orm";
import { FastifyReply, FastifyRequest } from "fastify";
import { db } from "../../db/postgres/postgres.js";
@@ -9,6 +10,8 @@ interface UpdateTeamBody {
name?: string;
memberUserIds?: string[];
siteIds?: number[];
+ /** Role the team's members get on its sites (editor, member or viewer); null for each member's organization role; omit to keep. */
+ siteRole?: string | null;
}
export async function updateTeam(
@@ -19,9 +22,13 @@ export async function updateTeam(
reply: FastifyReply
) {
const { organizationId, teamId } = request.params;
- const { name, siteIds } = request.body;
+ const { name, siteIds, siteRole } = request.body;
const memberUserIds = request.body.memberUserIds === undefined ? undefined : [...new Set(request.body.memberUserIds)];
+ if (siteRole !== undefined && siteRole !== null && !isSiteGrantRole(siteRole)) {
+ return reply.status(400).send({ error: `siteRole must be one of: ${SITE_GRANT_ROLES.join(", ")}` });
+ }
+
try {
// Verify team belongs to org
const teamRecord = await db
@@ -98,17 +105,30 @@ export async function updateTeam(
}
}
- // Replace sites if provided
+ // Replace sites if provided, keeping the team's site role unless a new
+ // one was given.
if (siteIds !== undefined) {
+ let role: string | null = siteRole ?? null;
+ if (siteRole === undefined) {
+ const [current] = await tx
+ .select({ role: teamSiteAccess.role })
+ .from(teamSiteAccess)
+ .where(eq(teamSiteAccess.teamId, teamId))
+ .limit(1);
+ role = current?.role ?? null;
+ }
await tx.delete(teamSiteAccess).where(eq(teamSiteAccess.teamId, teamId));
if (siteIds.length > 0) {
await tx.insert(teamSiteAccess).values(
siteIds.map(siteId => ({
teamId,
siteId,
+ role,
}))
);
}
+ } else if (siteRole !== undefined) {
+ await tx.update(teamSiteAccess).set({ role: siteRole }).where(eq(teamSiteAccess.teamId, teamId));
}
});
diff --git a/server/src/api/user/addUserToOrganization.ts b/server/src/api/user/addUserToOrganization.ts
index 059b470ad..aae3dd58d 100644
--- a/server/src/api/user/addUserToOrganization.ts
+++ b/server/src/api/user/addUserToOrganization.ts
@@ -3,7 +3,10 @@ import { FastifyReply, FastifyRequest } from "fastify";
import { db } from "../../db/postgres/postgres.js";
import { member, user } from "../../db/postgres/schema.js";
import { randomBytes } from "crypto";
-import { getOrgMembership, isOrgAdmin } from "../../lib/access.js";
+import { canAssignRole, isOrgRole, ORG_ROLES, roleHasPermission } from "@rybbit/shared";
+import { getOrgMembership } from "../../lib/access.js";
+import { getPlanMemberLimit, memberLimitError } from "../../lib/memberLimits.js";
+import { withOrganizationSiteLock } from "../../services/sites/withOrganizationSiteLock.js";
import { getIsUserAdmin } from "../../lib/auth-utils.js";
function generateId(len = 32) {
@@ -40,7 +43,7 @@ export async function addUserToOrganization(request: FastifyRequest<AddUserToOrg
return reply.status(401).send({ error: "Unauthorized" });
}
callerMembership = await getOrgMembership(userId, organizationId);
- if (!isOrgAdmin(callerMembership)) {
+ if (!roleHasPermission(callerMembership?.role, "members:manage")) {
return reply.status(401).send({ error: "Unauthorized" });
}
}
@@ -52,17 +55,17 @@ export async function addUserToOrganization(request: FastifyRequest<AddUserToOrg
});
}
- if (role !== "admin" && role !== "member" && role !== "owner") {
+ if (!isOrgRole(role)) {
return reply.status(400).send({
- error: "Role must be either admin, member, or owner",
+ error: `Role must be one of: ${ORG_ROLES.join(", ")}`,
});
}
- // Only an organization owner (or a system admin) may grant the owner role.
- // Otherwise an org admin could mint an owner β€” an account with higher
- // privileges than their own β€” which is a privilege-escalation path.
- if (role === "owner" && !isAdmin && callerMembership?.role !== "owner") {
- return reply.status(403).send({ error: "Only an organization owner can assign the owner role" });
+ // Nobody but a system admin grants a role above their own (only owners make
+ // owners). Otherwise an org admin could mint an owner β€” an account with
+ // higher privileges than their own β€” which is a privilege-escalation path.
+ if (!isAdmin && !canAssignRole(callerMembership?.role, role)) {
+ return reply.status(403).send({ error: "You cannot assign a role above your own" });
}
const foundUser = await db.query.user.findFirst({
@@ -82,15 +85,27 @@ export async function addUserToOrganization(request: FastifyRequest<AddUserToOrg
return reply.status(400).send({ error: "User is already a member of this organization" });
}
- await db.insert(member).values([
- {
- userId: foundUser.id,
- organizationId: organizationId,
- role: role,
- id: generateId(),
- createdAt: new Date().toISOString(),
- },
- ]);
+ // Count and insert under the organization's row lock, so concurrent adds
+ // can't both take the last seat. (The plan's limit is looked up first:
+ // the locked transaction must not wait on a second connection.)
+ const memberLimit = await getPlanMemberLimit(organizationId);
+ const limitReached = await withOrganizationSiteLock(organizationId, async tx => {
+ const limitError = await memberLimitError(organizationId, memberLimit, tx);
+ if (limitError) return limitError;
+ await tx.insert(member).values([
+ {
+ userId: foundUser.id,
+ organizationId: organizationId,
+ role: role,
+ id: generateId(),
+ createdAt: new Date().toISOString(),
+ },
+ ]);
+ return null;
+ });
+ if (limitReached) {
+ return reply.status(403).send({ error: limitReached });
+ }
return reply.status(201).send({
message: "User added to organization successfully",
diff --git a/server/src/api/user/createOrgApiKey.ts b/server/src/api/user/createOrgApiKey.ts
index 8b68af824..087598461 100644
--- a/server/src/api/user/createOrgApiKey.ts
+++ b/server/src/api/user/createOrgApiKey.ts
@@ -34,7 +34,7 @@ export async function createOrgApiKey(
// 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
+ // (requireOrgPermission("apikeys:manage"), 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;
diff --git a/server/src/api/user/createUserInOrganization.ts b/server/src/api/user/createUserInOrganization.ts
index bd2a71a57..d9a8af215 100644
--- a/server/src/api/user/createUserInOrganization.ts
+++ b/server/src/api/user/createUserInOrganization.ts
@@ -4,7 +4,10 @@ import { randomBytes } from "crypto";
import { db } from "../../db/postgres/postgres.js";
import { member } from "../../db/postgres/schema.js";
import { auth } from "../../lib/auth.js";
-import { getOrgMembership, isOrgAdmin } from "../../lib/access.js";
+import { canAssignRole, isOrgRole, ORG_ROLES, roleHasPermission } from "@rybbit/shared";
+import { getOrgMembership } from "../../lib/access.js";
+import { getMemberLimitError, getPlanMemberLimit, memberLimitError } from "../../lib/memberLimits.js";
+import { withOrganizationSiteLock } from "../../services/sites/withOrganizationSiteLock.js";
import { getIsUserAdmin } from "../../lib/auth-utils.js";
function generateId(len = 32) {
@@ -52,7 +55,7 @@ export async function createUserInOrganization(request: FastifyRequest<CreateUse
return reply.status(401).send({ error: "Unauthorized" });
}
callerMembership = await getOrgMembership(userId, organizationId);
- if (!isOrgAdmin(callerMembership)) {
+ if (!roleHasPermission(callerMembership?.role, "members:manage")) {
return reply.status(401).send({ error: "Unauthorized" });
}
}
@@ -64,15 +67,15 @@ export async function createUserInOrganization(request: FastifyRequest<CreateUse
const email = rawEmail.toLowerCase();
- if (role !== "admin" && role !== "member" && role !== "owner") {
- return reply.status(400).send({ error: "Role must be either admin, member, or owner" });
+ if (!isOrgRole(role)) {
+ return reply.status(400).send({ error: `Role must be one of: ${ORG_ROLES.join(", ")}` });
}
- // Only an organization owner (or a system admin) may create an owner β€” minting
- // an account with higher privileges than an org admin's own is a
- // privilege-escalation path.
- if (role === "owner" && !isAdmin && callerMembership?.role !== "owner") {
- return reply.status(403).send({ error: "Only an organization owner can assign the owner role" });
+ // Nobody but a system admin creates a user with a role above their own (only
+ // owners make owners) β€” minting an account with higher privileges than an
+ // org admin's own is a privilege-escalation path.
+ if (!isAdmin && !canAssignRole(callerMembership?.role, role)) {
+ return reply.status(403).send({ error: "You cannot assign a role above your own" });
}
if (password.length < 8) {
@@ -85,6 +88,14 @@ export async function createUserInOrganization(request: FastifyRequest<CreateUse
return reply.status(400).send({ error: "A user with this email already exists" });
}
+ // Checked before the account is created, so a full organization usually
+ // never leaves behind a user who belongs nowhere; re-checked under the
+ // organization's lock when the membership is written.
+ const earlyLimitError = await getMemberLimitError(organizationId);
+ if (earlyLimitError) {
+ return reply.status(403).send({ error: earlyLimitError });
+ }
+
// Create the user + credential account (mirrors better-auth's admin createUser)
const createdUser = await ctx.internalAdapter.createUser(
{
@@ -107,16 +118,28 @@ export async function createUserInOrganization(request: FastifyRequest<CreateUse
userId: createdUser.id,
});
- // Add the new user to the organization
- await db.insert(member).values([
- {
- userId: createdUser.id,
- organizationId: organizationId,
- role: role,
- id: generateId(),
- createdAt: new Date().toISOString(),
- },
- ]);
+ // Add the new user to the organization, re-counting under the
+ // organization's row lock so concurrent creates can't both take the last
+ // seat. The loser's just-created account is removed again.
+ const memberLimit = await getPlanMemberLimit(organizationId);
+ const limitReached = await withOrganizationSiteLock(organizationId, async tx => {
+ const limitError = await memberLimitError(organizationId, memberLimit, tx);
+ if (limitError) return limitError;
+ await tx.insert(member).values([
+ {
+ userId: createdUser.id,
+ organizationId: organizationId,
+ role: role,
+ id: generateId(),
+ createdAt: new Date().toISOString(),
+ },
+ ]);
+ return null;
+ });
+ if (limitReached) {
+ await ctx.internalAdapter.deleteUser(createdUser.id);
+ return reply.status(403).send({ error: limitReached });
+ }
return reply.status(201).send({ message: "User created and added to organization successfully" });
} catch (error: any) {
diff --git a/server/src/api/user/getMyOrganizations.ts b/server/src/api/user/getMyOrganizations.ts
index 0858d3d1c..8db86a5cf 100644
--- a/server/src/api/user/getMyOrganizations.ts
+++ b/server/src/api/user/getMyOrganizations.ts
@@ -1,3 +1,4 @@
+import { isAdminRole, isOrgRole } from "@rybbit/shared";
import { FastifyRequest, FastifyReply } from "fastify";
import { db } from "../../db/postgres/postgres.js";
import { eq } from "drizzle-orm";
@@ -108,7 +109,10 @@ export const getMyOrganizations = async (request: FastifyRequest, reply: Fastify
// and teams. Admins/owners see everything.
let organizationSites = allOrgSites;
- if (callerMemberRecord?.role === "member") {
+ if (callerMemberRecord && !isOrgRole(callerMemberRecord.role)) {
+ // A role Rybbit doesn't know reaches nothing.
+ organizationSites = [];
+ } else if (callerMemberRecord && !isAdminRole(callerMemberRecord.role)) {
// getOrgMembership null-guards a missing userId, so a non-null
// callerMemberRecord here means userId was set.
organizationSites = await filterSitesByMemberAccess(
diff --git a/server/src/api/user/getUserOrganizations.ts b/server/src/api/user/getUserOrganizations.ts
index dda4c886f..263335888 100644
--- a/server/src/api/user/getUserOrganizations.ts
+++ b/server/src/api/user/getUserOrganizations.ts
@@ -1,7 +1,10 @@
+import { assignableRoles, higherRole, permissionsForRole } from "@rybbit/shared";
import { FastifyRequest, FastifyReply } from "fastify";
import { db } from "../../db/postgres/postgres.js";
import { eq } from "drizzle-orm";
import { member, organization } from "../../db/postgres/schema.js";
+import { effectiveOrgRole } from "../../lib/access.js";
+import { getIsUserAdmin } from "../../lib/auth-utils.js";
export const getUserOrganizations = async (request: FastifyRequest, reply: FastifyReply) => {
try {
@@ -19,12 +22,34 @@ export const getUserOrganizations = async (request: FastifyRequest, reply: Fasti
createdAt: organization.createdAt,
metadata: organization.metadata,
role: member.role,
+ hasRestrictedSiteAccess: member.hasRestrictedSiteAccess,
})
.from(member)
.innerJoin(organization, eq(member.organizationId, organization.id))
.where(eq(member.userId, userId));
- return reply.send(userOrganizations);
+ // The same role the organization guards use: a system-admin browser
+ // session acts as admin in every organization it belongs to.
+ const isSystemAdmin = !request.bearerAuth && (await getIsUserAdmin(request));
+
+ return reply.send(
+ userOrganizations.map(({ hasRestrictedSiteAccess, ...org }) => {
+ // A member restricted to specific sites is a viewer at the organization
+ // level; their role applies on the sites they were granted.
+ const orgRole = higherRole(
+ effectiveOrgRole({ role: org.role, hasRestrictedSiteAccess }),
+ isSystemAdmin ? "admin" : null
+ );
+ return {
+ ...org,
+ // What the caller's role allows in the organization. Site grants and
+ // teams can add to it on individual sites (see each site's permissions).
+ permissions: permissionsForRole(orgRole),
+ // Roles the caller may give when inviting or editing members.
+ assignableRoles: assignableRoles(orgRole),
+ };
+ })
+ );
} catch (error) {
request.log.error({ err: error }, "Error fetching user organizations");
return reply.status(500).send("Failed to fetch user organizations");
diff --git a/server/src/api/user/listOrganizationMembers.ts b/server/src/api/user/listOrganizationMembers.ts
index 76ac4e55c..9a8a197ec 100644
--- a/server/src/api/user/listOrganizationMembers.ts
+++ b/server/src/api/user/listOrganizationMembers.ts
@@ -43,6 +43,7 @@ export async function listOrganizationMembers(
.select({
memberId: memberSiteAccess.memberId,
siteId: memberSiteAccess.siteId,
+ role: memberSiteAccess.role,
})
.from(memberSiteAccess)
.where(inArray(memberSiteAccess.memberId, memberIds))
@@ -62,11 +63,21 @@ export async function listOrganizationMembers(
// Create maps for quick lookup
const siteIdsMap = new Map<string, number[]>();
+ const siteRolesMap = new Map<string, Set<string | null>>();
for (const record of siteAccessRecords) {
const existing = siteIdsMap.get(record.memberId) || [];
existing.push(record.siteId);
siteIdsMap.set(record.memberId, existing);
+ const roles = siteRolesMap.get(record.memberId) || new Set();
+ roles.add(record.role);
+ siteRolesMap.set(record.memberId, roles);
}
+ // The role every one of a member's grants carries; null when they carry
+ // none (the member's organization role applies) or differ.
+ const sharedSiteRole = (memberId: string) => {
+ const roles = siteRolesMap.get(memberId);
+ return roles?.size === 1 ? [...roles][0] : null;
+ };
const teamsMap = new Map<string, { id: string; name: string }[]>();
for (const record of teamMemberships) {
@@ -92,6 +103,7 @@ export async function listOrganizationMembers(
siteAccess: {
hasRestrictedSiteAccess: m.hasRestrictedSiteAccess,
siteIds: siteIdsMap.get(m.id) || [],
+ siteRole: sharedSiteRole(m.id),
},
teams: teamsMap.get(m.userId) || [],
})),
diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.ts
index af39e7a17..a0fa79f7f 100644
--- a/server/src/db/postgres/schema.ts
+++ b/server/src/db/postgres/schema.ts
@@ -273,6 +273,8 @@ export const invitation = pgTable("invitation", {
// Site access restriction for the invited member
hasRestrictedSiteAccess: boolean("has_restricted_site_access").default(false).notNull(),
siteIds: jsonb("site_ids").default([]).$type<number[]>(), // Array of site IDs to grant access to
+ // Raises the invited role on those sites (editor, member or viewer); null = no raise
+ siteRole: text("site_role"),
teamId: text().references(() => team.id, { onDelete: "set null" }),
});
@@ -288,6 +290,8 @@ export const memberSiteAccess = pgTable(
siteId: integer("site_id")
.notNull()
.references(() => sites.siteId, { onDelete: "cascade" }),
+ // Raises the member's role on this site (editor, member or viewer); null or lower = their organization role
+ role: text("role"),
createdAt: timestamp("created_at", { mode: "string" }).defaultNow().notNull(),
createdBy: text("created_by").references(() => user.id, { onDelete: "set null" }),
},
@@ -328,6 +332,8 @@ export const teamSiteAccess = pgTable(
siteId: integer("site_id")
.notNull()
.references(() => sites.siteId, { onDelete: "cascade" }),
+ // Raises the team members' role on this site (editor, member or viewer); null or lower = each one's organization role
+ role: text("role"),
createdAt: timestamp("created_at", { mode: "string" }).defaultNow().notNull(),
},
(table) => [
@@ -776,6 +782,29 @@ export const telemetry = pgTable("telemetry", {
});
// Google Search Console connections table
+// A pending hand-over of a site to someone outside its organization. The
+// site's admin names a recipient by email; the recipient accepts into an
+// organization they administer. The id is the secret in the emailed link. At
+// most one per site; the row is deleted when the transfer is accepted,
+// declined, cancelled or superseded, or when the site moves by other means.
+export const siteTransfers = pgTable(
+ "site_transfers",
+ {
+ id: text("id").primaryKey().notNull(),
+ siteId: integer("site_id")
+ .notNull()
+ .references(() => sites.siteId, { onDelete: "cascade" }),
+ sourceOrganizationId: text("source_organization_id")
+ .notNull()
+ .references(() => organization.id, { onDelete: "cascade" }),
+ recipientEmail: text("recipient_email").notNull(),
+ createdBy: text("created_by").references(() => user.id, { onDelete: "set null" }),
+ createdAt: timestamp("created_at", { mode: "string" }).defaultNow().notNull(),
+ expiresAt: timestamp("expires_at", { mode: "string" }).notNull(),
+ },
+ table => [unique("site_transfers_site_unique").on(table.siteId)]
+);
+
export const gscConnections = pgTable("gsc_connections", {
siteId: integer("site_id")
.primaryKey()
diff --git a/server/src/index.ts b/server/src/index.ts
index a119b6050..703b4342b 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -1,208 +1,19 @@
import cluster from "node:cluster";
-import { createHash } from "node:crypto";
import cors from "@fastify/cors";
import rateLimit from "@fastify/rate-limit";
import fastifyStatic from "@fastify/static";
import { toNodeHandler } from "better-auth/node";
-import Fastify, { type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify";
+import Fastify, { type FastifyRequest } from "fastify";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
-import {
- adminMoveSite,
- collectTelemetry,
- deleteAdminOrganizationMember,
- getAdminOrganizationMember,
- getAdminOrganizationOptions,
- getAdminOrganizations,
- getAdminSubscriptionPlans,
- getAdminServiceEventCount,
- getAdminSites,
- getClickhouseStats,
- getClickhouseQueryLog,
- updateAdminOrganizationMember,
- updateAdminSubscriptionOverride,
-} from "./api/admin/index.js";
-import {
- createAnnotation,
- createDashboard,
- createSegment,
- createFunnel,
- createGoal,
- deleteAnnotation,
- deleteDashboard,
- deleteSegment,
- deleteFunnel,
- deleteGoal,
- deleteUser,
- generatePdfReport,
- getAnnotations,
- getDashboard,
- getDashboards,
- getSegment,
- getSegments,
- getBotAiSummary,
- getBotDimension,
- getBotOverview,
- getBotTimeSeries,
- getErrorBucketed,
- getErrorEvents,
- getErrorNames,
- generateCustomQuery,
- getEventBucketed,
- getEventNames,
- getAutocaptureEvents,
- getAutocaptureValues,
- getEventProperties,
- getEvents,
- getFunnel,
- getFunnelStepSessions,
- getFunnels,
- getGoalSessions,
- getGoalTimeSeries,
- getGoals,
- getJourneys,
- getLiveUsercount,
- getMetric,
- getMetricLite,
- getOrgEventCount,
- getOutboundLinks,
- getOverview,
- getOverviewBucketed,
- getOverviewBucketedLite,
- getOverviewLite,
- getSiteCardsLite,
- getSiteCards,
- getPageTitles,
- getPerformanceByDimension,
- getPerformanceOverview,
- getPerformanceTimeSeries,
- getRetention,
- getSession,
- getSessionLocations,
- getSessions,
- getSiteEventCount,
- getUserInfo,
- getUserSessionCount,
- getUserTraitKeys,
- getUserTraitValueUsers,
- getUserTraitValues,
- getUsers,
- identifyUser,
- runCustomQuery,
- runDashboardCardQuery,
- updateAnnotation,
- updateDashboard,
- updateSegment,
- expandSegmentParam,
- updateGoal,
- updateUserTraits,
-} from "./api/analytics/index.js";
-import { getConfig, getVersion } from "./api/getConfig.js";
-import {
- createExperiment,
- deleteExperiment,
- getExperimentResults,
- getExperiments,
- updateExperiment,
-} from "./api/experiments/index.js";
-import {
- createFeatureFlag,
- deleteFeatureFlag,
- evaluateFeatureFlags,
- evaluateServerFeatureFlags,
- getFeatureFlags,
- updateFeatureFlag,
-} from "./api/featureFlags/index.js";
-import {
- connectGSC,
- disconnectGSC,
- getGSCData,
- getGSCStatus,
- gscCallback,
- selectGSCProperty,
-} from "./api/gsc/index.js";
-import { updateMemberSiteAccess } from "./api/memberAccess/index.js";
-import { listTeams, createTeam, updateTeam, deleteTeam } from "./api/teams/index.js";
-import {
- deleteSessionReplay,
- getSessionReplayEvents,
- getSessionReplays,
- recordSessionReplay,
-} from "./api/sessionReplay/index.js";
-import {
- addSite,
- batchImportEvents,
- claimSite,
- createUnclaimedSite,
- createSiteImport,
- deleteSite,
- deleteSiteImport,
- getEmbedStats,
- getSite,
- getSiteExcludedCountries,
- getSiteExcludedHostnames,
- getSiteExcludedIPs,
- getSiteExcludedPaths,
- getSiteExcludedUserAgents,
- getSiteExcludedASNs,
- getSiteExcludedQueryParams,
- getSiteHasData,
- checkInstall,
- getSiteImports,
- getSiteIsPublic,
- getSiteUsage,
- getSitePrivateLinkConfig,
- getSitesFromOrg,
- getTrackingConfig,
- moveSite,
- updateSiteConfig,
- updateSitePrivateLinkConfig,
-} from "./api/sites/index.js";
-import {
- createCheckoutSession,
- createPortalSession,
- getInvoices,
- getSubscription,
- handleWebhook,
- previewSubscriptionUpdate,
- submitCancellationFeedback,
- updateSubscription,
-} from "./api/stripe/index.js";
-import {
- addUserToOrganization,
- createOrgApiKey,
- createUserApiKey,
- createUserInOrganization,
- getMyOrganizations,
- getOrgApiUsage,
- getUserOrganizations,
- listOrganizationMembers,
- oneClickUnsubscribeMarketing,
- unsubscribeMarketing,
- updateAccountSettings,
-} from "./api/user/index.js";
-import { createDashboardCache } from "./api/analytics/utils/dashboardCache.js";
-import { validateHttpTimeParams } from "./api/analytics/utils/query-validation.js";
import { initializeClickhouse } from "./db/clickhouse/clickhouse.js";
-import { unclaimedSiteRouteOptions } from "./api/sites/createUnclaimedSite.js";
-import { apiRateLimitRedis, dashboardCacheRedis } from "./db/redis/redis.js";
+import { apiRateLimitRedis } from "./db/redis/redis.js";
import { initPostgres } from "./db/postgres/initPostgres.js";
-import {
- allowPublicSiteAccess,
- requireAdmin,
- requireAuth,
- requireOrgAdminFromParams,
- requireOrgMember,
- requireSiteAccess,
- requireSiteAdminAccess,
- resolveSiteId,
-} from "./lib/auth-middleware.js";
import { mapHeaders } from "./lib/auth-utils.js";
import { registerApiErrorResponses } from "./lib/api-errors.js";
-import type { ScopeAction, ScopeResource } from "./lib/scopes.js";
-import type { ScopeStatements } from "@rybbit/shared";
+import { apiRoutes } from "./api/routes.js";
+import type { OrgRole, ScopeStatements } from "@rybbit/shared";
import { auth } from "./lib/auth.js";
-import { mcpRoutes } from "./mcp/index.js";
import { oauthWellKnownRoutes } from "./mcp/wellKnown.js";
import { createCorsOptionsDelegate, createRejectUntrustedOriginHook } from "./lib/cors.js";
import { IS_CLOUD } from "./lib/const.js";
@@ -217,122 +28,6 @@ import { startSiteBaselineRefresh } from "./services/tracker/botBlocking/siteBas
import { usageService } from "./services/usageService.js";
import { unclaimedSiteCleanupService } from "./services/sites/unclaimedSiteCleanupService.js";
import { weeklyReportService } from "./services/weekyReports/weeklyReportService.js";
-import { handleAppSumoWebhook, activateAppSumoLicense } from "./api/as/index.js";
-
-// Reject requests whose shared time query params are present but invalid.
-// Historically they were silently dropped, so endpoints ran over all time and
-// returned wrong data with a 200. Absent params (all-time mode) stay valid.
-const validateTimeParams = async (request: FastifyRequest, reply: FastifyReply) => {
- const error = validateHttpTimeParams(request.query);
- if (error) {
- return reply.status(400).send({ error });
- }
-};
-
-// Pre-composed middleware chains for common auth patterns
-// Cast as any to work around Fastify's type inference limitations with preHandler
-//
-// Each scoped chain names the resource:action a BEARER credential (API key or
-// OAuth token) must be granted; unrestricted legacy credentials and cookie
-// sessions always pass. See lib/scopes.ts for the taxonomy.
-//
-// validateTimeParams is on every chain rather than only the ones that currently
-// host a time-taking route: absent params always pass, and the two chains that
-// went without it were how /org-event-count and /admin/service-event-count came
-// to answer a malformed date with all-time data and a 200.
-// expandSegmentParam turns a `segment_id` query param into `filters` after the
-// access guard has run, so every analytics endpoint accepts a saved segment
-// with no per-endpoint change. It is a no-op when the param is absent.
-const publicSiteScoped = (resource: ScopeResource, action: ScopeAction) => ({
- preHandler: [
- resolveSiteId,
- allowPublicSiteAccess({ resource, action }),
- validateTimeParams,
- expandSegmentParam,
- ] as any,
-});
-const authSiteScoped = (resource: ScopeResource, action: ScopeAction) => ({
- preHandler: [resolveSiteId, requireSiteAccess({ resource, action }), validateTimeParams, expandSegmentParam] as any,
-});
-const adminSiteScoped = (resource: ScopeResource, action: ScopeAction) => ({
- preHandler: [resolveSiteId, requireSiteAdminAccess({ resource, action }), validateTimeParams] as any,
-});
-const orgMemberScoped = (resource: ScopeResource, action: ScopeAction) => ({
- preHandler: [requireOrgMember({ resource, action }), validateTimeParams] as any,
-});
-const orgAdminScoped = (resource: ScopeResource, action: ScopeAction) => ({
- preHandler: [requireOrgAdminFromParams({ resource, action }), validateTimeParams] as any,
-});
-const authOnlyScoped = (resource: ScopeResource, action: ScopeAction) => ({
- preHandler: [requireAuth({ resource, action }), validateTimeParams] as any,
-});
-
-// Reused scoped chains
-const publicAnalyticsRead = publicSiteScoped("analytics", "read");
-const dashboardCacheSeconds = Number(process.env.DASHBOARD_CACHE_TTL_SECONDS ?? 30);
-const cacheDashboard = createDashboardCache({
- redis: dashboardCacheRedis,
- namespace: createHash("sha256")
- .update(JSON.stringify([process.env.CLICKHOUSE_HOST, process.env.CLICKHOUSE_DB]))
- .digest("hex"),
- ttlMs: (Number.isFinite(dashboardCacheSeconds) ? Math.max(0, Math.min(30, dashboardCacheSeconds)) : 30) * 1000,
-});
-const cachedAnalyticsRead = cacheDashboard(publicAnalyticsRead);
-const publicSessionsRead = publicSiteScoped("sessions", "read");
-const publicEventsRead = publicSiteScoped("events", "read");
-const cachedEventsRead = cacheDashboard(publicEventsRead);
-const publicUsersRead = publicSiteScoped("users", "read");
-const publicFunnelsRead = publicSiteScoped("funnels", "read");
-const publicGoalsRead = publicSiteScoped("goals", "read");
-const publicSitesRead = publicSiteScoped("sites", "read");
-const publicReplayRead = publicSiteScoped("replay", "read");
-const publicGscRead = publicSiteScoped("gsc", "read");
-const authUsersWrite = authSiteScoped("users", "write");
-const authGoalsWrite = authSiteScoped("goals", "write");
-const authFunnelsWrite = authSiteScoped("funnels", "write");
-const authAnalyticsRead = authSiteScoped("analytics", "read");
-const authReplayWrite = authSiteScoped("replay", "write");
-const authOrgRead = authOnlyScoped("org", "read");
-const adminSitesRead = adminSiteScoped("sites", "read");
-// Annotations validate their own optional start/end bounds (either may stand
-// alone), so the shared time validator is left off this chain.
-const publicAnnotationsRead = {
- preHandler: [resolveSiteId, allowPublicSiteAccess({ resource: "annotations", action: "read" })] as any,
-};
-const authAnnotationsWrite = authSiteScoped("annotations", "write");
-const authDashboardsRead = authSiteScoped("dashboards", "read");
-const authDashboardsWrite = authSiteScoped("dashboards", "write");
-const publicSegmentsRead = publicSiteScoped("segments", "read");
-const authSegmentsWrite = authSiteScoped("segments", "write");
-const authFlagsRead = authSiteScoped("flags", "read");
-const authExperimentsRead = authSiteScoped("experiments", "read");
-const authSitesRead = authSiteScoped("sites", "read");
-const adminUsersWrite = adminSiteScoped("users", "write");
-const adminFlagsWrite = adminSiteScoped("flags", "write");
-const adminExperimentsWrite = adminSiteScoped("experiments", "write");
-const adminSitesWrite = adminSiteScoped("sites", "write");
-const adminGscWrite = adminSiteScoped("gsc", "write");
-const orgAnalyticsRead = orgMemberScoped("analytics", "read");
-const orgSqlRead = orgMemberScoped("sql", "read");
-
-// User-authored SQL fans out real ClickHouse work per call (a dashboard runs
-// one query per card), and /generate spends OpenRouter credit. Cap per user.
-const customQueryRateLimit = { max: 60, timeWindow: "1 minute" };
-const generateQueryRateLimit = { max: 20, timeWindow: "1 minute" };
-const withRateLimit = <T extends { preHandler: unknown }>(opts: T, limit: { max: number; timeWindow: string }) => ({
- ...opts,
- config: { rateLimit: limit },
-});
-const orgOrgRead = orgMemberScoped("org", "read");
-const orgAdminSitesWrite = orgAdminScoped("sites", "write");
-const orgAdminOrgWrite = orgAdminScoped("org", "write");
-const authOrgWrite = authOnlyScoped("org", "write");
-
-// Scope-exempt / non-bearer chains. "deny-scoped" rejects scoped credentials
-// on surfaces with no taxonomy resource (account settings, billing).
-const adminOnly = { preHandler: [requireAdmin, validateTimeParams] 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);
@@ -431,256 +126,6 @@ server.get("/api/script.js", async (_, reply) => reply.sendFile("script.js", { m
server.get("/api/replay.js", async (_, reply) => reply.sendFile("rrweb.min.js", { maxAge: "1d" }));
server.get("/api/metrics.js", async (_, reply) => reply.sendFile("web-vitals.iife.js", { maxAge: "1d" }));
-// Domain-specific route plugins
-async function analyticsRoutes(fastify: FastifyInstance) {
- // WEB & PRODUCT ANALYTICS
-
- // This endpoint gets called a lot so we don't want to log it
- fastify.get("/sites/:siteId/live-user-count", { logLevel: "silent", ...publicAnalyticsRead }, getLiveUsercount);
- fastify.get("/sites/:siteId/overview", cachedAnalyticsRead, getOverview);
- fastify.get("/sites/:siteId/overview/time-series", cachedAnalyticsRead, getOverviewBucketed);
- fastify.get("/sites/:siteId/overview-lite", cachedAnalyticsRead, getOverviewLite);
- fastify.get("/sites/:siteId/overview-bucketed-lite", cachedAnalyticsRead, getOverviewBucketedLite);
- fastify.get("/sites/:siteId/metric-lite", cachedAnalyticsRead, getMetricLite);
- fastify.get("/sites/:siteId/metric", cachedAnalyticsRead, getMetric);
- fastify.get("/sites/:siteId/page-titles", cachedAnalyticsRead, getPageTitles);
- fastify.get("/sites/:siteId/errors/names", publicAnalyticsRead, getErrorNames);
- fastify.get("/sites/:siteId/errors/events", publicAnalyticsRead, getErrorEvents);
- fastify.get("/sites/:siteId/errors/time-series", publicAnalyticsRead, getErrorBucketed);
- fastify.get("/sites/:siteId/retention", publicAnalyticsRead, getRetention);
- fastify.get("/sites/:siteId/has-data", publicSitesRead, getSiteHasData);
- fastify.get("/sites/:siteId/is-public", publicSitesRead, getSiteIsPublic);
- fastify.get("/sites/:siteId/sessions", publicSessionsRead, getSessions);
- fastify.get("/sites/:siteId/sessions/:sessionId", publicSessionsRead, getSession);
- fastify.get("/sites/:siteId/events", publicEventsRead, getEvents);
- fastify.get("/sites/:siteId/events/time-series", publicEventsRead, getEventBucketed);
- fastify.get("/sites/:siteId/events/count", publicEventsRead, getSiteEventCount);
- fastify.get("/sites/:siteId/users", publicUsersRead, getUsers);
-
- fastify.get("/sites/:siteId/users/session-count", publicUsersRead, getUserSessionCount);
- fastify.get("/sites/:siteId/users/:userId", publicUsersRead, getUserInfo);
- fastify.post("/sites/:siteId/users/identify", authUsersWrite, identifyUser);
- fastify.put("/sites/:siteId/users/:userId/traits", authUsersWrite, updateUserTraits);
- fastify.delete("/sites/:siteId/users/:userId", adminUsersWrite, deleteUser);
- fastify.get("/sites/:siteId/user-traits/keys", publicUsersRead, getUserTraitKeys);
- fastify.get("/sites/:siteId/user-traits/values", publicUsersRead, getUserTraitValues);
- fastify.get("/sites/:siteId/user-traits/users", publicUsersRead, getUserTraitValueUsers);
- fastify.get("/sites/:siteId/sessions/locations", publicSessionsRead, getSessionLocations);
- fastify.get("/sites/:siteId/funnels", publicFunnelsRead, getFunnels);
- fastify.get("/sites/:siteId/journeys", publicAnalyticsRead, getJourneys);
- fastify.post("/sites/:siteId/funnels/analyze", publicFunnelsRead, getFunnel);
- fastify.post("/sites/:siteId/funnels/:stepNumber/sessions", publicFunnelsRead, getFunnelStepSessions);
- fastify.post("/sites/:siteId/funnels", authFunnelsWrite, createFunnel);
- fastify.delete("/sites/:siteId/funnels/:funnelId", authFunnelsWrite, deleteFunnel);
- fastify.get("/sites/:siteId/goals", publicGoalsRead, getGoals);
- fastify.get("/sites/:siteId/goals/time-series", publicGoalsRead, getGoalTimeSeries);
- fastify.get("/sites/:siteId/goals/:goalId/sessions", publicGoalsRead, getGoalSessions);
- fastify.post("/sites/:siteId/goals", authGoalsWrite, createGoal);
- fastify.delete("/sites/:siteId/goals/:goalId", authGoalsWrite, deleteGoal);
- fastify.put("/sites/:siteId/goals/:goalId", authGoalsWrite, updateGoal);
- // Timeline annotations. Read is public-guarded so public dashboards and
- // private links get the annotations marked public; writes need site access.
- fastify.get("/sites/:siteId/annotations", publicAnnotationsRead, getAnnotations);
- fastify.post("/sites/:siteId/annotations", authAnnotationsWrite, createAnnotation);
- fastify.put("/sites/:siteId/annotations/:annotationId", authAnnotationsWrite, updateAnnotation);
- fastify.delete("/sites/:siteId/annotations/:annotationId", authAnnotationsWrite, deleteAnnotation);
- fastify.get("/sites/:siteId/dashboards", authDashboardsRead, getDashboards);
- fastify.get("/sites/:siteId/dashboards/:dashboardId", authDashboardsRead, getDashboard);
- fastify.post("/sites/:siteId/dashboards", authDashboardsWrite, createDashboard);
- fastify.put("/sites/:siteId/dashboards/:dashboardId", authDashboardsWrite, updateDashboard);
- fastify.delete("/sites/:siteId/dashboards/:dashboardId", authDashboardsWrite, deleteDashboard);
-
- // Saved segments. Reads allow public/private-link viewers (they only see
- // public segments); writes need site access and are further gated per row.
- fastify.get("/sites/:siteId/segments", publicSegmentsRead, getSegments);
- fastify.get("/sites/:siteId/segments/:segmentId", publicSegmentsRead, getSegment);
- fastify.post("/sites/:siteId/segments", authSegmentsWrite, createSegment);
- fastify.put("/sites/:siteId/segments/:segmentId", authSegmentsWrite, updateSegment);
- fastify.delete("/sites/:siteId/segments/:segmentId", authSegmentsWrite, deleteSegment);
- fastify.post(
- "/sites/:siteId/dashboards/run-card",
- withRateLimit(authDashboardsRead, customQueryRateLimit),
- runDashboardCardQuery
- );
- fastify.get("/sites/:siteId/feature-flags", authFlagsRead, getFeatureFlags);
- fastify.post("/sites/:siteId/feature-flags", adminFlagsWrite, createFeatureFlag);
- fastify.put("/sites/:siteId/feature-flags/:flagId", adminFlagsWrite, updateFeatureFlag);
- fastify.delete("/sites/:siteId/feature-flags/:flagId", adminFlagsWrite, deleteFeatureFlag);
- fastify.post("/sites/:siteId/feature-flags/evaluate", authFlagsRead, evaluateServerFeatureFlags);
- fastify.post("/site/:siteId/feature-flags/evaluate", evaluateFeatureFlags);
- fastify.get("/sites/:siteId/experiments", authExperimentsRead, getExperiments);
- fastify.post("/sites/:siteId/experiments", adminExperimentsWrite, createExperiment);
- fastify.put("/sites/:siteId/experiments/:experimentId", adminExperimentsWrite, updateExperiment);
- fastify.delete("/sites/:siteId/experiments/:experimentId", adminExperimentsWrite, deleteExperiment);
- fastify.get("/sites/:siteId/experiments/:experimentId/results", authExperimentsRead, getExperimentResults);
- fastify.get("/sites/:siteId/events/names", cachedEventsRead, getEventNames);
- fastify.get("/sites/:siteId/events/properties", publicEventsRead, getEventProperties);
- fastify.get("/sites/:siteId/events/autocapture", cachedEventsRead, getAutocaptureEvents);
- fastify.get("/sites/:siteId/events/autocapture-values", publicEventsRead, getAutocaptureValues);
- fastify.get("/sites/:siteId/events/outbound", cachedEventsRead, getOutboundLinks);
- fastify.get("/org-event-count/:organizationId", orgAnalyticsRead, getOrgEventCount);
- fastify.post(
- "/organizations/:organizationId/analytics/query",
- withRateLimit(orgSqlRead, customQueryRateLimit),
- runCustomQuery
- );
- fastify.post(
- "/organizations/:organizationId/analytics/query/generate",
- withRateLimit(orgSqlRead, generateQueryRateLimit),
- generateCustomQuery
- );
- fastify.get("/sites/:siteId/performance/overview", publicAnalyticsRead, getPerformanceOverview);
- fastify.get("/sites/:siteId/performance/time-series", publicAnalyticsRead, getPerformanceTimeSeries);
- fastify.get("/sites/:siteId/performance/by-dimension", publicAnalyticsRead, getPerformanceByDimension);
- fastify.get("/sites/:siteId/bots/overview", publicAnalyticsRead, getBotOverview);
- fastify.get("/sites/:siteId/bots/time-series", publicAnalyticsRead, getBotTimeSeries);
- fastify.get("/sites/:siteId/bots/by-dimension", publicAnalyticsRead, getBotDimension);
- fastify.get("/sites/:siteId/bots/ai-summary", publicAnalyticsRead, getBotAiSummary);
- fastify.get("/sites/:siteId/export/pdf", authAnalyticsRead, generatePdfReport);
-}
-
-async function sessionReplayRoutes(fastify: FastifyInstance) {
- // Session Replay
- fastify.post("/session-replay/record/:siteId", recordSessionReplay); // Public - tracking endpoint
- fastify.get("/sites/:siteId/session-replay/list", publicReplayRead, getSessionReplays);
- fastify.get("/sites/:siteId/session-replay/:sessionId", publicReplayRead, getSessionReplayEvents);
- fastify.delete("/sites/:siteId/session-replay/:sessionId", authReplayWrite, deleteSessionReplay);
-}
-
-async function sitesRoutes(fastify: FastifyInstance) {
- // Sites
- fastify.get("/sites/:siteId", publicSitesRead, getSite);
- fastify.put("/sites/:siteId/config", adminSitesWrite, updateSiteConfig);
- fastify.put("/sites/:siteId/move", adminSitesWrite, moveSite);
- fastify.delete("/sites/:siteId", adminSitesWrite, deleteSite);
- fastify.get("/sites/:siteId/private-link-config", adminSitesWrite, getSitePrivateLinkConfig);
- fastify.post("/sites/:siteId/private-link-config", adminSitesWrite, updateSitePrivateLinkConfig);
- fastify.get("/site/tracking-config/:siteId", getTrackingConfig); // Public - used by tracking script
- fastify.get("/site/check-install", checkInstall); // Public (HMAC-signed) - linked from lifecycle emails
- fastify.get("/sites/:siteId/embed-stats", { preHandler: [resolveSiteId] as any }, getEmbedStats); // Public - widget endpoint (handler checks site is public)
- fastify.get("/sites/:siteId/excluded-ips", authSitesRead, getSiteExcludedIPs);
- fastify.get("/sites/:siteId/excluded-countries", authSitesRead, getSiteExcludedCountries);
- fastify.get("/sites/:siteId/excluded-paths", authSitesRead, getSiteExcludedPaths);
- fastify.get("/sites/:siteId/excluded-hostnames", authSitesRead, getSiteExcludedHostnames);
- fastify.get("/sites/:siteId/excluded-user-agents", authSitesRead, getSiteExcludedUserAgents);
- fastify.get("/sites/:siteId/excluded-asns", authSitesRead, getSiteExcludedASNs);
- fastify.get("/sites/:siteId/excluded-query-params", authSitesRead, getSiteExcludedQueryParams);
-
- // Site Usage
- fastify.get("/sites/:siteId/usage", authSitesRead, getSiteUsage);
-
- // Site Imports
- fastify.get("/sites/:siteId/imports", adminSitesRead, getSiteImports);
- fastify.post("/sites/:siteId/imports", adminSitesWrite, createSiteImport);
- fastify.post(
- "/sites/:siteId/imports/:importId/events",
- { ...adminSitesWrite, bodyLimit: 50 * 1024 * 1024 },
- batchImportEvents
- );
- fastify.delete("/sites/:siteId/imports/:importId", adminSitesWrite, deleteSiteImport);
-}
-
-async function organizationsRoutes(fastify: FastifyInstance) {
- // Organizations
- fastify.get("/organizations", getMyOrganizations);
- fastify.get("/organizations/:organizationId/sites", orgOrgRead, getSitesFromOrg);
- fastify.post("/organizations/:organizationId/site-cards-lite", orgAnalyticsRead, getSiteCardsLite);
- fastify.post("/organizations/:organizationId/site-cards", orgAnalyticsRead, getSiteCards);
- fastify.post("/organizations/:organizationId/sites", orgAdminSitesWrite, addSite);
- // Landing-page domain input: creates an owner-less site reachable only by
- // its private link key. Public, so cap creations per IP.
- fastify.post("/sites/unclaimed", unclaimedSiteRouteOptions, createUnclaimedSite);
- fastify.post("/sites/:siteId/claim", { ...authOnlyScoped("sites", "write"), bodyLimit: 1024 }, claimSite);
- fastify.get("/organizations/:organizationId/members", orgOrgRead, listOrganizationMembers);
- fastify.post("/organizations/:organizationId/members", authOrgWrite, addUserToOrganization);
- fastify.post("/organizations/:organizationId/users", authOrgWrite, createUserInOrganization);
-
- // Member site access management (admin/owner only)
- fastify.put("/organizations/:organizationId/members/:memberId/sites", orgAdminOrgWrite, updateMemberSiteAccess);
-}
-
-async function teamsRoutes(fastify: FastifyInstance) {
- // Teams
- fastify.get("/organizations/:organizationId/teams", orgOrgRead, listTeams);
- fastify.post("/organizations/:organizationId/teams", orgAdminOrgWrite, createTeam);
- fastify.put("/organizations/:organizationId/teams/:teamId", orgAdminOrgWrite, updateTeam);
- fastify.delete("/organizations/:organizationId/teams/:teamId", orgAdminOrgWrite, deleteTeam);
-}
-
-async function userRoutes(fastify: FastifyInstance) {
- // User
- fastify.get("/config", getConfig); // Public - returns app config
- fastify.get("/version", getVersion); // Public - returns app version
- fastify.get("/user/organizations", authOrgRead, getUserOrganizations);
- fastify.post("/user/account-settings", authOnlyNoScopedKeys, updateAccountSettings);
- fastify.post("/user/unsubscribe-marketing", authOnlyNoScopedKeys, unsubscribeMarketing);
- fastify.get("/user/unsubscribe-marketing-oneclick", oneClickUnsubscribeMarketing); // Public - for link clicks
- fastify.post("/user/unsubscribe-marketing-oneclick", oneClickUnsubscribeMarketing); // Public - for List-Unsubscribe header
- fastify.post("/user/api-keys", authOnlyNoScopedKeys, createUserApiKey);
- fastify.post("/organizations/:organizationId/api-keys", orgAdminNoScopedKeys, createOrgApiKey);
- fastify.get("/organizations/:organizationId/api-usage", orgOrgRead, getOrgApiUsage);
-}
-
-async function gscRoutes(fastify: FastifyInstance) {
- // GOOGLE SEARCH CONSOLE
- fastify.get("/sites/:siteId/gsc/connect", adminGscWrite, connectGSC);
- fastify.get("/gsc/callback", gscCallback); // Public - OAuth callback
- fastify.get("/sites/:siteId/gsc/status", publicGscRead, getGSCStatus);
- fastify.delete("/sites/:siteId/gsc/disconnect", adminGscWrite, disconnectGSC);
- fastify.post("/sites/:siteId/gsc/select-property", adminGscWrite, selectGSCProperty);
- fastify.get("/sites/:siteId/gsc/data", publicGscRead, getGSCData);
-}
-
-async function stripeAdminRoutes(fastify: FastifyInstance) {
- // ClickHouse stats (available for all admins)
- fastify.get("/admin/clickhouse-stats", adminOnly, getClickhouseStats);
- fastify.get("/admin/clickhouse-query-log", adminOnly, getClickhouseQueryLog);
- fastify.get("/admin/sites", adminOnly, getAdminSites);
- fastify.put("/admin/sites/:siteId/move", adminOnly, adminMoveSite);
- fastify.get("/admin/organizations", adminOnly, getAdminOrganizations);
- fastify.get("/admin/organization-options", adminOnly, getAdminOrganizationOptions);
- fastify.get("/admin/subscription-plans", adminOnly, getAdminSubscriptionPlans);
- fastify.put("/admin/organizations/:organizationId/subscription-override", adminOnly, updateAdminSubscriptionOverride);
- fastify.get("/admin/organizations/:organizationId/members/:memberId", adminOnly, getAdminOrganizationMember);
- fastify.patch("/admin/organizations/:organizationId/members/:memberId", adminOnly, updateAdminOrganizationMember);
- fastify.delete("/admin/organizations/:organizationId/members/:memberId", adminOnly, deleteAdminOrganizationMember);
- fastify.get("/admin/service-event-count", adminOnly, getAdminServiceEventCount);
- fastify.post("/admin/telemetry", collectTelemetry); // Public - telemetry collection
-
- // STRIPE & ADMIN
- if (IS_CLOUD) {
- // Stripe Routes
- fastify.post("/stripe/create-checkout-session", authOnlyNoScopedKeys, createCheckoutSession);
- fastify.post("/stripe/create-portal-session", authOnlyNoScopedKeys, createPortalSession);
- fastify.post("/stripe/preview-subscription-update", authOnlyNoScopedKeys, previewSubscriptionUpdate);
- fastify.post("/stripe/update-subscription", authOnlyNoScopedKeys, updateSubscription);
- fastify.get("/stripe/subscription", authOnlyNoScopedKeys, getSubscription);
- fastify.get("/stripe/invoices", authOnlyNoScopedKeys, getInvoices);
- fastify.post("/stripe/cancellation-feedback", authOnlyNoScopedKeys, submitCancellationFeedback);
- fastify.post("/stripe/webhook", { config: { rawBody: true } }, handleWebhook); // Public - Stripe webhook
-
- // AppSumo Routes
- fastify.post("/as/activate", authOnlyNoScopedKeys, activateAppSumoLicense);
- fastify.post("/as/webhook", handleAppSumoWebhook); // Public - AppSumo webhook
- }
-}
-
-// Main API routes plugin - registers all domain plugins
-async function apiRoutes(fastify: FastifyInstance) {
- await fastify.register(analyticsRoutes);
- await fastify.register(sessionReplayRoutes);
- await fastify.register(sitesRoutes);
- await fastify.register(organizationsRoutes);
- await fastify.register(teamsRoutes);
- await fastify.register(userRoutes);
- await fastify.register(gscRoutes);
- await fastify.register(stripeAdminRoutes);
- await fastify.register(mcpRoutes);
-
- // Health check
- fastify.get("/health", { logLevel: "silent" }, (_: FastifyRequest, reply: FastifyReply) => reply.send("OK"));
-}
-
server.post("/api/track", trackEvent);
server.post("/api/identify", handleIdentify);
@@ -787,5 +232,7 @@ declare module "fastify" {
bearerAuth?: boolean;
/** Scope statements of that credential; null = unrestricted. */
bearerStatements?: ScopeStatements | null;
+ /** The role a permission guard admitted the caller with, on the site or organization it checked. */
+ accessRole?: OrgRole;
}
}
diff --git a/server/src/lib/access.test.ts b/server/src/lib/access.test.ts
index e40b202aa..3f6ab0df7 100644
--- a/server/src/lib/access.test.ts
+++ b/server/src/lib/access.test.ts
@@ -51,20 +51,24 @@ vi.mock("../db/postgres/postgres.js", async () => {
import {
filterSitesByMemberAccess,
getOrgMembership,
+ grantsInOrganization,
isOrgAdmin,
isOrgOwner,
memberCanAccessSite,
MemberSiteGrants,
+ memberSiteRole,
resolveMemberSiteGrants,
restrictedMemberSiteIds,
siteIdsInOrganization,
} from "./access.js";
+// Grants that name no role of their own (they inherit the member's org role).
function grants(overrides: Partial<Record<keyof MemberSiteGrants, number[]>> = {}): MemberSiteGrants {
+ const inherit = (ids: number[] = []) => new Map(ids.map(id => [id, [null]]));
return {
- explicitSiteIds: new Set(overrides.explicitSiteIds ?? []),
+ explicitSiteIds: inherit(overrides.explicitSiteIds),
teamGatedSiteIds: new Set(overrides.teamGatedSiteIds ?? []),
- userTeamSiteIds: new Set(overrides.userTeamSiteIds ?? []),
+ userTeamSiteIds: inherit(overrides.userTeamSiteIds),
};
}
@@ -142,6 +146,22 @@ describe("restrictedMemberSiteIds cross-checks memberCanAccessSite", () => {
expect(checked).toBe(shapes.length ** 3);
});
+ it("gives a role exactly where the predicate admits the site, for every grant shape", () => {
+ for (const hasRestrictedSiteAccess of [true, false]) {
+ for (const explicitSiteIds of shapes) {
+ for (const teamGatedSiteIds of shapes) {
+ for (const userTeamSiteIds of shapes) {
+ const g = grants({ explicitSiteIds, teamGatedSiteIds, userTeamSiteIds });
+ for (const siteId of universe) {
+ const role = memberSiteRole(g, siteId, { role: "viewer", hasRestrictedSiteAccess });
+ expect(role !== null).toBe(memberCanAccessSite(g, siteId, hasRestrictedSiteAccess));
+ }
+ }
+ }
+ }
+ }
+ });
+
it("never repeats a site id, even when the explicit and team grants overlap", () => {
const ids = restrictedMemberSiteIds(grants({ explicitSiteIds: [1, 2], userTeamSiteIds: [2, 3] }));
@@ -154,6 +174,29 @@ describe("restrictedMemberSiteIds cross-checks memberCanAccessSite", () => {
});
});
+describe("memberSiteRole", () => {
+ const withRoles = (explicit: [number, (string | null)[]][], team: [number, (string | null)[]][] = []) => ({
+ explicitSiteIds: new Map(explicit),
+ teamGatedSiteIds: new Set<number>(),
+ userTeamSiteIds: new Map(team),
+ });
+
+ it("raises the organization role to the highest grant", () => {
+ const g = withRoles([[1, ["editor"]]], [[1, ["member"]]]);
+ expect(memberSiteRole(g, 1, { role: "viewer", hasRestrictedSiteAccess: true })).toBe("editor");
+ });
+
+ it("never lowers the organization role", () => {
+ const g = withRoles([[1, ["viewer"]]]);
+ expect(memberSiteRole(g, 1, { role: "member", hasRestrictedSiteAccess: true })).toBe("member");
+ });
+
+ it("uses the organization role for grants that name none", () => {
+ const g = withRoles([[1, [null]]]);
+ expect(memberSiteRole(g, 1, { role: "editor", hasRestrictedSiteAccess: true })).toBe("editor");
+ });
+});
+
describe("getOrgMembership", () => {
it("returns the membership row when the user belongs to the organization", async () => {
state.member = [
@@ -223,10 +266,17 @@ describe("siteIdsInOrganization", () => {
describe("resolveMemberSiteGrants", () => {
it("collects explicit grants, team-gated sites and the user's own team sites", async () => {
- state.member_site_access = [{ siteId: 1 }, { siteId: 1 }, { siteId: 2 }];
- state.team_site_access_joined = [{ siteId: 2 }, { siteId: 3 }];
- state.teamMember = [{ teamId: "t_1" }];
- state.team_site_access = [{ siteId: 3 }];
+ state.member_site_access = [
+ { siteId: 1, organizationId: "org_1" },
+ { siteId: 1, organizationId: "org_1" },
+ { siteId: 2, organizationId: "org_1" },
+ ];
+ state.team_site_access_joined = [
+ { siteId: 2, organizationId: "org_1" },
+ { siteId: 3, organizationId: "org_1" },
+ ];
+ state.teamMember = [{ teamId: "t_1", organizationId: "org_1" }];
+ state.team_site_access = [{ teamId: "t_1", siteId: 3 }];
const resolved = await resolveMemberSiteGrants({
userId: "u_1",
@@ -234,13 +284,14 @@ describe("resolveMemberSiteGrants", () => {
grantedMemberIds: ["m_1"],
});
- expect(resolved.explicitSiteIds).toEqual(new Set([1, 2]));
- expect(resolved.teamGatedSiteIds).toEqual(new Set([2, 3]));
- expect(resolved.userTeamSiteIds).toEqual(new Set([3]));
+ const org = grantsInOrganization(resolved, "org_1");
+ expect(new Set(org.explicitSiteIds.keys())).toEqual(new Set([1, 2]));
+ expect(org.teamGatedSiteIds).toEqual(new Set([2, 3]));
+ expect(new Set(org.userTeamSiteIds.keys())).toEqual(new Set([3]));
});
it("skips the explicit-grant query when no member ids are supplied", async () => {
- state.member_site_access = [{ siteId: 42 }];
+ state.member_site_access = [{ siteId: 42, organizationId: "org_1" }];
const resolved = await resolveMemberSiteGrants({
userId: "u_1",
@@ -248,13 +299,13 @@ describe("resolveMemberSiteGrants", () => {
grantedMemberIds: [],
});
- expect(resolved.explicitSiteIds).toEqual(new Set());
+ expect(grantsInOrganization(resolved, "org_1").explicitSiteIds.size).toBe(0);
expect(state.queriedTables).not.toContain("member_site_access");
});
it("skips the team-site query when the user is on no team", async () => {
state.teamMember = [];
- state.team_site_access = [{ siteId: 7 }];
+ state.team_site_access = [{ teamId: "t_1", siteId: 7 }];
const resolved = await resolveMemberSiteGrants({
userId: "u_1",
@@ -262,22 +313,38 @@ describe("resolveMemberSiteGrants", () => {
grantedMemberIds: [],
});
- expect(resolved.userTeamSiteIds).toEqual(new Set());
+ expect(grantsInOrganization(resolved, "org_1").userTeamSiteIds.size).toBe(0);
expect(state.queriedTables).not.toContain("team_site_access");
});
it("returns empty grants without querying when there is nothing to scope by", async () => {
const resolved = await resolveMemberSiteGrants({ userId: "u_1", organizationIds: [], grantedMemberIds: [] });
- expect(resolved.explicitSiteIds).toEqual(new Set());
- expect(resolved.teamGatedSiteIds).toEqual(new Set());
- expect(resolved.userTeamSiteIds).toEqual(new Set());
+ expect(resolved.size).toBe(0);
expect(state.queriedTables).toEqual([]);
});
+ it("files each grant under the organization that made it", async () => {
+ // A grant written by org_old for a site that has since moved counts only
+ // toward org_old's sites, where that site no longer is.
+ state.member_site_access = [
+ { siteId: 1, organizationId: "org_old" },
+ { siteId: 2, organizationId: "org_1" },
+ ];
+
+ const resolved = await resolveMemberSiteGrants({
+ userId: "u_1",
+ organizationIds: [],
+ grantedMemberIds: ["m_old", "m_1"],
+ });
+
+ expect([...grantsInOrganization(resolved, "org_1").explicitSiteIds.keys()]).toEqual([2]);
+ expect([...grantsInOrganization(resolved, "org_old").explicitSiteIds.keys()]).toEqual([1]);
+ });
+
it("still loads explicit grants when only member ids are scoped, leaving the org-scoped sets empty", async () => {
- state.member_site_access = [{ siteId: 5 }];
- state.team_site_access_joined = [{ siteId: 6 }];
+ state.member_site_access = [{ siteId: 5, organizationId: "org_1" }];
+ state.team_site_access_joined = [{ siteId: 6, organizationId: "org_1" }];
const resolved = await resolveMemberSiteGrants({
userId: "u_1",
@@ -285,18 +352,19 @@ describe("resolveMemberSiteGrants", () => {
grantedMemberIds: ["m_1"],
});
- expect(resolved.explicitSiteIds).toEqual(new Set([5]));
- expect(resolved.teamGatedSiteIds).toEqual(new Set());
+ const org = grantsInOrganization(resolved, "org_1");
+ expect(new Set(org.explicitSiteIds.keys())).toEqual(new Set([5]));
+ expect(org.teamGatedSiteIds).toEqual(new Set());
expect(state.queriedTables).toEqual(["member_site_access"]);
});
});
describe("filterSitesByMemberAccess", () => {
it("keeps only granted sites for a restricted member and asks for their explicit grants", async () => {
- state.member_site_access = [{ siteId: 1 }];
- state.team_site_access_joined = [{ siteId: 2 }];
- state.teamMember = [{ teamId: "t_1" }];
- state.team_site_access = [{ siteId: 2 }];
+ state.member_site_access = [{ siteId: 1, organizationId: "org_1" }];
+ state.team_site_access_joined = [{ siteId: 2, organizationId: "org_1" }];
+ state.teamMember = [{ teamId: "t_1", organizationId: "org_1" }];
+ state.team_site_access = [{ teamId: "t_1", siteId: 2 }];
const kept = await filterSitesByMemberAccess(
[{ siteId: 1 }, { siteId: 2 }, { siteId: 3 }],
@@ -311,8 +379,8 @@ describe("filterSitesByMemberAccess", () => {
});
it("keeps ungated sites for an unrestricted member and does not load explicit grants", async () => {
- state.member_site_access = [{ siteId: 99 }];
- state.team_site_access_joined = [{ siteId: 2 }];
+ state.member_site_access = [{ siteId: 99, organizationId: "org_1" }];
+ state.team_site_access_joined = [{ siteId: 2, organizationId: "org_1" }];
const kept = await filterSitesByMemberAccess(
[{ siteId: 1 }, { siteId: 2 }, { siteId: 3 }],
@@ -327,7 +395,7 @@ describe("filterSitesByMemberAccess", () => {
});
it("preserves the caller's own row shape and ordering", async () => {
- state.team_site_access_joined = [{ siteId: 2 }];
+ state.team_site_access_joined = [{ siteId: 2, organizationId: "org_1" }];
const kept = await filterSitesByMemberAccess(
[
diff --git a/server/src/lib/access.ts b/server/src/lib/access.ts
index 8ef9b5009..201031d61 100644
--- a/server/src/lib/access.ts
+++ b/server/src/lib/access.ts
@@ -1,3 +1,4 @@
+import { higherRole, isAdminRole, isOrgRole, isSiteGrantRole, type OrgRole } from "@rybbit/shared";
import { and, eq, inArray } from "drizzle-orm";
import { db } from "../db/postgres/postgres.js";
import { member, memberSiteAccess, sites, team, teamMember, teamSiteAccess } from "../db/postgres/schema.js";
@@ -36,13 +37,16 @@ export interface OrgMembership {
*/
export async function getOrgMembership(
userId: string | undefined | null,
- organizationId: string | undefined | null
+ organizationId: string | undefined | null,
+ // Pass the open transaction when calling from inside one: a second pooled
+ // connection per transaction can exhaust the pool and stall every worker.
+ executor: Pick<typeof db, "select"> = db
): Promise<OrgMembership | null> {
if (!userId || !organizationId) {
return null;
}
- const rows = await db
+ const rows = await executor
.select({
id: member.id,
userId: member.userId,
@@ -57,9 +61,28 @@ export async function getOrgMembership(
return rows[0] ?? null;
}
+/**
+ * The role a membership holds across the organization as a whole β€” what the
+ * organization-level permissions (org routes, org-wide segments and
+ * annotations) are checked against. A member restricted to specific sites is a
+ * viewer at that level: their role applies on the sites they were granted, not
+ * to things that span sites they cannot see.
+ */
+export function effectiveOrgRole(
+ membership: Pick<OrgMembership, "role" | "hasRestrictedSiteAccess"> | null | undefined
+): OrgRole | null {
+ if (!membership || !isOrgRole(membership.role)) {
+ return null;
+ }
+ if (membership.hasRestrictedSiteAccess && !isAdminRole(membership.role)) {
+ return "viewer";
+ }
+ return membership.role;
+}
+
/** Admin or owner of the organization β€” the two roles that bypass site gating. */
export function isOrgAdmin(membership: OrgMembership | null | undefined): boolean {
- return membership?.role === "admin" || membership?.role === "owner";
+ return isAdminRole(membership?.role);
}
/** Owner of the organization β€” the only role that may manage billing. */
@@ -90,28 +113,68 @@ export async function siteIdsInOrganization(siteIds: number[], organizationId: s
}
/**
- * The grants that decide, together with the member's restriction flag, which
- * sites a member-role user may access. Resolved once per request and consulted
- * per site by {@link memberCanAccessSite}.
+ * A grant's role; null means "the member's organization role". A site reached
+ * through several grants lists each one's role.
+ */
+type GrantRoles = (string | null)[];
+
+/**
+ * One organization's grants that decide, together with the member's
+ * restriction flag, which of its sites a non-admin member may access and with
+ * what role. Consulted per site by {@link memberSiteRole}.
*/
export interface MemberSiteGrants {
- /** Explicit per-member grants (member_site_access). */
- explicitSiteIds: Set<number>;
+ /** Explicit per-member grants (member_site_access), with each grant's role. */
+ explicitSiteIds: Map<number, GrantRoles>;
/** Sites gated behind any team in the scoped organizations. */
teamGatedSiteIds: Set<number>;
- /** Sites reachable through the teams the user belongs to. */
- userTeamSiteIds: Set<number>;
+ /** Sites reachable through the teams the user belongs to, with each team grant's role. */
+ userTeamSiteIds: Map<number, GrantRoles>;
}
-const NO_GRANTS: MemberSiteGrants = {
- explicitSiteIds: new Set(),
+const emptyGrants = (): MemberSiteGrants => ({
+ explicitSiteIds: new Map(),
teamGatedSiteIds: new Set(),
- userTeamSiteIds: new Set(),
-};
+ userTeamSiteIds: new Map(),
+});
+
+const NO_GRANTS: MemberSiteGrants = emptyGrants();
+
+/**
+ * Grants keyed by the organization that made them β€” the organization of the
+ * membership (explicit grants) or team (team grants). A grant counts only
+ * toward sites of that same organization: a site that moved elsewhere keeps no
+ * authority from grants its old organization wrote, even ones written in the
+ * race window around the move.
+ */
+export type OrganizationSiteGrants = Map<string, MemberSiteGrants>;
+
+/** One organization's grants (empty when it made none). */
+export function grantsInOrganization(grants: OrganizationSiteGrants, organizationId: string): MemberSiteGrants {
+ return grants.get(organizationId) ?? NO_GRANTS;
+}
+
+function grantsFor(grants: OrganizationSiteGrants, organizationId: string): MemberSiteGrants {
+ let scoped = grants.get(organizationId);
+ if (!scoped) {
+ scoped = emptyGrants();
+ grants.set(organizationId, scoped);
+ }
+ return scoped;
+}
+
+// A grant row naming a role no grant can carry (unknown, or admin/owner) is
+// ignored outright, so reachability and role never disagree about it.
+function addGrant(grants: Map<number, GrantRoles>, siteId: number, role: string | null | undefined) {
+ if (role != null && !isSiteGrantRole(role)) return;
+ const roles = grants.get(siteId);
+ if (roles) roles.push(role ?? null);
+ else grants.set(siteId, [role ?? null]);
+}
/**
* Load the site grants for one user across the organizations where they hold a
- * member role.
+ * non-admin role.
*
* `grantedMemberIds` carries the member rows whose explicit grants apply.
* Explicit grants are only recorded for members with restricted access, so
@@ -121,57 +184,62 @@ export async function resolveMemberSiteGrants(options: {
userId: string;
organizationIds: string[];
grantedMemberIds: string[];
-}): Promise<MemberSiteGrants> {
+}): Promise<OrganizationSiteGrants> {
const { userId, organizationIds, grantedMemberIds } = options;
+ const grants: OrganizationSiteGrants = new Map();
if (organizationIds.length === 0 && grantedMemberIds.length === 0) {
- return NO_GRANTS;
+ return grants;
}
const [explicitGrants, teamGated, userTeams] = await Promise.all([
grantedMemberIds.length > 0
? db
- .select({ siteId: memberSiteAccess.siteId })
+ .select({
+ siteId: memberSiteAccess.siteId,
+ role: memberSiteAccess.role,
+ organizationId: member.organizationId,
+ })
.from(memberSiteAccess)
+ .innerJoin(member, eq(memberSiteAccess.memberId, member.id))
.where(inArray(memberSiteAccess.memberId, grantedMemberIds))
: Promise.resolve([]),
organizationIds.length > 0
? db
- .select({ siteId: teamSiteAccess.siteId })
+ .select({ siteId: teamSiteAccess.siteId, organizationId: team.organizationId })
.from(teamSiteAccess)
.innerJoin(team, eq(teamSiteAccess.teamId, team.id))
.where(inArray(team.organizationId, organizationIds))
: Promise.resolve([]),
organizationIds.length > 0
? db
- .select({ teamId: teamMember.teamId })
+ .select({ teamId: teamMember.teamId, organizationId: team.organizationId })
.from(teamMember)
.innerJoin(team, eq(teamMember.teamId, team.id))
.where(and(eq(teamMember.userId, userId), inArray(team.organizationId, organizationIds)))
: Promise.resolve([]),
]);
- const userTeamSiteIds = new Set<number>();
if (userTeams.length > 0) {
+ const organizationByTeam = new Map(userTeams.map(t => [t.teamId, t.organizationId]));
const userTeamSites = await db
- .select({ siteId: teamSiteAccess.siteId })
+ .select({ teamId: teamSiteAccess.teamId, siteId: teamSiteAccess.siteId, role: teamSiteAccess.role })
.from(teamSiteAccess)
- .where(
- inArray(
- teamSiteAccess.teamId,
- userTeams.map(t => t.teamId)
- )
- );
+ .where(inArray(teamSiteAccess.teamId, [...organizationByTeam.keys()]));
for (const s of userTeamSites) {
- userTeamSiteIds.add(s.siteId);
+ const organizationId = organizationByTeam.get(s.teamId);
+ if (organizationId) addGrant(grantsFor(grants, organizationId).userTeamSiteIds, s.siteId, s.role);
}
}
- return {
- explicitSiteIds: new Set(explicitGrants.map(g => g.siteId)),
- teamGatedSiteIds: new Set(teamGated.map(s => s.siteId)),
- userTeamSiteIds,
- };
+ for (const grant of explicitGrants) {
+ addGrant(grantsFor(grants, grant.organizationId).explicitSiteIds, grant.siteId, grant.role);
+ }
+ for (const gated of teamGated) {
+ grantsFor(grants, gated.organizationId).teamGatedSiteIds.add(gated.siteId);
+ }
+
+ return grants;
}
/**
@@ -197,6 +265,34 @@ export function memberCanAccessSite(
return !grants.teamGatedSiteIds.has(siteId);
}
+/**
+ * The role a non-admin member holds on a site, or null when they cannot reach
+ * it. The member's organization role applies on every site they reach; an
+ * explicit or team grant naming a higher role raises it on that site, and never
+ * lowers it. (Grants stop at editor, and rows naming anything else are dropped
+ * when loaded.)
+ *
+ * Reachability is exactly {@link memberCanAccessSite}; this adds the role.
+ */
+export function memberSiteRole(
+ grants: MemberSiteGrants,
+ siteId: number,
+ membership: { role: OrgRole; hasRestrictedSiteAccess: boolean }
+): OrgRole | null {
+ const grantRoles = [...(grants.explicitSiteIds.get(siteId) ?? []), ...(grants.userTeamSiteIds.get(siteId) ?? [])];
+ const reachable =
+ grantRoles.length > 0 || (!membership.hasRestrictedSiteAccess && !grants.teamGatedSiteIds.has(siteId));
+ if (!reachable) {
+ return null;
+ }
+
+ let role: OrgRole | null = membership.role;
+ for (const granted of grantRoles) {
+ role = higherRole(role, granted);
+ }
+ return role;
+}
+
/**
* The closed set of sites a *restricted* member can reach β€” the narrowing
* counterpart of {@link memberCanAccessSite}. Restricted access is entirely
@@ -208,7 +304,7 @@ export function memberCanAccessSite(
* the two are cross-checked in access.test.ts.
*/
export function restrictedMemberSiteIds(grants: MemberSiteGrants): number[] {
- return Array.from(new Set([...grants.explicitSiteIds, ...grants.userTeamSiteIds]));
+ return Array.from(new Set([...grants.explicitSiteIds.keys(), ...grants.userTeamSiteIds.keys()]));
}
/**
@@ -225,11 +321,234 @@ export async function filterSitesByMemberAccess<T extends { siteId: number }>(
memberId: string,
hasRestrictedSiteAccess: boolean
): Promise<T[]> {
- const grants = await resolveMemberSiteGrants({
- userId,
- organizationIds: [organizationId],
- grantedMemberIds: hasRestrictedSiteAccess ? [memberId] : [],
- });
+ const grants = grantsInOrganization(
+ await resolveMemberSiteGrants({
+ userId,
+ organizationIds: [organizationId],
+ grantedMemberIds: hasRestrictedSiteAccess ? [memberId] : [],
+ }),
+ organizationId
+ );
return orgSites.filter(site => memberCanAccessSite(grants, site.siteId, hasRestrictedSiteAccess));
}
+
+export type SiteRow = typeof sites.$inferSelect;
+
+/** A site the caller can reach, with the role they hold on it. */
+export type AccessibleSite = SiteRow & { accessRole: OrgRole };
+
+/**
+ * Every site a user reaches through their organization memberships, each with
+ * the role they hold on it β€” the single computation behind both the session
+ * and the bearer-credential paths, so a personal API key reaches exactly what
+ * its user's browser session reaches.
+ *
+ * Admin/owner memberships reach every site of the organization. Any other
+ * role reaches the sites the Site Access rule ({@link memberCanAccessSite})
+ * admits. A membership whose role is not a known role reaches nothing.
+ *
+ * System-admin authority is not a membership and is not applied here; the
+ * session layer adds it.
+ */
+export async function resolveUserSites(
+ userId: string,
+ // Only this organization's sites (and only the membership in it).
+ { organizationId }: { organizationId?: string } = {}
+): Promise<AccessibleSite[]> {
+ const memberRecords = await db
+ .select({
+ id: member.id,
+ organizationId: member.organizationId,
+ role: member.role,
+ hasRestrictedSiteAccess: member.hasRestrictedSiteAccess,
+ })
+ .from(member)
+ .where(
+ organizationId
+ ? and(eq(member.userId, userId), eq(member.organizationId, organizationId))
+ : eq(member.userId, userId)
+ );
+
+ const roleByOrgId = new Map<string, OrgRole>();
+ const fullAccessOrgIds: string[] = [];
+ const gatedMembers: typeof memberRecords = [];
+
+ for (const record of memberRecords) {
+ if (!isOrgRole(record.role)) {
+ continue;
+ }
+ roleByOrgId.set(record.organizationId, record.role);
+ if (isAdminRole(record.role)) {
+ fullAccessOrgIds.push(record.organizationId);
+ } else {
+ gatedMembers.push(record);
+ }
+ }
+
+ const gatedRowByOrgId = new Map(gatedMembers.map(record => [record.organizationId, record]));
+ const gatedOrgIds = Array.from(gatedRowByOrgId.keys());
+ const restrictedMembers = gatedMembers.filter(record => record.hasRestrictedSiteAccess);
+ const restrictedOrgIds = restrictedMembers.map(record => record.organizationId);
+
+ // A restricted membership reaches a closed set of sites, so its
+ // organization is loaded by id below rather than read in full and
+ // discarded β€” an org can hold far more sites than one member is granted.
+ const restrictedOrgIdSet = new Set(restrictedOrgIds);
+ const eagerOrgIds = Array.from(
+ new Set([...fullAccessOrgIds, ...gatedOrgIds.filter(id => !restrictedOrgIdSet.has(id))])
+ );
+
+ if (eagerOrgIds.length === 0 && restrictedOrgIds.length === 0) {
+ return [];
+ }
+
+ const [eagerSites, grants] = await Promise.all([
+ eagerOrgIds.length > 0
+ ? db.select().from(sites).where(inArray(sites.organizationId, eagerOrgIds))
+ : Promise.resolve([]),
+ gatedOrgIds.length > 0
+ ? resolveMemberSiteGrants({
+ userId,
+ organizationIds: gatedOrgIds,
+ grantedMemberIds: restrictedMembers.map(record => record.id),
+ })
+ : null,
+ ]);
+
+ // Admin/owner memberships hold their role on every site of the
+ // organization; other roles hold whatever their grants give them per site.
+ const withRole = (site: SiteRow): AccessibleSite | null => {
+ const orgRole = site.organizationId ? roleByOrgId.get(site.organizationId) : undefined;
+ if (!orgRole) return null;
+ const gatedRow = gatedRowByOrgId.get(site.organizationId!);
+ if (!gatedRow) return { ...site, accessRole: orgRole };
+ const role = grants
+ ? memberSiteRole(grantsInOrganization(grants, site.organizationId!), site.siteId, {
+ role: orgRole,
+ hasRestrictedSiteAccess: gatedRow.hasRestrictedSiteAccess,
+ })
+ : null;
+ return role ? { ...site, accessRole: role } : null;
+ };
+ const accessible: AccessibleSite[] = [];
+ for (const site of eagerSites) {
+ const entry = withRole(site);
+ if (entry) accessible.push(entry);
+ }
+
+ if (grants && restrictedOrgIds.length > 0) {
+ const candidateSiteIds = Array.from(
+ new Set(
+ restrictedOrgIds.flatMap(organizationId =>
+ restrictedMemberSiteIds(grantsInOrganization(grants, organizationId))
+ )
+ )
+ );
+ if (candidateSiteIds.length > 0) {
+ const grantedSites = await db
+ .select()
+ .from(sites)
+ .where(and(inArray(sites.siteId, candidateSiteIds), inArray(sites.organizationId, restrictedOrgIds)));
+ const seen = new Set(accessible.map(site => site.siteId));
+ for (const site of grantedSites) {
+ if (seen.has(site.siteId)) continue;
+ const entry = withRole(site);
+ if (entry) accessible.push(entry);
+ }
+ }
+ }
+
+ return accessible;
+}
+
+/**
+ * The role a user holds on one site through their membership in its
+ * organization, or null β€” the same answer {@link resolveUserSites} gives for
+ * that site, computed from that site alone: its organization, the one
+ * membership there, and the grants that name the site. For checks that must
+ * not trust a cached list (every permission above viewer) and so can't afford
+ * to rebuild the whole list per request.
+ *
+ */
+export async function resolveUserSiteRole(userId: string, siteId: number): Promise<OrgRole | null> {
+ const [site] = await db
+ .select({ organizationId: sites.organizationId })
+ .from(sites)
+ .where(eq(sites.siteId, siteId))
+ .limit(1);
+ if (!site?.organizationId) {
+ return null;
+ }
+ const organizationId = site.organizationId;
+
+ const membership = await getOrgMembership(userId, organizationId);
+ if (!membership || !isOrgRole(membership.role)) {
+ return null;
+ }
+ if (isAdminRole(membership.role)) {
+ return membership.role;
+ }
+
+ // The grants that concern this site: the member's own (recorded only while
+ // restricted), whether any of the organization's teams gates it, and the
+ // teams of this user that grant it.
+ const [explicit, gated, viaTeams] = await Promise.all([
+ membership.hasRestrictedSiteAccess
+ ? db
+ .select({ role: memberSiteAccess.role })
+ .from(memberSiteAccess)
+ .where(and(eq(memberSiteAccess.memberId, membership.id), eq(memberSiteAccess.siteId, siteId)))
+ : Promise.resolve([]),
+ db
+ .select({ teamId: teamSiteAccess.teamId })
+ .from(teamSiteAccess)
+ .innerJoin(team, eq(teamSiteAccess.teamId, team.id))
+ .where(and(eq(teamSiteAccess.siteId, siteId), eq(team.organizationId, organizationId)))
+ .limit(1),
+ db
+ .select({ role: teamSiteAccess.role })
+ .from(teamSiteAccess)
+ .innerJoin(team, eq(teamSiteAccess.teamId, team.id))
+ .innerJoin(teamMember, eq(teamMember.teamId, team.id))
+ .where(
+ and(eq(teamSiteAccess.siteId, siteId), eq(team.organizationId, organizationId), eq(teamMember.userId, userId))
+ ),
+ ]);
+
+ const grants = emptyGrants();
+ for (const grant of explicit) addGrant(grants.explicitSiteIds, siteId, grant.role);
+ for (const grant of viaTeams) addGrant(grants.userTeamSiteIds, siteId, grant.role);
+ if (gated.length > 0) grants.teamGatedSiteIds.add(siteId);
+
+ return memberSiteRole(grants, siteId, {
+ role: membership.role,
+ hasRestrictedSiteAccess: membership.hasRestrictedSiteAccess,
+ });
+}
+
+/**
+ * The role each grant gets when a member's site grants are rewritten. With a
+ * role requested (null included, meaning "no raise"), every grant gets it.
+ * With none requested, grants that stay keep the role they carried, and newly
+ * granted sites get the role all the old grants shared β€” so a caller that only
+ * changes which sites a member has never silently drops their site role.
+ * Read the old grants before deleting them, inside the same transaction.
+ */
+export async function grantRoleForRewrite(
+ executor: Pick<typeof db, "select">,
+ memberId: string,
+ requested: string | null | undefined
+): Promise<(siteId: number) => string | null> {
+ if (requested !== undefined) {
+ return () => requested;
+ }
+ const previous = await executor
+ .select({ siteId: memberSiteAccess.siteId, role: memberSiteAccess.role })
+ .from(memberSiteAccess)
+ .where(eq(memberSiteAccess.memberId, memberId));
+ const previousRoles = new Map(previous.map(grant => [grant.siteId, grant.role]));
+ const sharedRoles = new Set(previous.map(grant => grant.role));
+ const sharedRole = sharedRoles.size === 1 ? [...sharedRoles][0] : null;
+ return siteId => (previousRoles.has(siteId) ? previousRoles.get(siteId)! : sharedRole);
+}
diff --git a/server/src/lib/auth-middleware.test.ts b/server/src/lib/auth-middleware.test.ts
index 30f8089c0..2f360bfec 100644
--- a/server/src/lib/auth-middleware.test.ts
+++ b/server/src/lib/auth-middleware.test.ts
@@ -4,11 +4,10 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
checkApiKey: vi.fn(),
getSessionFromReq: vi.fn(),
- getUserHasAccessToSite: vi.fn(),
- getUserHasAdminAccessToSite: vi.fn(),
- getUserHasAccessToSitePublic: vi.fn(),
- getUserIsInOrg: vi.fn(),
+ getUserSiteRole: vi.fn(),
+ getSiteIsPubliclyReadable: vi.fn(),
getIsUserAdmin: vi.fn(),
+ getUserOrgRole: vi.fn(),
}));
vi.mock("./auth-utils.js", () => mocks);
@@ -17,14 +16,7 @@ vi.mock("../db/postgres/postgres.js", () => ({
}));
vi.mock("./siteConfig.js", () => ({ siteConfig: { resolveSiteId: vi.fn(async () => null) } }));
-import {
- allowPublicSiteAccess,
- requireAuth,
- requireOrgMember,
- requireSiteAccess,
- requireSiteAdminAccess,
- resolveSiteId,
-} from "./auth-middleware.js";
+import { requireAuth, requireOrgPermission, requireSitePermission, resolveSiteId } from "./auth-middleware.js";
import type { ScopeStatements } from "./scopes.js";
const bearer = { authorization: "Bearer rb_key" };
@@ -35,43 +27,47 @@ function bearerResult(statements: ScopeStatements | null, role = "member") {
const invalidResult = { valid: false, role: null, statements: null };
-describe("auth middleware scope enforcement", () => {
+describe("permission guards", () => {
let app: FastifyInstance;
beforeEach(async () => {
vi.clearAllMocks();
mocks.getSessionFromReq.mockResolvedValue(null);
- mocks.getUserHasAccessToSite.mockResolvedValue(false);
- mocks.getUserHasAdminAccessToSite.mockResolvedValue(false);
- mocks.getUserHasAccessToSitePublic.mockResolvedValue(false);
- mocks.getUserIsInOrg.mockResolvedValue(false);
+ mocks.getUserSiteRole.mockResolvedValue(null);
+ mocks.getSiteIsPubliclyReadable.mockResolvedValue(false);
mocks.getIsUserAdmin.mockResolvedValue(false);
mocks.checkApiKey.mockResolvedValue(invalidResult);
+ mocks.getUserOrgRole.mockResolvedValue(null);
app = Fastify();
app.get(
"/sites/:siteId/goals",
- { preHandler: [resolveSiteId, requireSiteAccess({ resource: "goals", action: "read" })] as any },
- async () => ({ ok: true })
+ { preHandler: [resolveSiteId, requireSitePermission("goals:read")] as any },
+ async request => ({ role: request.accessRole ?? null })
);
app.post(
"/sites/:siteId/goals",
- { preHandler: [resolveSiteId, requireSiteAccess({ resource: "goals", action: "write" })] as any },
+ { preHandler: [resolveSiteId, requireSitePermission("goals:write")] as any },
async () => ({ ok: true })
);
app.delete(
"/sites/:siteId",
- { preHandler: [resolveSiteId, requireSiteAdminAccess({ resource: "sites", action: "write" })] as any },
+ { preHandler: [resolveSiteId, requireSitePermission("sites:delete")] as any },
async () => ({ ok: true })
);
app.get(
"/sites/:siteId/overview",
- { preHandler: [resolveSiteId, allowPublicSiteAccess({ resource: "analytics", action: "read" })] as any },
+ { preHandler: [resolveSiteId, requireSitePermission("analytics:read", { allowPublic: true })] as any },
async () => ({ ok: true })
);
app.get(
"/organizations/:organizationId/members",
- { preHandler: [requireOrgMember({ resource: "org", action: "read" })] as any },
+ { preHandler: [requireOrgPermission("org:read")] as any },
+ async () => ({ ok: true })
+ );
+ app.post(
+ "/organizations/:organizationId/teams",
+ { preHandler: [requireOrgPermission("teams:manage")] as any },
async () => ({ ok: true })
);
app.post("/user/settings", { preHandler: [requireAuth("deny-scoped")] as any }, async () => ({ ok: true }));
@@ -97,6 +93,7 @@ describe("auth middleware scope enforcement", () => {
const response = await app.inject({ method: "GET", url: "/sites/5/goals", headers: bearer });
expect(response.statusCode).toBe(200);
+ expect(response.json()).toEqual({ role: "member" });
});
it("treats legacy credentials (null statements) as unrestricted", async () => {
@@ -104,12 +101,13 @@ describe("auth middleware scope enforcement", () => {
expect((await app.inject({ method: "POST", url: "/sites/5/goals", headers: bearer })).statusCode).toBe(200);
// ...but scopes never elevate: a member-role legacy key still can't hit admin routes.
- expect((await app.inject({ method: "DELETE", url: "/sites/5", headers: bearer })).statusCode).toBe(403);
+ const deleted = await app.inject({ method: "DELETE", url: "/sites/5", headers: bearer });
+ expect(deleted.statusCode).toBe(403);
+ expect(deleted.json()).toEqual({ error: "Insufficient role", required: "admin" });
});
it("sessions bypass scopes entirely", async () => {
- mocks.checkApiKey.mockResolvedValue(invalidResult);
- mocks.getUserHasAccessToSite.mockResolvedValue(true);
+ mocks.getUserSiteRole.mockResolvedValue("member");
mocks.getSessionFromReq.mockResolvedValue({ user: { id: "session_user" } });
const response = await app.inject({ method: "POST", url: "/sites/5/goals" });
@@ -117,19 +115,26 @@ describe("auth middleware scope enforcement", () => {
expect(response.statusCode).toBe(200);
});
- it("allows Better Auth system admins on site-admin routes without organization-admin access", async () => {
- mocks.getIsUserAdmin.mockResolvedValue(true);
- mocks.getSessionFromReq.mockResolvedValue({ user: { id: "system_admin", role: "admin" } });
+ it("admits a session whose role on the site holds the permission, and only that", async () => {
+ mocks.getSessionFromReq.mockResolvedValue({ user: { id: "session_user" } });
+
+ mocks.getUserSiteRole.mockResolvedValue("admin");
+ expect((await app.inject({ method: "DELETE", url: "/sites/5" })).statusCode).toBe(200);
- const response = await app.inject({ method: "DELETE", url: "/sites/5" });
+ mocks.getUserSiteRole.mockResolvedValue("member");
+ const denied = await app.inject({ method: "DELETE", url: "/sites/5" });
+ expect(denied.statusCode).toBe(403);
+ expect(denied.json()).toEqual({ error: "Insufficient role", required: "admin" });
- expect(response.statusCode).toBe(200);
- expect(mocks.getUserHasAdminAccessToSite).not.toHaveBeenCalled();
+ mocks.getUserSiteRole.mockResolvedValue(null);
+ const outsider = await app.inject({ method: "DELETE", url: "/sites/5" });
+ expect(outsider.statusCode).toBe(403);
+ expect(outsider.json()).toEqual({ error: "Forbidden" });
});
it("falls through to session access when the bearer scope is insufficient", async () => {
mocks.checkApiKey.mockResolvedValue(bearerResult({ goals: ["read"] }));
- mocks.getUserHasAccessToSite.mockResolvedValue(true);
+ mocks.getUserSiteRole.mockResolvedValue("member");
mocks.getSessionFromReq.mockResolvedValue({ user: { id: "session_user" } });
const response = await app.inject({ method: "POST", url: "/sites/5/goals", headers: bearer });
@@ -137,7 +142,7 @@ describe("auth middleware scope enforcement", () => {
expect(response.statusCode).toBe(200);
});
- it("admin guard requires both the admin role and the scope", async () => {
+ it("admin permissions require both the admin role and the scope", async () => {
mocks.checkApiKey.mockResolvedValue(bearerResult({ sites: ["write"] }, "admin"));
expect((await app.inject({ method: "DELETE", url: "/sites/5", headers: bearer })).statusCode).toBe(200);
@@ -149,7 +154,7 @@ describe("auth middleware scope enforcement", () => {
mocks.checkApiKey.mockResolvedValue(bearerResult({ sites: ["write"] }, "member"));
const wrongRole = await app.inject({ method: "DELETE", url: "/sites/5", headers: bearer });
expect(wrongRole.statusCode).toBe(403);
- expect(wrongRole.json().error).toBe("Forbidden");
+ expect(wrongRole.json().error).toBe("Insufficient role");
});
it("deny-scoped routes reject scoped credentials but allow unrestricted ones", async () => {
@@ -162,7 +167,7 @@ describe("auth middleware scope enforcement", () => {
expect((await app.inject({ method: "POST", url: "/user/settings", headers: bearer })).statusCode).toBe(200);
});
- it("org member guard enforces org scopes", async () => {
+ it("org guard enforces org scopes", async () => {
mocks.checkApiKey.mockResolvedValue(bearerResult({ analytics: ["read"] }));
const response = await app.inject({ method: "GET", url: "/organizations/org_1/members", headers: bearer });
@@ -171,19 +176,65 @@ describe("auth middleware scope enforcement", () => {
expect(response.json()).toEqual({ error: "Insufficient scope", required: "org:read" });
});
- it("threads the scope requirement into the public-access fallback", async () => {
+ it("org guard reads the session's organization role", async () => {
+ mocks.getSessionFromReq.mockResolvedValue({ user: { id: "session_user" } });
+
+ mocks.getUserOrgRole.mockResolvedValue("member");
+ expect((await app.inject({ method: "GET", url: "/organizations/org_1/members" })).statusCode).toBe(200);
+ const member = await app.inject({ method: "POST", url: "/organizations/org_1/teams" });
+ expect(member.statusCode).toBe(403);
+ expect(member.json()).toEqual({ error: "Insufficient role", required: "admin" });
+
+ mocks.getUserOrgRole.mockResolvedValue("admin");
+ expect((await app.inject({ method: "POST", url: "/organizations/org_1/teams" })).statusCode).toBe(200);
+
+ mocks.getUserOrgRole.mockResolvedValue(null);
+ const outsider = await app.inject({ method: "GET", url: "/organizations/org_1/members" });
+ expect(outsider.statusCode).toBe(403);
+ expect(outsider.json()).toEqual({ error: "You are not a member of this organization" });
+ });
+
+ it("org guard answers 401 when there is no credential at all", async () => {
+ expect((await app.inject({ method: "GET", url: "/organizations/org_1/members" })).statusCode).toBe(401);
+ });
+
+ it("admits anyone on a public site, even a key lacking the scope", async () => {
mocks.checkApiKey.mockResolvedValue(bearerResult({ goals: ["read"] }));
- mocks.getUserHasAccessToSitePublic.mockResolvedValue(true);
+ mocks.getSiteIsPubliclyReadable.mockResolvedValue(true);
+ // The site is public: the anonymous baseline applies regardless of the key.
const response = await app.inject({ method: "GET", url: "/sites/5/overview", headers: bearer });
- // Public helper said yes (e.g. the site is public) β€” request passes even
- // though the key lacks analytics:read; the helper received the requirement.
expect(response.statusCode).toBe(200);
- expect(mocks.getUserHasAccessToSitePublic).toHaveBeenCalledWith(expect.anything(), "5", {
- resource: "analytics",
- action: "read",
- });
+ });
+
+ it("keeps the scope error on a private site for a key lacking the scope", async () => {
+ mocks.checkApiKey.mockResolvedValue(bearerResult({ goals: ["read"] }));
+
+ const response = await app.inject({ method: "GET", url: "/sites/5/overview", headers: bearer });
+
+ expect(response.statusCode).toBe(403);
+ expect(response.json()).toEqual({ error: "Insufficient scope", required: "analytics:read" });
+ });
+
+ it("does not consult public access on routes that do not allow it", async () => {
+ mocks.getSiteIsPubliclyReadable.mockResolvedValue(true);
+
+ expect((await app.inject({ method: "GET", url: "/sites/5/goals" })).statusCode).toBe(403);
+ expect(mocks.getSiteIsPubliclyReadable).not.toHaveBeenCalled();
+ });
+
+ it("re-reads the role for anything beyond reading, and uses the cache for reads", async () => {
+ mocks.getSessionFromReq.mockResolvedValue({ user: { id: "session_user" } });
+ mocks.getUserSiteRole.mockResolvedValue("admin");
+
+ await app.inject({ method: "GET", url: "/sites/5/goals" });
+ expect(mocks.getUserSiteRole).toHaveBeenLastCalledWith(expect.anything(), "5", { fresh: false });
+ expect(mocks.checkApiKey).toHaveBeenLastCalledWith(expect.anything(), { siteId: "5", fresh: false });
+
+ await app.inject({ method: "DELETE", url: "/sites/5" });
+ expect(mocks.getUserSiteRole).toHaveBeenLastCalledWith(expect.anything(), "5", { fresh: true });
+ expect(mocks.checkApiKey).toHaveBeenLastCalledWith(expect.anything(), { siteId: "5", fresh: true });
});
it("keeps returning 429 for rate-limited keys", async () => {
@@ -215,11 +266,14 @@ describe("auth middleware rate limit reporting", () => {
beforeEach(async () => {
vi.clearAllMocks();
mocks.getSessionFromReq.mockResolvedValue(null);
- mocks.getUserHasAccessToSite.mockResolvedValue(false);
+ mocks.getUserSiteRole.mockResolvedValue(null);
+ mocks.getSiteIsPubliclyReadable.mockResolvedValue(false);
mocks.getIsUserAdmin.mockResolvedValue(false);
app = Fastify();
- app.get("/sites/:siteId/goals", { preHandler: [requireSiteAccess()] as any }, async () => ({ ok: true }));
+ app.get("/sites/:siteId/goals", { preHandler: [requireSitePermission("goals:read")] as any }, async () => ({
+ ok: true,
+ }));
await app.ready();
});
@@ -281,7 +335,7 @@ describe("auth middleware rate limit reporting", () => {
it("sends no rate limit headers for session-authenticated requests", async () => {
mocks.checkApiKey.mockResolvedValue(invalidResult);
- mocks.getUserHasAccessToSite.mockResolvedValue(true);
+ mocks.getUserSiteRole.mockResolvedValue("member");
mocks.getSessionFromReq.mockResolvedValue({ user: { id: "user_1" } });
const response = await app.inject({ method: "GET", url: "/sites/5/goals" });
diff --git a/server/src/lib/auth-middleware.ts b/server/src/lib/auth-middleware.ts
index 71479121e..24c6e7695 100644
--- a/server/src/lib/auth-middleware.ts
+++ b/server/src/lib/auth-middleware.ts
@@ -1,20 +1,53 @@
-import { FastifyRequest, FastifyReply } from "fastify";
+import { FastifyRequest, FastifyReply, type RouteOptions } from "fastify";
+import { PERMISSIONS, roleHasPermission, type OrgRole, type Permission } from "@rybbit/shared";
import {
getSessionFromReq,
checkApiKey,
- getUserHasAccessToSite,
- getUserHasAdminAccessToSite,
- getUserHasAccessToSitePublic,
getIsUserAdmin,
- getUserIsInOrg,
+ getSiteIsPubliclyReadable,
+ getUserOrgRole,
+ getUserSiteRole,
type BearerAuthResult,
} from "./auth-utils.js";
-import { getOrgMembership, isOrgAdmin } from "./access.js";
import { hasScope, scopeToString, type ScopeRequirement } from "./scopes.js";
import { siteConfig } from "./siteConfig.js";
type AuthMiddleware = (request: FastifyRequest, reply: FastifyReply) => Promise<void>;
+/**
+ * Who may call a route. Every /api route declares one in `config.access`;
+ * {@link assertRouteAccessDeclared} refuses to register a route without it.
+ * - a permission on a site (:siteId) or organization (:organizationId),
+ * enforced by {@link requireSitePermission} / {@link requireOrgPermission}
+ * - "authenticated": any signed-in user or credential (user-level surfaces)
+ * - "system-admin": Better Auth system admins only
+ * - "public": no guard β€” tracking, webhooks, signed links, and handlers that
+ * authenticate the caller themselves
+ */
+export type RouteAccess =
+ | { level: "site"; permission: Permission; allowPublic: boolean }
+ | { level: "org"; permission: Permission }
+ | "authenticated"
+ | "system-admin"
+ | "public";
+
+declare module "fastify" {
+ interface FastifyContextConfig {
+ access?: RouteAccess;
+ }
+}
+
+/** onRoute hook: a route that doesn't say who may call it never registers. */
+export function assertRouteAccessDeclared(route: RouteOptions): void {
+ const access = (route.config as { access?: RouteAccess } | undefined)?.access;
+ if (!access) {
+ throw new Error(`Route ${route.method} ${route.url} does not declare config.access`);
+ }
+ if (typeof access === "object" && !(access.permission in PERMISSIONS)) {
+ throw new Error(`Route ${route.method} ${route.url} declares unknown permission "${access.permission}"`);
+ }
+}
+
/**
* Scope requirement for a route. Scopes constrain BEARER credentials only β€”
* cookie sessions always bypass them (the check sits inside the bearer branch
@@ -192,79 +225,57 @@ export const requireAdmin: AuthMiddleware = async (request, reply) => {
if (session?.user) request.user = session.user;
};
-/**
- * Requires access to site (via session or API key).
- */
-export function requireSiteAccess(scope?: RouteScope): AuthMiddleware {
- return async (request, reply) => {
- const siteId = getSiteIdFromParams(request);
- if (!siteId) {
- return reply.status(400).send({ error: "Site ID required" });
- }
-
- // Check API key first.
- let scopeDenied = false;
- const apiKeyResult = await checkApiKey(request, { siteId });
- if (apiKeyResult.valid) {
- if (bearerScopeOk(apiKeyResult, scope)) {
- attachApiKeyUser(request, reply, apiKeyResult);
- return;
- }
- scopeDenied = true;
- }
-
- // Check session-based access
- const hasAccess = await getUserHasAccessToSite(request, siteId);
- if (hasAccess) {
- const session = await getSessionFromReq(request);
- if (session?.user) request.user = session.user;
- return;
- }
+const sendInsufficientRole = (reply: FastifyReply, permission: Permission) =>
+ reply.status(403).send({ error: "Insufficient role", required: PERMISSIONS[permission].minRole });
- if (apiKeyResult.rateLimited) {
- return sendRateLimited(reply, apiKeyResult);
- }
- if (scopeDenied) {
- return sendInsufficientScope(reply, scope!);
- }
-
- return reply.status(403).send({ error: "Forbidden" });
- };
+export interface SitePermissionOptions {
+ /**
+ * Also admit callers with no role on the site when the site is public or the
+ * request carries its private link key. Only for read permissions.
+ */
+ allowPublic?: boolean;
}
/**
- * Requires admin/owner access to site.
+ * Requires a permission on the site named by the :siteId param. The caller's
+ * role on that site β€” from their membership, their site grants and teams, or
+ * admin authority for org-owned keys and system-admin sessions β€” must hold the
+ * permission, and a bearer credential must also carry the permission's scope.
*/
-export function requireSiteAdminAccess(scope?: RouteScope): AuthMiddleware {
+export function requireSitePermission(permission: Permission, options: SitePermissionOptions = {}): AuthMiddleware {
+ const scope = PERMISSIONS[permission].scope;
+ // Reads (every viewer permission) may use the short-lived per-worker role
+ // cache; anything a viewer can't do re-reads the role, so revoking access
+ // takes effect immediately for writes and admin actions.
+ const fresh = PERMISSIONS[permission].minRole !== "viewer";
return async (request, reply) => {
const siteId = getSiteIdFromParams(request);
if (!siteId) {
return reply.status(400).send({ error: "Site ID required" });
}
- // Check API key with admin/owner role first.
+ // Bearer credential first. A key whose role or scope falls short falls
+ // through to the session, so a browser tab holding both still works.
let scopeDenied = false;
- const apiKeyResult = await checkApiKey(request, { siteId });
- if (apiKeyResult.valid && (apiKeyResult.role === "admin" || apiKeyResult.role === "owner")) {
+ const apiKeyResult = await checkApiKey(request, { siteId, fresh });
+ if (apiKeyResult.valid && roleHasPermission(apiKeyResult.role, permission)) {
if (bearerScopeOk(apiKeyResult, scope)) {
attachApiKeyUser(request, reply, apiKeyResult);
+ request.accessRole = apiKeyResult.role as OrgRole;
return;
}
scopeDenied = true;
}
- // Better Auth system admins have account-wide authority and do not need
- // an admin/owner membership in the organization that owns the site.
- const isSystemAdmin = await getIsUserAdmin(request);
- if (isSystemAdmin) {
+ const role = await getUserSiteRole(request, siteId, { fresh });
+ if (roleHasPermission(role, permission)) {
const session = await getSessionFromReq(request);
if (session?.user) request.user = session.user;
+ request.accessRole = role!;
return;
}
- // Check session-based admin access
- const hasAdminAccess = await getUserHasAdminAccessToSite(request, siteId);
- if (hasAdminAccess) {
+ if (options.allowPublic && (await getSiteIsPubliclyReadable(request, siteId))) {
const session = await getSessionFromReq(request);
if (session?.user) request.user = session.user;
return;
@@ -274,59 +285,22 @@ export function requireSiteAdminAccess(scope?: RouteScope): AuthMiddleware {
return sendRateLimited(reply, apiKeyResult);
}
if (scopeDenied) {
- return sendInsufficientScope(reply, scope!);
+ return sendInsufficientScope(reply, scope);
}
-
- return reply.status(403).send({ error: "Forbidden" });
- };
-}
-
-/**
- * Allows public site access, private key, or authenticated access.
- */
-export function allowPublicSiteAccess(scope?: RouteScope): AuthMiddleware {
- const requirement = scope && scope !== "deny-scoped" ? scope : undefined;
- return async (request, reply) => {
- const siteId = getSiteIdFromParams(request);
- if (!siteId) {
- return reply.status(400).send({ error: "Site ID required" });
- }
-
- let scopeDenied = false;
- const apiKeyResult = await checkApiKey(request, { siteId });
- if (apiKeyResult.valid) {
- if (bearerScopeOk(apiKeyResult, scope)) {
- attachApiKeyUser(request, reply, apiKeyResult);
- return;
- }
- scopeDenied = true;
+ if (role || (apiKeyResult.valid && apiKeyResult.role)) {
+ return sendInsufficientRole(reply, permission);
}
-
- // Public/private-link/session access. The scope threads into this helper's
- // own bearer fallback; a public site stays readable regardless (anonymous
- // baseline).
- const hasAccess = await getUserHasAccessToSitePublic(request, siteId, requirement);
- if (hasAccess) {
- const session = await getSessionFromReq(request);
- if (session?.user) request.user = session.user;
- return;
- }
-
- if (apiKeyResult.rateLimited) {
- return sendRateLimited(reply, apiKeyResult);
- }
- if (scopeDenied) {
- return sendInsufficientScope(reply, scope!);
- }
-
return reply.status(403).send({ error: "Forbidden" });
};
}
/**
- * Requires membership in organization.
+ * Requires a permission in the organization named by the :organizationId
+ * param, held by the caller's organization role (system-admin sessions act as
+ * admin in every organization); bearer credentials also need the scope.
*/
-export function requireOrgMember(scope?: RouteScope): AuthMiddleware {
+export function requireOrgPermission(permission: Permission): AuthMiddleware {
+ const scope = PERMISSIONS[permission].scope;
return async (request, reply) => {
const params = request.params as Record<string, string>;
const organizationId = params.organizationId;
@@ -337,80 +311,44 @@ export function requireOrgMember(scope?: RouteScope): AuthMiddleware {
let scopeDenied = false;
const apiKeyResult = await checkApiKey(request, { organizationId });
- if (apiKeyResult.valid) {
+ if (apiKeyResult.valid && roleHasPermission(apiKeyResult.role, permission)) {
if (bearerScopeOk(apiKeyResult, scope)) {
attachApiKeyUser(request, reply, apiKeyResult);
+ request.accessRole = apiKeyResult.role as OrgRole;
return;
}
scopeDenied = true;
}
- const isMember = await getUserIsInOrg(request, organizationId);
- if (isMember) {
- const session = await getSessionFromReq(request);
- if (session?.user) request.user = session.user;
- return;
- }
-
- if (apiKeyResult.rateLimited) {
- return sendRateLimited(reply, apiKeyResult);
- }
- if (scopeDenied) {
- return sendInsufficientScope(reply, scope!);
- }
-
- return reply.status(403).send({ error: "Forbidden" });
- };
-}
-
-/**
- * Requires org admin/owner access via session or API key.
- * Extracts organizationId from request params (orgId).
- * Use for endpoints that create resources in an org (like addSite).
- */
-export function requireOrgAdminFromParams(scope?: RouteScope): AuthMiddleware {
- return async (request, reply) => {
- const params = request.params as Record<string, string>;
- const organizationId = params.organizationId;
-
- if (!organizationId) {
- return reply.status(400).send({ error: "Organization ID required in path" });
- }
-
- // Check API key first - must have admin/owner role
- let scopeDenied = false;
- const apiKeyResult = await checkApiKey(request, { organizationId });
- if (apiKeyResult.valid && (apiKeyResult.role === "admin" || apiKeyResult.role === "owner")) {
- if (bearerScopeOk(apiKeyResult, scope)) {
- attachApiKeyUser(request, reply, apiKeyResult);
+ const session = await getSessionFromReq(request);
+ if (session?.user?.id) {
+ const role = await getUserOrgRole(request, organizationId);
+ if (roleHasPermission(role, permission)) {
+ request.user = session.user;
+ request.accessRole = role!;
return;
}
- scopeDenied = true;
- }
-
- // Check session-based access - must be admin/owner of org
- const session = await getSessionFromReq(request);
- if (!session?.user?.id) {
if (apiKeyResult.rateLimited) {
return sendRateLimited(reply, apiKeyResult);
}
if (scopeDenied) {
- return sendInsufficientScope(reply, scope!);
+ return sendInsufficientScope(reply, scope);
+ }
+ if (role) {
+ return sendInsufficientRole(reply, permission);
}
- return reply.status(401).send({ error: "Unauthorized" });
- }
-
- // Check org membership and role
- const membership = await getOrgMembership(session.user.id, organizationId);
-
- if (!membership) {
return reply.status(403).send({ error: "You are not a member of this organization" });
}
- if (!isOrgAdmin(membership)) {
- return reply.status(403).send({ error: "You must be an admin or owner" });
+ if (apiKeyResult.rateLimited) {
+ return sendRateLimited(reply, apiKeyResult);
}
-
- request.user = session.user;
+ if (scopeDenied) {
+ return sendInsufficientScope(reply, scope);
+ }
+ if (apiKeyResult.valid) {
+ return sendInsufficientRole(reply, permission);
+ }
+ return reply.status(401).send({ error: "Unauthorized" });
};
}
diff --git a/server/src/lib/auth-utils.test.ts b/server/src/lib/auth-utils.test.ts
index e5b9a43b1..157800dbb 100644
--- a/server/src/lib/auth-utils.test.ts
+++ b/server/src/lib/auth-utils.test.ts
@@ -53,15 +53,21 @@ import {
getUserHasAdminAccessToSite,
getRequestIdentity,
getUserIdFromRequest,
+ getOrganizationSitesForCaller,
+ getUserHasSitePermission,
+ getUserOrgRole,
+ getUserSiteRole,
invalidateSitesAccessCache,
} from "./auth-utils.js";
import {
filterSitesByMemberAccess,
getOrgMembership,
+ grantsInOrganization,
isOrgAdmin,
isOrgOwner,
memberCanAccessSite,
resolveMemberSiteGrants,
+ resolveUserSiteRole,
restrictedMemberSiteIds,
siteIdsInOrganization,
} from "./access.js";
@@ -82,6 +88,7 @@ CREATE TABLE "member_site_access" (
"id" serial PRIMARY KEY,
"member_id" text NOT NULL,
"site_id" integer NOT NULL,
+ "role" text,
"created_at" timestamp NOT NULL DEFAULT now(),
"created_by" text
);
@@ -104,6 +111,7 @@ CREATE TABLE "team_site_access" (
"id" serial PRIMARY KEY,
"team_id" text NOT NULL,
"site_id" integer NOT NULL,
+ "role" text,
"created_at" timestamp NOT NULL DEFAULT now()
);
CREATE TABLE "sites" (
@@ -336,11 +344,14 @@ describe("restrictedMemberSiteIds matches the restricted branch of memberCanAcce
const universe = Array.from({ length: 13 }, (_, i) => i + 1);
async function grantsFor(restricted: boolean) {
- return resolveMemberSiteGrants({
- userId: "user_peer",
- organizationIds: [ORG],
- grantedMemberIds: restricted ? ["member_peer"] : [],
- });
+ return grantsInOrganization(
+ await resolveMemberSiteGrants({
+ userId: "user_peer",
+ organizationIds: [ORG],
+ grantedMemberIds: restricted ? ["member_peer"] : [],
+ }),
+ ORG
+ );
}
it("enumerates exactly the sites the predicate admits, for a member on a team", async () => {
@@ -630,6 +641,321 @@ describe("checkApiKey β€” organization-owned keys", () => {
});
});
+describe("per-site roles", () => {
+ it("attaches the caller's role to every site they can reach", async () => {
+ invalidateSitesAccessCache("user_peer");
+ invalidateSitesAccessCache("user_owner");
+ const peerSites = await getSitesUserHasAccessTo(reqFor("user_peer"));
+ const ownerSites = await getSitesUserHasAccessTo(reqFor("user_owner"));
+
+ expect(new Set(peerSites.map(site => site.accessRole))).toEqual(new Set(["member"]));
+ expect(new Set(ownerSites.map(site => site.accessRole))).toEqual(new Set(["owner"]));
+ });
+
+ it("answers a site role for reachable sites and null otherwise", async () => {
+ invalidateSitesAccessCache("user_peer");
+ expect(await getUserSiteRole(reqFor("user_peer"), 1)).toBe("member");
+ expect(await getUserSiteRole(reqFor("user_peer"), 12)).toBeNull();
+ expect(await getUserSiteRole(reqFor("user_owner"), 12)).toBe("owner");
+ });
+
+ it("holds editors and viewers to site grants and teams like members", async () => {
+ await db.insert(member).values([
+ { id: "member_editor", organizationId: ORG, userId: "user_editor", role: "editor", createdAt: NOW },
+ {
+ id: "member_viewer",
+ organizationId: ORG,
+ userId: "user_viewer",
+ role: "viewer",
+ createdAt: NOW,
+ hasRestrictedSiteAccess: true,
+ },
+ ]);
+ await db.insert(memberSiteAccess).values({ memberId: "member_viewer", siteId: 5 });
+
+ // Unrestricted, on no team: only the site no team gates.
+ expect(await siteIdsFor("user_editor")).toEqual([13]);
+ expect(await getUserSiteRole(reqFor("user_editor"), 13)).toBe("editor");
+ expect(await siteIdsFor("user_viewer")).toEqual([5]);
+ expect(await getUserSiteRole(reqFor("user_viewer"), 5)).toBe("viewer");
+ });
+
+ it("gives a membership with an unknown role no access at all", async () => {
+ await db.insert(member).values({
+ id: "member_odd",
+ organizationId: ORG,
+ userId: "user_odd",
+ role: "superuser",
+ createdAt: NOW,
+ });
+
+ expect(await siteIdsFor("user_odd")).toEqual([]);
+ });
+
+ it("filters to admin-role sites when asked", async () => {
+ invalidateSitesAccessCache("user_peer");
+ expect(await getSitesUserHasAccessTo(reqFor("user_peer"), true)).toEqual([]);
+ expect((await getSitesUserHasAccessTo(reqFor("user_owner"), true)).length).toBe(13);
+ });
+});
+
+describe("per-site roles from grants and teams", () => {
+ it("gives a restricted member the role their grant carries", async () => {
+ await db.insert(member).values({
+ id: "member_client",
+ organizationId: ORG,
+ userId: "user_client",
+ role: "viewer",
+ createdAt: NOW,
+ hasRestrictedSiteAccess: true,
+ });
+ await db.insert(memberSiteAccess).values([
+ { memberId: "member_client", siteId: 5, role: "editor" },
+ { memberId: "member_client", siteId: 6, role: null },
+ ]);
+
+ invalidateSitesAccessCache("user_client");
+ expect(await getUserSiteRole(reqFor("user_client"), 5)).toBe("editor");
+ // A grant without a role of its own carries the organization role.
+ expect(await getUserSiteRole(reqFor("user_client"), 6)).toBe("viewer");
+ expect(await getUserSiteRole(reqFor("user_client"), 7)).toBeNull();
+ });
+
+ it("raises a team member's role on the team's sites only", async () => {
+ await db.update(teamSiteAccess).set({ role: "editor" }).where(eq(teamSiteAccess.teamId, "team_bbc"));
+
+ invalidateSitesAccessCache("user_peer");
+ expect(await getUserSiteRole(reqFor("user_peer"), 1)).toBe("editor");
+ expect(await getUserSiteRole(reqFor("user_peer"), 13)).toBe("member");
+ });
+
+ it("never lowers a role below the member's organization role", async () => {
+ await db.update(teamSiteAccess).set({ role: "viewer" }).where(eq(teamSiteAccess.teamId, "team_bbc"));
+ await db.update(member).set({ role: "editor" }).where(eq(member.id, "member_peer"));
+
+ invalidateSitesAccessCache("user_peer");
+ // The team grant says viewer; the member's own role is higher and stands.
+ expect(await getUserSiteRole(reqFor("user_peer"), 1)).toBe("editor");
+ });
+
+ it("ignores a grant naming a role grants cannot carry", async () => {
+ await db.insert(member).values({
+ id: "member_forged",
+ organizationId: ORG,
+ userId: "user_forged",
+ role: "viewer",
+ createdAt: NOW,
+ hasRestrictedSiteAccess: true,
+ });
+ await db.insert(memberSiteAccess).values({ memberId: "member_forged", siteId: 5, role: "owner" });
+
+ expect(await siteIdsFor("user_forged")).toEqual([]);
+ });
+
+ it("ignores a grant its organization wrote for a site that has since moved away", async () => {
+ // user_client is a viewer in both organizations; ORG's editor grant on
+ // site 5 was written (or raced in) after site 5 moved to org_new.
+ await db.insert(member).values([
+ {
+ id: "m_client_old",
+ organizationId: ORG,
+ userId: "user_client2",
+ role: "viewer",
+ createdAt: NOW,
+ hasRestrictedSiteAccess: true,
+ },
+ { id: "m_client_new", organizationId: "org_new", userId: "user_client2", role: "viewer", createdAt: NOW },
+ ]);
+ await db.insert(memberSiteAccess).values({ memberId: "m_client_old", siteId: 5, role: "editor" });
+ await db.update(sites).set({ organizationId: "org_new" }).where(eq(sites.siteId, 5));
+
+ invalidateSitesAccessCache("user_client2");
+ expect(await getUserSiteRole(reqFor("user_client2"), 5)).toBe("viewer");
+ });
+
+ it("treats a restricted member as a viewer across the organization", async () => {
+ await db.insert(member).values({
+ id: "member_restricted_editor",
+ organizationId: ORG,
+ userId: "user_restricted_editor",
+ role: "editor",
+ createdAt: NOW,
+ hasRestrictedSiteAccess: true,
+ });
+ await db.insert(memberSiteAccess).values({ memberId: "member_restricted_editor", siteId: 5 });
+
+ expect(await getUserOrgRole(reqFor("user_restricted_editor"), ORG)).toBe("viewer");
+ invalidateSitesAccessCache("user_restricted_editor");
+ expect(await getUserSiteRole(reqFor("user_restricted_editor"), 5)).toBe("editor");
+ });
+});
+
+describe("getUserHasSitePermission", () => {
+ it("decides anything beyond reading on the current role, not a cached one", async () => {
+ invalidateSitesAccessCache("user_owner");
+ expect(await getUserSiteRole(reqFor("user_owner"), 13)).toBe("owner"); // warms the cache
+
+ // Demoted elsewhere (another worker): nothing invalidates this cache.
+ await db.update(member).set({ role: "viewer" }).where(eq(member.id, "member_owner"));
+
+ expect(await getUserHasSitePermission(reqFor("user_owner"), 13, "gsc:write")).toBe(false);
+ expect(await getUserHasSitePermission(reqFor("user_owner"), 13, "analytics:read")).toBe(true);
+ });
+});
+
+describe("resolving one site agrees with resolving the list", () => {
+ it("gives every user the same role on every site either way", async () => {
+ // A spread of shapes: owner, unrestricted member on a team (team role
+ // raised to editor), restricted viewer with a raised and a plain grant, an
+ // unknown role, a stale grant from an organization the site has left.
+ await db.update(teamSiteAccess).set({ role: "editor" }).where(eq(teamSiteAccess.teamId, "team_bbc"));
+ await db.insert(member).values([
+ {
+ id: "m_v",
+ organizationId: ORG,
+ userId: "user_v",
+ role: "viewer",
+ createdAt: NOW,
+ hasRestrictedSiteAccess: true,
+ },
+ { id: "m_odd", organizationId: ORG, userId: "user_odd2", role: "superuser", createdAt: NOW },
+ { id: "m_other", organizationId: "org_other", userId: "user_v", role: "viewer", createdAt: NOW },
+ ]);
+ await db.insert(memberSiteAccess).values([
+ { memberId: "m_v", siteId: 3, role: "editor" },
+ { memberId: "m_v", siteId: 13, role: null },
+ { memberId: "m_other", siteId: 4, role: "editor" },
+ ]);
+
+ for (const userId of ["user_owner", "user_peer", "user_v", "user_odd2", "user_nobody"]) {
+ invalidateSitesAccessCache(userId);
+ const listed = await getSitesUserHasAccessTo(reqFor(userId));
+ for (let siteId = 1; siteId <= 13; siteId++) {
+ const fromList = listed.find(site => site.siteId === siteId)?.accessRole ?? null;
+ expect(await resolveUserSiteRole(userId, siteId), `${userId} on site ${siteId}`).toBe(fromList);
+ }
+ }
+ });
+});
+
+describe("getOrganizationSitesForCaller", () => {
+ it("returns only that organization's sites the caller reaches, with their roles", async () => {
+ await db.insert(sites).values({
+ id: "hex_other_org",
+ siteId: 700,
+ name: "other",
+ domain: "other.example.com",
+ organizationId: "org_other",
+ });
+ await db
+ .insert(member)
+ .values({
+ id: "m_owner_other",
+ organizationId: "org_other",
+ userId: "user_owner",
+ role: "owner",
+ createdAt: NOW,
+ });
+
+ const peerSites = await getOrganizationSitesForCaller(reqFor("user_peer"), ORG);
+ expect(peerSites.map(site => site.siteId).sort((a, b) => a - b)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13]);
+ const ownerSites = await getOrganizationSitesForCaller(reqFor("user_owner"), ORG);
+ expect(ownerSites).toHaveLength(13);
+ expect(ownerSites.every(site => site.organizationId === ORG && site.accessRole === "owner")).toBe(true);
+ });
+});
+
+describe("getUserOrgRole", () => {
+ it("reads the membership role", async () => {
+ expect(await getUserOrgRole(reqFor("user_peer"), ORG)).toBe("member");
+ expect(await getUserOrgRole(reqFor("user_owner"), ORG)).toBe("owner");
+ expect(await getUserOrgRole(reqFor("user_nobody"), ORG)).toBeNull();
+ });
+
+ it("treats an organization key as admin of its own organization only", async () => {
+ const orgKey = (organizationId: string) =>
+ ({ headers: {}, query: {}, apiKeyOrganizationId: organizationId }) as any;
+
+ expect(await getUserOrgRole(orgKey(ORG), ORG)).toBe("admin");
+ expect(await getUserOrgRole(orgKey("org_other"), ORG)).toBeNull();
+ });
+});
+
+// A personal key or OAuth token must reach exactly the sites its user's
+// browser session reaches β€” the guards trust checkApiKey before they consult
+// the session, so a key that ignored member/team restrictions would be a way
+// around them.
+describe("checkApiKey β€” user credentials honour site restrictions", () => {
+ const request = () => ({ headers: { authorization: "Bearer rb_user_key" }, query: {} }) as any;
+ const userKey = (userId: string) =>
+ ({ valid: true, key: { referenceId: userId, permissions: null, configId: "default" } }) as any;
+
+ beforeEach(async () => {
+ vi.mocked(auth.api.verifyApiKey).mockReset();
+ vi.mocked(auth.api.verifyRybbitOAuthToken as any).mockReset();
+ vi.mocked(auth.api.verifyRybbitOAuthToken as any).mockResolvedValue(null);
+ await db.insert(member).values({
+ id: "member_restricted",
+ organizationId: ORG,
+ userId: "user_restricted",
+ role: "member",
+ createdAt: NOW,
+ hasRestrictedSiteAccess: true,
+ });
+ await db.insert(memberSiteAccess).values({ memberId: "member_restricted", siteId: 13 });
+ await db.insert(sites).values({
+ id: "hex_elsewhere",
+ siteId: 900,
+ name: "elsewhere",
+ domain: "elsewhere.example.com",
+ organizationId: "org_elsewhere",
+ });
+ });
+
+ it("admits a restricted member's key on a granted site", async () => {
+ vi.mocked(auth.api.verifyApiKey).mockResolvedValue(userKey("user_restricted"));
+
+ const result = await checkApiKey(request(), { siteId: 13 });
+
+ expect(result.valid).toBe(true);
+ expect(result.role).toBe("member");
+ });
+
+ it("rejects a restricted member's key on an ungranted site in the same organization", async () => {
+ vi.mocked(auth.api.verifyApiKey).mockResolvedValue(userKey("user_restricted"));
+
+ const result = await checkApiKey(request(), { siteId: 1 });
+
+ expect(result.valid).toBe(false);
+ expect(result.role).toBeNull();
+ });
+
+ it("rejects an unrestricted member's key on a site gated by a team they are not on", async () => {
+ vi.mocked(auth.api.verifyApiKey).mockResolvedValue(userKey("user_peer"));
+
+ expect((await checkApiKey(request(), { siteId: 12 })).valid).toBe(false);
+ expect((await checkApiKey(request(), { siteId: 1 })).valid).toBe(true);
+ });
+
+ it("lets an owner's key reach every site of the organization", async () => {
+ vi.mocked(auth.api.verifyApiKey).mockResolvedValue(userKey("user_owner"));
+
+ expect((await checkApiKey(request(), { siteId: 12 })).valid).toBe(true);
+ });
+
+ it("rejects a site outside the organization named alongside it", async () => {
+ vi.mocked(auth.api.verifyApiKey).mockResolvedValue(userKey("user_owner"));
+
+ expect((await checkApiKey(request(), { organizationId: ORG, siteId: 900 })).valid).toBe(false);
+ });
+
+ it("still validates org-level requests on membership alone", async () => {
+ vi.mocked(auth.api.verifyApiKey).mockResolvedValue(userKey("user_restricted"));
+
+ expect((await checkApiKey(request(), { organizationId: ORG })).valid).toBe(true);
+ });
+});
+
// 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
diff --git a/server/src/lib/auth-utils.ts b/server/src/lib/auth-utils.ts
index b056d41e8..553b2d85d 100644
--- a/server/src/lib/auth-utils.ts
+++ b/server/src/lib/auth-utils.ts
@@ -1,9 +1,17 @@
-import { and, eq, inArray } from "drizzle-orm";
+import { eq } from "drizzle-orm";
import { FastifyRequest } from "fastify";
import NodeCache from "node-cache";
import { db } from "../db/postgres/postgres.js";
-import { member, sites, user } from "../db/postgres/schema.js";
-import { getOrgMembership, memberCanAccessSite, resolveMemberSiteGrants, restrictedMemberSiteIds } from "./access.js";
+import { sites, user } from "../db/postgres/schema.js";
+import { higherRole, isAdminRole, PERMISSIONS, roleHasPermission, type OrgRole, type Permission } from "@rybbit/shared";
+import {
+ effectiveOrgRole,
+ getOrgMembership,
+ resolveUserSites,
+ resolveUserSiteRole,
+ siteIdsInOrganization,
+ type AccessibleSite,
+} from "./access.js";
import type { RateLimitDecision } from "./apiRateLimit.js";
import { consumeRateLimitForIdentity } from "./apiRateLimitPolicy.js";
import { auth } from "./auth.js";
@@ -15,7 +23,7 @@ import {
resolveBearerIdentity,
type BearerResolverDeps,
} from "./bearerAuth.js";
-import { hasScope, type ScopeRequirement, type ScopeStatements } from "./scopes.js";
+import { type ScopeStatements } from "./scopes.js";
import { siteConfig } from "./siteConfig.js";
import { logger } from "./logger/logger.js";
@@ -120,19 +128,21 @@ 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) {
+// All sites of an organization, for org-owned API keys, which act with admin
+// authority over exactly that organization. Cached under an "org:"-prefixed
+// key (org and user ids never collide, the prefix is hygiene).
+async function getSitesForOrganization(organizationId: string): Promise<AccessibleSite[]> {
const cacheKey = `org:${organizationId}`;
- const cached = sitesAccessCache.get<Promise<any[]>>(cacheKey);
+ const cached = sitesAccessCache.get<Promise<AccessibleSite[]>>(cacheKey);
if (cached) {
return cached;
}
const promise = (async () => {
try {
- return await db.select().from(sites).where(eq(sites.organizationId, organizationId));
+ const orgSites = await db.select().from(sites).where(eq(sites.organizationId, organizationId));
+ return orgSites.map(site => ({ ...site, accessRole: "admin" as const }));
} catch (error) {
console.error("Error getting sites for organization:", error);
sitesAccessCache.del(cacheKey);
@@ -144,134 +154,21 @@ async function getSitesForOrganization(organizationId: string) {
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;
-
- if (!userId) {
- return [];
- }
+// Cache keys for one user's site list. A browser session may carry
+// system-admin authority; a bearer credential for the same user never does,
+// so the two are cached apart.
+const sessionSitesKey = (userId: string) => `${userId}:session`;
+const bearerSitesKey = (userId: string) => `${userId}:bearer`;
- // Create cache key
- const cacheKey = `${userId}:${adminOnly}`;
-
- // Check if we have a cached promise
- const cached = sitesAccessCache.get<Promise<any[]>>(cacheKey);
+function cachedSites(cacheKey: string, load: () => Promise<AccessibleSite[]>): Promise<AccessibleSite[]> {
+ const cached = sitesAccessCache.get<Promise<AccessibleSite[]>>(cacheKey);
if (cached) {
return cached;
}
- // Create new promise and cache it
const promise = (async () => {
try {
- const [isAdmin, memberRecords] = await Promise.all([
- getIsUserAdmin(req),
- db
- .select({
- id: member.id,
- organizationId: member.organizationId,
- role: member.role,
- hasRestrictedSiteAccess: member.hasRestrictedSiteAccess,
- })
- .from(member)
- .where(eq(member.userId, userId)),
- ]);
-
- if (isAdmin) {
- const allSites = await db.select().from(sites);
- return allSites;
- }
-
- if (!memberRecords || memberRecords.length === 0) {
- return [];
- }
-
- // Two kinds of membership:
- // - admin/owner (and any non-"member" role): every site of the org, no
- // team gating
- // - "member": the org's sites filtered by the shared Site Access rule
- const fullAccessOrgIds: string[] = [];
- const memberRowByOrgId = new Map<string, (typeof memberRecords)[0]>();
-
- for (const record of memberRecords) {
- // If adminOnly is true, skip members with "member" role
- if (adminOnly && record.role === "member") {
- continue;
- }
-
- if (record.role === "member") {
- memberRowByOrgId.set(record.organizationId, record);
- } else {
- fullAccessOrgIds.push(record.organizationId);
- }
- }
-
- const memberOrgIds = Array.from(memberRowByOrgId.keys());
- const restrictedMembers = Array.from(memberRowByOrgId.values()).filter(record => record.hasRestrictedSiteAccess);
- const restrictedOrgIds = restrictedMembers.map(record => record.organizationId);
-
- // A restricted membership reaches a closed set of sites, so its
- // organization is loaded by id below rather than read in full and
- // discarded β€” an org can hold far more sites than one member is granted.
- const restrictedOrgIdSet = new Set(restrictedOrgIds);
- const eagerOrgIds = Array.from(
- new Set([...fullAccessOrgIds, ...memberOrgIds.filter(id => !restrictedOrgIdSet.has(id))])
- );
-
- if (eagerOrgIds.length === 0 && restrictedOrgIds.length === 0) {
- return [];
- }
-
- const [eagerSites, grants] = await Promise.all([
- eagerOrgIds.length > 0
- ? db.select().from(sites).where(inArray(sites.organizationId, eagerOrgIds))
- : Promise.resolve([]),
- memberOrgIds.length > 0
- ? resolveMemberSiteGrants({
- userId,
- organizationIds: memberOrgIds,
- grantedMemberIds: restrictedMembers.map(record => record.id),
- })
- : null,
- ]);
-
- if (!grants) {
- return eagerSites;
- }
-
- const accessible = eagerSites.filter(site => {
- const memberRow = site.organizationId ? memberRowByOrgId.get(site.organizationId) : undefined;
- // No member row for the org means admin/owner authority over it.
- if (!memberRow) {
- return true;
- }
- return memberCanAccessSite(grants, site.siteId, memberRow.hasRestrictedSiteAccess);
- });
-
- if (restrictedOrgIds.length > 0) {
- const candidateSiteIds = restrictedMemberSiteIds(grants);
- if (candidateSiteIds.length > 0) {
- const grantedSites = await db
- .select()
- .from(sites)
- .where(and(inArray(sites.siteId, candidateSiteIds), inArray(sites.organizationId, restrictedOrgIds)));
- const seen = new Set(accessible.map(site => site.siteId));
- for (const site of grantedSites) {
- if (!seen.has(site.siteId)) {
- accessible.push(site);
- }
- }
- }
- }
-
- return accessible;
+ return await load();
} catch (error) {
console.error("Error getting sites user has access to:", error);
// Remove from cache on error so it can be retried
@@ -280,16 +177,67 @@ export async function getSitesUserHasAccessTo(req: FastifyRequest, adminOnly = f
}
})();
- // Cache the promise
sitesAccessCache.set(cacheKey, promise);
-
return promise;
}
+/** The sites a user reaches through a bearer credential: memberships only. */
+function getBearerUserSites(userId: string): Promise<AccessibleSite[]> {
+ return cachedSites(bearerSitesKey(userId), () => resolveUserSites(userId));
+}
+
+/**
+ * The sites a browser session reaches: its memberships, plus admin authority
+ * over every site when the user is a Better Auth system admin.
+ */
+function getSessionUserSites(req: FastifyRequest, userId: string): Promise<AccessibleSite[]> {
+ return cachedSites(sessionSitesKey(userId), async () => {
+ const [isSystemAdmin, memberSites] = await Promise.all([getIsUserAdmin(req), resolveUserSites(userId)]);
+ if (!isSystemAdmin) {
+ return memberSites;
+ }
+ const memberRoleBySite = new Map(memberSites.map(site => [site.siteId, site.accessRole]));
+ const allSites = await db.select().from(sites);
+ return allSites.map(site => ({
+ ...site,
+ accessRole: higherRole(memberRoleBySite.get(site.siteId), "admin") ?? "admin",
+ }));
+ });
+}
+
+/**
+ * Every site the caller can reach, each with the role they hold on it.
+ * `adminOnly` narrows to sites where that role is admin or owner. `fresh`
+ * skips this worker's short-lived cache β€” for listings, where a site created,
+ * deleted or granted moments ago (possibly through another worker) must show.
+ */
+export async function getSitesUserHasAccessTo(req: FastifyRequest, adminOnly = false): Promise<AccessibleSite[]> {
+ let accessible: AccessibleSite[];
+
+ // Organization-owned API key (attached by the auth guards).
+ if (!req.user?.id && req.apiKeyOrganizationId) {
+ accessible = await getSitesForOrganization(req.apiKeyOrganizationId);
+ } else {
+ const session = req.user?.id ? null : await getSessionFromReq(req);
+ const userId = req.user?.id ?? session?.user.id;
+ if (!userId) {
+ return [];
+ }
+ accessible = req.bearerAuth ? await getBearerUserSites(userId) : await getSessionUserSites(req, userId);
+ }
+
+ return adminOnly ? accessible.filter(site => isAdminRole(site.accessRole)) : accessible;
+}
+
+/** Drop an organization-owned key's cached site list (after a site leaves or joins the organization). */
+export function invalidateOrganizationSitesCache(organizationId: string) {
+ sitesAccessCache.del(`org:${organizationId}`);
+}
+
// Cache invalidation helper - call this when member site access changes
export function invalidateSitesAccessCache(userId: string) {
- sitesAccessCache.del(`${userId}:true`);
- sitesAccessCache.del(`${userId}:false`);
+ sitesAccessCache.del(sessionSitesKey(userId));
+ sitesAccessCache.del(bearerSitesKey(userId));
}
/**
@@ -322,28 +270,54 @@ async function resolveTargetOrganizationId(options: {
}
/**
- * Resolve the org membership role for a bearer-authenticated user, scoped to
- * either an explicit organization or the organization owning a site.
+ * Resolve the role a bearer-authenticated user holds for a request: on the
+ * named site (the same per-site rule as their browser session, so a personal
+ * key or OAuth token is held to member and team site restrictions), or else in
+ * the named organization.
*/
-async function resolveBearerUserOrgRole(
+async function resolveBearerUserRole(
userId: string,
- options: { organizationId?: string; siteId?: string | number }
+ options: { organizationId?: string; siteId?: string | number; fresh?: boolean }
): 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 organization
- const userMembership = await db
- .select()
- .from(member)
- .where(and(eq(member.userId, userId), eq(member.organizationId, organizationId)))
- .limit(1);
+ const denied = { valid: false, role: null };
+
+ if (options.siteId !== undefined && options.siteId !== null && options.siteId !== "") {
+ const siteId = Number(options.siteId);
+ if (!Number.isInteger(siteId)) {
+ return denied;
+ }
+ if (options.fresh) {
+ // Decided on this one site, straight from the database.
+ const [role, inOrganization] = await Promise.all([
+ resolveUserSiteRole(userId, siteId),
+ options.organizationId ? siteIdsInOrganization([siteId], options.organizationId) : null,
+ ]);
+ if (!role || (inOrganization && inOrganization.length === 0)) {
+ return denied;
+ }
+ return { valid: true, role, userId };
+ }
+ const findSite = (list: AccessibleSite[]) => list.find(site => site.siteId === siteId);
+ let site = findSite(await getBearerUserSites(userId));
+ if (!site) {
+ // Never let a cached miss deny a grant made in the last few seconds.
+ invalidateSitesAccessCache(userId);
+ site = findSite(await getBearerUserSites(userId));
+ }
+ if (!site || (options.organizationId && site.organizationId !== options.organizationId)) {
+ return denied;
+ }
+ return { valid: true, role: site.accessRole, userId };
+ }
- if (userMembership.length > 0) {
- return { valid: true, role: userMembership[0].role, userId };
+ if (options.organizationId) {
+ const role = effectiveOrgRole(await getOrgMembership(userId, options.organizationId));
+ if (role) {
+ return { valid: true, role, userId };
}
}
- return { valid: false, role: null };
+
+ return denied;
}
export interface BearerAuthResult {
@@ -370,7 +344,9 @@ export interface BearerAuthResult {
*/
export async function checkApiKey(
req: FastifyRequest,
- options: { organizationId?: string; siteId?: string | number }
+ // fresh: resolve the user's site role from the database rather than this
+ // worker's short-lived cache β€” for permissions that change something.
+ options: { organizationId?: string; siteId?: string | number; fresh?: boolean }
): Promise<BearerAuthResult> {
const apiKey = resolveBearerTokenFromRequest(req);
if (!apiKey) {
@@ -407,7 +383,7 @@ export async function checkApiKey(
return { valid: false, role: null, rateLimit: identity.rateLimit, statements: null };
}
if (identity.status === "valid" && identity.userId) {
- const membership = await resolveBearerUserOrgRole(identity.userId, options);
+ const membership = await resolveBearerUserRole(identity.userId, options);
return { ...membership, rateLimit: identity.rateLimit, statements: identity.statements };
}
return { valid: false, role: null, statements: null };
@@ -458,65 +434,167 @@ export async function getUserIdFromRequest(req: FastifyRequest): Promise<string
return (await getRequestIdentity(req)).userId;
}
-// for routes that are potentially public
-export async function getUserHasAccessToSitePublic(
- req: FastifyRequest,
- siteId: string | number,
- requiredScope?: ScopeRequirement
-) {
- const [hasDirectAccess, config] = await Promise.all([
- getUserHasAccessToSite(req, siteId),
- siteConfig.getConfig(siteId),
- ]);
-
- // Check if user has direct access to the site
- if (hasDirectAccess) {
- return true;
- }
+/**
+ * Whether anyone may read the site without a role on it: it is public, or the
+ * request carries its current private link key.
+ */
+export async function getSiteIsPubliclyReadable(req: FastifyRequest, siteId: string | number): Promise<boolean> {
+ const config = await siteConfig.getConfig(siteId);
- // Check if site is public
if (config?.public) {
return true;
}
- // Check if a valid private key was provided in the header
const privateKey = req.headers["x-private-key"];
if (privateKey && typeof privateKey === "string" && config?.privateLinkKey === privateKey) {
+ // Another worker may have revoked the key since this one cached it.
const fresh = await siteConfig.reload(siteId);
return fresh?.privateLinkKey === privateKey;
}
- // Bearer-credential fallback. Scopes apply here too β€” without this check a
- // scoped key could reach any public-guard route on a private site.
- const result = await checkApiKey(req, { siteId });
- if (result.valid && (!requiredScope || hasScope(result.statements, requiredScope))) {
- return true;
+ return false;
+}
+
+/**
+ * One organization's sites the caller can reach, each with their role on it,
+ * read straight from the database (no cache) β€” for listings, where a site
+ * created, deleted, moved or granted moments ago, possibly through another
+ * worker, must show correctly, and for raw-data access that must not outlive
+ * a revoked grant. Loads only that organization.
+ */
+export async function getOrganizationSitesForCaller(
+ req: FastifyRequest,
+ organizationId: string
+): Promise<AccessibleSite[]> {
+ if (!req.user?.id && req.apiKeyOrganizationId) {
+ if (req.apiKeyOrganizationId !== organizationId) {
+ return [];
+ }
+ invalidateOrganizationSitesCache(organizationId);
+ return getSitesForOrganization(organizationId);
}
- return false;
+ const userId = req.user?.id ?? (await getSessionFromReq(req))?.user.id;
+ if (!userId) {
+ return [];
+ }
+ const [memberSites, isSystemAdmin] = await Promise.all([
+ resolveUserSites(userId, { organizationId }),
+ req.bearerAuth ? false : getIsUserAdmin(req),
+ ]);
+ if (!isSystemAdmin) {
+ return memberSites;
+ }
+ const memberRoleBySite = new Map(memberSites.map(site => [site.siteId, site.accessRole]));
+ const orgSites = await db.select().from(sites).where(eq(sites.organizationId, organizationId));
+ return orgSites.map(site => ({
+ ...site,
+ accessRole: higherRole(memberRoleBySite.get(site.siteId), "admin") ?? "admin",
+ }));
+}
+
+/**
+ * The role the caller holds on one site, straight from the database: the
+ * `fresh` path of {@link getUserSiteRole}. Reads only that site's
+ * organization, membership and grants.
+ */
+async function resolveCallerSiteRole(req: FastifyRequest, siteId: number): Promise<OrgRole | null> {
+ if (!req.user?.id && req.apiKeyOrganizationId) {
+ const [inOrganization] = await siteIdsInOrganization([siteId], req.apiKeyOrganizationId);
+ return inOrganization === undefined ? null : "admin";
+ }
+
+ const userId = req.user?.id ?? (await getSessionFromReq(req))?.user.id;
+ if (!userId) {
+ return null;
+ }
+ const [role, isSystemAdmin] = await Promise.all([
+ resolveUserSiteRole(userId, siteId),
+ req.bearerAuth ? false : getIsUserAdmin(req),
+ ]);
+ if (!isSystemAdmin) {
+ return role;
+ }
+ // System admins act as admin on every existing site.
+ const [site] = await db.select({ siteId: sites.siteId }).from(sites).where(eq(sites.siteId, siteId)).limit(1);
+ return site ? (higherRole(role, "admin") ?? "admin") : null;
}
-async function hasSiteAccess(req: FastifyRequest, siteId: string | number, adminOnly: boolean): Promise<boolean> {
- const matches = (accessible: { siteId: number }[]) => accessible.some(site => site.siteId === Number(siteId));
- if (matches(await getSitesUserHasAccessTo(req, adminOnly))) return true;
+/**
+ * The role the caller holds on a site, or null when they cannot reach it.
+ * `fresh` reads it from the database instead of this worker's short-lived
+ * cache, so a demotion, removal or site move made moments ago (possibly on
+ * another worker) already applies; it looks at that one site only.
+ */
+export async function getUserSiteRole(
+ req: FastifyRequest,
+ siteId: string | number,
+ { fresh = false }: { fresh?: boolean } = {}
+): Promise<OrgRole | null> {
+ if (fresh) {
+ const id = Number(siteId);
+ return Number.isInteger(id) ? resolveCallerSiteRole(req, id) : null;
+ }
+ const find = (accessible: AccessibleSite[]) =>
+ accessible.find(site => site.siteId === Number(siteId))?.accessRole ?? null;
+ const role = find(await getSitesUserHasAccessTo(req));
+ if (role) return role;
// A claim may have committed in another worker while this one still holds
// the user's pre-claim site list. Never let a cached miss deny a new grant.
const userId = req.user?.id ?? (await getSessionFromReq(req))?.user.id;
- if (!userId) return false;
+ if (!userId) return null;
invalidateSitesAccessCache(userId);
- return matches(await getSitesUserHasAccessTo(req, adminOnly));
+ return find(await getSitesUserHasAccessTo(req));
+}
+
+/**
+ * Whether the caller's role on the site holds the permission (roles only;
+ * scopes are the guards' job). Like the route guards, anything beyond reading
+ * is decided on the role as it stands now, not this worker's cached copy.
+ */
+export async function getUserHasSitePermission(
+ req: FastifyRequest,
+ siteId: string | number,
+ permission: Permission
+): Promise<boolean> {
+ const fresh = PERMISSIONS[permission].minRole !== "viewer";
+ return roleHasPermission(await getUserSiteRole(req, siteId, { fresh }), permission);
}
export async function getUserHasAccessToSite(req: FastifyRequest, siteId: string | number) {
- return hasSiteAccess(req, siteId, false);
+ return (await getUserSiteRole(req, siteId)) !== null;
}
export async function getUserHasAdminAccessToSite(req: FastifyRequest, siteId: string | number) {
- return hasSiteAccess(req, siteId, true);
+ return isAdminRole(await getUserSiteRole(req, siteId));
}
-export async function getUserIsInOrg(req: FastifyRequest, organizationId: string): Promise<boolean> {
+/**
+ * The role the caller holds in an organization: their membership role, admin
+ * for a system-admin browser session, admin for the organization's own API
+ * key. Null when they are not in it.
+ */
+export async function getUserOrgRole(req: FastifyRequest, organizationId: string): Promise<OrgRole | null> {
+ if (!req.user?.id && req.apiKeyOrganizationId) {
+ return req.apiKeyOrganizationId === organizationId ? "admin" : null;
+ }
const userId = req.user?.id ?? (await getSessionFromReq(req))?.user.id;
- return (await getOrgMembership(userId, organizationId)) !== null;
+ if (!userId) {
+ return null;
+ }
+ const [membership, isSystemAdmin] = await Promise.all([
+ getOrgMembership(userId, organizationId),
+ req.bearerAuth ? false : getIsUserAdmin(req),
+ ]);
+ return higherRole(effectiveOrgRole(membership), isSystemAdmin ? "admin" : null);
+}
+
+/** Whether the caller's organization role holds the permission (roles only; scopes are the guards' job). */
+export async function getUserHasOrgPermission(
+ req: FastifyRequest,
+ organizationId: string,
+ permission: Permission
+): Promise<boolean> {
+ return roleHasPermission(await getUserOrgRole(req, organizationId), permission);
}
diff --git a/server/src/lib/auth.ts b/server/src/lib/auth.ts
index 99e712c47..54777a364 100644
--- a/server/src/lib/auth.ts
+++ b/server/src/lib/auth.ts
@@ -8,13 +8,15 @@ import dotenv from "dotenv";
import { and, asc, eq, inArray } from "drizzle-orm";
import pg from "pg";
import { dash } from "@better-auth/infra";
-import { apiKey } from "@better-auth/api-key"
+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 { isAdminRole, isOrgRole, isSiteGrantRole, ORG_ROLES, SITE_GRANT_ROLES, type OrgRole } from "@rybbit/shared";
import { siteIdsInOrganization } from "./access.js";
import { apiKeyLimitForPlan, countApiKeysForReference } from "./apiKeyLimits.js";
+import { getMemberLimitError, getPlanMemberLimit } from "./memberLimits.js";
import { invalidateSitesAccessCache } from "./auth-utils.js";
import { ORG_API_KEY_CONFIG_ID } from "./bearerAuth.js";
import { DISABLE_SIGNUP, IS_CLOUD } from "./const.js";
@@ -42,11 +44,18 @@ const orgAccessControl = createAccessControl({
...defaultStatements,
apiKey: [...ORG_API_KEY_ACTIONS],
});
+//
+// Every role in ORG_ROLES (@rybbit/shared) must be registered here or
+// better-auth rejects it on invite and role change. Editors and viewers hold
+// no better-auth statements beyond a member's: what separates them is Rybbit's
+// own permission map, which the route guards enforce.
const orgRoles = {
owner: orgAccessControl.newRole({ ...ownerAc.statements, apiKey: [...ORG_API_KEY_ACTIONS] }),
admin: orgAccessControl.newRole({ ...adminAc.statements, apiKey: [...ORG_API_KEY_ACTIONS] }),
+ editor: orgAccessControl.newRole({ ...memberAc.statements }),
member: orgAccessControl.newRole({ ...memberAc.statements }),
-};
+ viewer: orgAccessControl.newRole({ ...memberAc.statements }),
+} satisfies Record<OrgRole, unknown>;
// Rate limiting moved out of the plugin and into lib/apiRateLimit.ts, which
// enforces a burst tier and a daily quota per credential *owner* rather than a
@@ -84,6 +93,10 @@ const pluginList = [
dash(),
organization({
allowUserToCreateOrganization: true,
+ // better-auth checks this whenever it adds a member itself β€” including
+ // accepting an invitation, which the invite-time check below can't
+ // cover. 100 is better-auth's own default, kept for unlimited plans.
+ membershipLimit: async (_user, org) => (await getPlanMemberLimit(org.id)) ?? 100,
creatorRole: "owner",
ac: orgAccessControl,
roles: orgRoles,
@@ -106,6 +119,7 @@ const pluginList = [
const invite = newInvitation as typeof newInvitation & {
hasRestrictedSiteAccess?: boolean;
siteIds?: number[];
+ siteRole?: string | null;
};
const hasRestrictedSiteAccess = invite.hasRestrictedSiteAccess === true;
@@ -114,13 +128,21 @@ const pluginList = [
data: {
hasRestrictedSiteAccess: false,
siteIds: [],
+ siteRole: null,
},
};
}
- if (invite.role !== "member") {
+ const siteRole = invite.siteRole ?? null;
+ if (siteRole !== null && !isSiteGrantRole(siteRole)) {
+ throw new APIError("BAD_REQUEST", {
+ message: `siteRole must be one of: ${SITE_GRANT_ROLES.join(", ")}`,
+ });
+ }
+
+ if (isAdminRole(invite.role)) {
throw new APIError("BAD_REQUEST", {
- message: "Site access restrictions can only be applied to member invitations",
+ message: "Site access restrictions cannot be applied to admin or owner invitations",
});
}
@@ -144,6 +166,7 @@ const pluginList = [
data: {
hasRestrictedSiteAccess: true,
siteIds: uniqueSiteIds,
+ siteRole,
},
};
},
@@ -184,6 +207,13 @@ const pluginList = [
defaultValue: [],
fieldName: "site_ids",
},
+ // Role on those sites; null = the invited role. Validated in
+ // beforeCreateInvitation.
+ siteRole: {
+ type: "string",
+ required: false,
+ fieldName: "site_role",
+ },
},
},
organization: {
@@ -227,11 +257,11 @@ const pluginList = [
// Add Cloudflare Turnstile captcha (cloud only)
...(IS_CLOUD && process.env.TURNSTILE_SECRET_KEY && process.env.NODE_ENV === "production"
? [
- captcha({
- provider: "cloudflare-turnstile",
- secretKey: process.env.TURNSTILE_SECRET_KEY,
- }),
- ]
+ captcha({
+ provider: "cloudflare-turnstile",
+ secretKey: process.env.TURNSTILE_SECRET_KEY,
+ }),
+ ]
: []),
];
@@ -260,14 +290,7 @@ export const auth = betterAuth({
disableSignUp: DISABLE_SIGNUP,
},
emailVerification: {
- sendVerificationEmail: async ({
- user,
- url,
- }: {
- user: { email: string };
- url: string;
- token: string;
- }) => {
+ sendVerificationEmail: async ({ user, url }: { user: { email: string }; url: string; token: string }) => {
await sendEmailVerificationLink(user.email, url);
},
},
@@ -373,7 +396,19 @@ export const auth = betterAuth({
},
},
hooks: {
- before: createAuthMiddleware(async (ctx) => {
+ before: createAuthMiddleware(async ctx => {
+ // better-auth accepts several roles at once (an array, stored
+ // comma-joined). Rybbit gives each membership exactly one role, and the
+ // access resolver denies anything else, so refuse it at the door.
+ if (ctx.path === "/organization/invite-member" || ctx.path === "/organization/update-member-role") {
+ const role = (ctx.body as { role?: unknown } | undefined)?.role;
+ if (!isOrgRole(role)) {
+ throw new APIError("BAD_REQUEST", {
+ message: `role must be one of: ${ORG_ROLES.join(", ")}`,
+ });
+ }
+ }
+
// 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
@@ -448,22 +483,9 @@ export const auth = betterAuth({
const organizationId = body?.organizationId;
if (organizationId) {
- // Lazy import to avoid circular dependency
- const { getSubscriptionInner } = await import("../api/stripe/getSubscription.js");
- const subscription = await getSubscriptionInner(organizationId);
- const memberLimit = subscription?.memberLimit ?? null;
-
- if (memberLimit !== null) {
- const members = await db
- .select({ id: member.id })
- .from(member)
- .where(eq(member.organizationId, organizationId));
-
- if (members.length >= memberLimit) {
- throw new APIError("FORBIDDEN", {
- message: `You have reached the limit of ${memberLimit} member${memberLimit === 1 ? "" : "s"} for your plan. Please upgrade to add more.`,
- });
- }
+ const memberLimitError = await getMemberLimitError(organizationId);
+ if (memberLimitError) {
+ throw new APIError("FORBIDDEN", { message: memberLimitError });
}
}
}
@@ -482,13 +504,14 @@ export const auth = betterAuth({
email: invitation.email,
hasRestrictedSiteAccess: invitation.hasRestrictedSiteAccess,
siteIds: invitation.siteIds,
+ siteRole: invitation.siteRole,
})
.from(invitation)
.where(eq(invitation.id, invitationId))
.limit(1);
if (invitationRecord.length === 0) return;
- const { organizationId, email, hasRestrictedSiteAccess, siteIds } = invitationRecord[0];
+ const { organizationId, email, hasRestrictedSiteAccess, siteIds, siteRole } = invitationRecord[0];
if (!hasRestrictedSiteAccess) return;
const userRecord = await db.select({ id: user.id }).from(user).where(eq(user.email, email)).limit(1);
@@ -534,6 +557,7 @@ export const auth = betterAuth({
grantableSiteIds.map(siteId => ({
memberId,
siteId,
+ role: isSiteGrantRole(siteRole) ? siteRole : null,
}))
);
}
diff --git a/server/src/lib/email/email.ts b/server/src/lib/email/email.ts
index dca9496e6..61fed911d 100644
--- a/server/src/lib/email/email.ts
+++ b/server/src/lib/email/email.ts
@@ -5,6 +5,7 @@ import { ApproachingLimitEmail } from "./templates/ApproachingLimitEmail.js";
import { InvitationEmail } from "./templates/InvitationEmail.js";
import { LimitExceededEmail } from "./templates/LimitExceededEmail.js";
import { OtpEmail, type OtpEmailType } from "./templates/OtpEmail.js";
+import { SiteTransferEmail } from "./templates/SiteTransferEmail.js";
import { WeeklyReportEmail } from "./templates/WeeklyReportEmail.js";
import type { SiteReport } from "../../services/weekyReports/weeklyReportTypes.js";
import { signExpiringPayload } from "../signedToken.js";
@@ -155,6 +156,17 @@ export const sendInvitationEmail = async (
await sendEmail(email, "You're Invited to Join an Organization on Rybbit", html);
};
+export const sendSiteTransferEmail = async (props: {
+ email: string;
+ sentBy: string;
+ siteDomain: string;
+ organizationName: string;
+ transferLink: string;
+}) => {
+ const html = await render(SiteTransferEmail(props));
+ await sendEmail(props.email, `${props.siteDomain} is being transferred to you on Rybbit`, html);
+};
+
export const sendLimitExceededEmail = async (
email: string,
organizationName: string,
diff --git a/server/src/lib/email/templates/SiteTransferEmail.tsx b/server/src/lib/email/templates/SiteTransferEmail.tsx
new file mode 100644
index 000000000..fe8edac8c
--- /dev/null
+++ b/server/src/lib/email/templates/SiteTransferEmail.tsx
@@ -0,0 +1,95 @@
+import {
+ Body,
+ Container,
+ Head,
+ Hr,
+ Html,
+ Img,
+ Link,
+ Preview,
+ Text,
+ Tailwind,
+ pixelBasedPreset,
+} from "@react-email/components";
+import * as React from "react";
+
+interface SiteTransferEmailProps {
+ email: string;
+ sentBy: string;
+ siteDomain: string;
+ organizationName: string;
+ transferLink: string;
+}
+
+export const SiteTransferEmail = ({
+ email,
+ sentBy,
+ siteDomain,
+ organizationName,
+ transferLink,
+}: SiteTransferEmailProps) => {
+ const currentYear = new Date().getFullYear();
+
+ return (
+ <Html>
+ <Head />
+ <Preview>
+ {sentBy} wants to hand {siteDomain} over to you on Rybbit
+ </Preview>
+ <Tailwind
+ config={{
+ presets: [pixelBasedPreset],
+ theme: {
+ extend: {
+ colors: {
+ brand: "#10b981",
+ darkText: "#111827",
+ mutedText: "#6b7280",
+ borderColor: "#e5e7eb",
+ },
+ },
+ },
+ }}
+ >
+ <Body className="bg-white font-sans">
+ <Container className="mx-auto py-8 px-6 max-w-[600px]">
+ <Img
+ src="https://app.rybbit.io/rybbit/horizontal_black.svg"
+ alt="Rybbit"
+ width="120"
+ height="28"
+ className="mb-8"
+ />
+
+ <Text className="text-darkText text-base leading-relaxed mb-4">Hi there,</Text>
+
+ <Text className="text-darkText text-base leading-relaxed mb-4">
+ {sentBy} wants to transfer the analytics for <span className="font-semibold">{siteDomain}</span>
+ {organizationName ? ` from ${organizationName}` : ""} to you on Rybbit Analytics.
+ </Text>
+
+ <Text className="text-darkText text-base leading-relaxed mb-4">
+ Accepting moves the site, with all of its data and settings, into an organization you manage. You'll need
+ a Rybbit account with this email address; you can create one from the link.
+ </Text>
+
+ <Text className="text-darkText text-base leading-relaxed mb-4">
+ <Link href={transferLink} className="text-brand underline">
+ Review the transfer
+ </Link>
+ </Text>
+
+ <Text className="text-mutedText text-sm leading-relaxed">
+ This transfer was sent to {email} and expires in 7 days. If you weren't expecting it, you can ignore this
+ email.
+ </Text>
+
+ <Hr className="border-borderColor my-8" />
+
+ <Text className="text-mutedText text-xs">Β© {currentYear} Rybbit Analytics</Text>
+ </Container>
+ </Body>
+ </Tailwind>
+ </Html>
+ );
+};
diff --git a/server/src/lib/memberLimits.test.ts b/server/src/lib/memberLimits.test.ts
new file mode 100644
index 000000000..448ed1163
--- /dev/null
+++ b/server/src/lib/memberLimits.test.ts
@@ -0,0 +1,48 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const state = vi.hoisted(() => ({ cloud: true, memberLimit: null as number | null, members: 0 }));
+
+vi.mock("./const.js", () => ({
+ get IS_CLOUD() {
+ return state.cloud;
+ },
+}));
+vi.mock("../api/stripe/getSubscription.js", () => ({
+ getSubscriptionInner: vi.fn(async () => ({ memberLimit: state.memberLimit })),
+}));
+vi.mock("../db/postgres/postgres.js", () => ({
+ db: { select: () => ({ from: () => ({ where: async () => [{ value: state.members }] }) }) },
+}));
+
+import { getMemberLimitError } from "./memberLimits.js";
+
+beforeEach(() => {
+ state.cloud = true;
+ state.memberLimit = null;
+ state.members = 0;
+});
+
+describe("getMemberLimitError", () => {
+ it("admits members while the organization is under its plan's limit", async () => {
+ state.memberLimit = 3;
+ state.members = 2;
+ expect(await getMemberLimitError("org_1")).toBeNull();
+ });
+
+ it("refuses once the organization is full", async () => {
+ state.memberLimit = 3;
+ state.members = 3;
+ expect(await getMemberLimitError("org_1")).toBe(
+ "You have reached the limit of 3 members for your plan. Please upgrade to add more."
+ );
+ });
+
+ it("never limits unlimited plans or self-hosted instances", async () => {
+ state.members = 500;
+ expect(await getMemberLimitError("org_1")).toBeNull();
+
+ state.memberLimit = 1;
+ state.cloud = false;
+ expect(await getMemberLimitError("org_1")).toBeNull();
+ });
+});
diff --git a/server/src/lib/memberLimits.ts b/server/src/lib/memberLimits.ts
new file mode 100644
index 000000000..97a371f9a
--- /dev/null
+++ b/server/src/lib/memberLimits.ts
@@ -0,0 +1,56 @@
+import { count, eq } from "drizzle-orm";
+import { db } from "../db/postgres/postgres.js";
+import { member } from "../db/postgres/schema.js";
+import type { SiteTransaction } from "../services/sites/withOrganizationSiteLock.js";
+import { IS_CLOUD } from "./const.js";
+
+/**
+ * The plan's member limit for an organization, or null when it has none
+ * (self-hosted instances, unlimited plans).
+ */
+export async function getPlanMemberLimit(organizationId: string): Promise<number | null> {
+ if (!IS_CLOUD) {
+ return null;
+ }
+ // Lazy import: getSubscription pulls in the Stripe client and, through it,
+ // modules that import auth.ts, which calls this.
+ const { getSubscriptionInner } = await import("../api/stripe/getSubscription.js");
+ const subscription = await getSubscriptionInner(organizationId);
+ return subscription?.memberLimit ?? null;
+}
+
+/**
+ * The plan's member limit, checked before anyone joins an organization
+ * directly (add-member / create-user). Returns the message to show when the
+ * organization is full, null otherwise.
+ */
+export async function getMemberLimitError(organizationId: string): Promise<string | null> {
+ return memberLimitError(organizationId, await getPlanMemberLimit(organizationId));
+}
+
+/**
+ * The same check against an already-resolved limit, counting through `tx` β€”
+ * the transaction holding the organization's row lock
+ * (withOrganizationSiteLock), so two concurrent joins can't both see the last
+ * free seat. Resolve the limit before opening that transaction: the plan
+ * lookup must not wait on a second pooled connection.
+ */
+export async function memberLimitError(
+ organizationId: string,
+ memberLimit: number | null,
+ tx?: SiteTransaction
+): Promise<string | null> {
+ if (memberLimit === null) {
+ return null;
+ }
+
+ const [row] = await (tx ?? db)
+ .select({ value: count() })
+ .from(member)
+ .where(eq(member.organizationId, organizationId));
+ if (Number(row?.value ?? 0) < memberLimit) {
+ return null;
+ }
+
+ return `You have reached the limit of ${memberLimit} member${memberLimit === 1 ? "" : "s"} for your plan. Please upgrade to add more.`;
+}
diff --git a/server/src/lib/permissions.test.ts b/server/src/lib/permissions.test.ts
new file mode 100644
index 000000000..098b59c90
--- /dev/null
+++ b/server/src/lib/permissions.test.ts
@@ -0,0 +1,95 @@
+import {
+ ALL_PERMISSIONS,
+ canAssignRole,
+ higherRole,
+ isAdminRole,
+ isOrgRole,
+ ORG_ROLES,
+ PERMISSIONS,
+ permissionsForRole,
+ roleHasPermission,
+} from "@rybbit/shared";
+import { describe, expect, it } from "vitest";
+import { SCOPE_MATRIX } from "./scopes.js";
+
+// ORG_ROLES is listed high β†’ low.
+const ladder = [...ORG_ROLES].reverse();
+
+describe("role ladder", () => {
+ it("gives every role all the permissions of the roles below it", () => {
+ for (let i = 1; i < ladder.length; i++) {
+ const lower = new Set(permissionsForRole(ladder[i - 1]));
+ const higher = new Set(permissionsForRole(ladder[i]));
+ for (const permission of lower) {
+ expect(higher.has(permission), `${ladder[i]} should hold ${permission}`).toBe(true);
+ }
+ }
+ });
+
+ it("gives the owner every permission and unknown roles none", () => {
+ expect(permissionsForRole("owner")).toEqual(ALL_PERMISSIONS);
+ expect(permissionsForRole("superuser")).toEqual([]);
+ expect(permissionsForRole(null)).toEqual([]);
+ expect(roleHasPermission(undefined, "analytics:read")).toBe(false);
+ });
+
+ it("maps every permission to a scope the credential taxonomy defines", () => {
+ for (const [permission, spec] of Object.entries(PERMISSIONS)) {
+ if (spec.scope === "deny-scoped") continue;
+ const actions = SCOPE_MATRIX[spec.scope.resource] as readonly string[] | undefined;
+ expect(actions?.includes(spec.scope.action), permission).toBe(true);
+ }
+ });
+
+ it("separates reading, report building, site configuration and administration", () => {
+ expect(roleHasPermission("viewer", "analytics:read")).toBe(true);
+ expect(roleHasPermission("viewer", "goals:write")).toBe(false);
+ expect(roleHasPermission("member", "goals:write")).toBe(true);
+ expect(roleHasPermission("member", "sites:configure")).toBe(false);
+ expect(roleHasPermission("editor", "sites:configure")).toBe(true);
+ expect(roleHasPermission("editor", "flags:write")).toBe(true);
+ expect(roleHasPermission("editor", "sites:create")).toBe(false);
+ expect(roleHasPermission("editor", "members:manage")).toBe(false);
+ });
+
+ it("keeps billing with owners and organization administration with admins", () => {
+ expect(roleHasPermission("admin", "billing:manage")).toBe(false);
+ expect(roleHasPermission("owner", "billing:manage")).toBe(true);
+ expect(roleHasPermission("member", "members:manage")).toBe(false);
+ expect(roleHasPermission("admin", "members:manage")).toBe(true);
+ });
+});
+
+describe("role helpers", () => {
+ it("recognises exactly the organization roles", () => {
+ for (const role of ORG_ROLES) expect(isOrgRole(role)).toBe(true);
+ expect(isOrgRole("superuser")).toBe(false);
+ expect(isOrgRole("toString")).toBe(false);
+ });
+
+ it("classifies admins and owners as administrators", () => {
+ expect(isAdminRole("owner")).toBe(true);
+ expect(isAdminRole("admin")).toBe(true);
+ expect(isAdminRole("editor")).toBe(false);
+ expect(isAdminRole("member")).toBe(false);
+ expect(isAdminRole(null)).toBe(false);
+ });
+
+ it("picks the higher of two roles, ignoring unknown ones", () => {
+ expect(higherRole("member", "admin")).toBe("admin");
+ expect(higherRole("owner", "admin")).toBe("owner");
+ expect(higherRole("superuser", "member")).toBe("member");
+ expect(higherRole(null, undefined)).toBeNull();
+ });
+
+ it("never lets anyone grant a role above their own", () => {
+ expect(canAssignRole("owner", "owner")).toBe(true);
+ expect(canAssignRole("admin", "owner")).toBe(false);
+ expect(canAssignRole("admin", "admin")).toBe(true);
+ expect(canAssignRole("admin", "member")).toBe(true);
+ expect(canAssignRole("admin", "viewer")).toBe(true);
+ expect(canAssignRole("editor", "viewer")).toBe(false);
+ expect(canAssignRole("member", "member")).toBe(false);
+ expect(canAssignRole("owner", "superuser")).toBe(false);
+ });
+});
diff --git a/server/src/lib/privateLinkAccess.test.ts b/server/src/lib/privateLinkAccess.test.ts
index e782dbfec..956e408cc 100644
--- a/server/src/lib/privateLinkAccess.test.ts
+++ b/server/src/lib/privateLinkAccess.test.ts
@@ -5,7 +5,7 @@ vi.mock("./siteConfig.js", () => ({ siteConfig: mocks }));
vi.mock("./auth.js", () => ({ auth: { api: { getSession: vi.fn(async () => null) } } }));
vi.mock("./apiRateLimitPolicy.js", () => ({ consumeRateLimitForIdentity: vi.fn() }));
vi.mock("../db/postgres/postgres.js", () => ({ db: {} }));
-import { getUserHasAccessToSitePublic } from "./auth-utils.js";
+import { getSiteIsPubliclyReadable } from "./auth-utils.js";
beforeEach(() => vi.resetAllMocks());
const request = () => ({ headers: { "x-private-key": "aaaaaaaaaaaa" } }) as any;
@@ -13,17 +13,17 @@ describe("private-link revocation across workers", () => {
it("rejects a revoked key even if this worker still caches it", async () => {
mocks.getConfig.mockResolvedValue({ siteId: 7, privateLinkKey: "aaaaaaaaaaaa", public: false });
mocks.reload.mockResolvedValue({ siteId: 7, privateLinkKey: null, public: false });
- expect(await getUserHasAccessToSitePublic(request(), 7)).toBe(false);
+ expect(await getSiteIsPubliclyReadable(request(), 7)).toBe(false);
});
it("accepts a key that is still present in Postgres", async () => {
const config = { siteId: 7, privateLinkKey: "aaaaaaaaaaaa", public: false };
mocks.getConfig.mockResolvedValue(config);
mocks.reload.mockResolvedValue(config);
- expect(await getUserHasAccessToSitePublic(request(), 7)).toBe(true);
+ expect(await getSiteIsPubliclyReadable(request(), 7)).toBe(true);
});
it("rejects a deleted site while its key is cached", async () => {
mocks.getConfig.mockResolvedValue({ siteId: 7, privateLinkKey: "aaaaaaaaaaaa", public: false });
mocks.reload.mockResolvedValue(undefined);
- expect(await getUserHasAccessToSitePublic(request(), 7)).toBe(false);
+ expect(await getSiteIsPubliclyReadable(request(), 7)).toBe(false);
});
});
diff --git a/server/src/mcp/index.ts b/server/src/mcp/index.ts
index 0c662ff68..5e5e64697 100644
--- a/server/src/mcp/index.ts
+++ b/server/src/mcp/index.ts
@@ -1,11 +1,7 @@
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
-import {
- extractBearerToken,
- registerBearerHandoff,
- releaseBearerHandoff,
-} from "../lib/bearerAuth.js";
+import { extractBearerToken, registerBearerHandoff, releaseBearerHandoff } from "../lib/bearerAuth.js";
import { RybbitApiClient } from "./apiClient.js";
import { authenticateMcpRequest, McpAuthenticationError, type McpAuthenticator } from "./auth.js";
import { registerTools, type ToolRegistrationConfig } from "./tools/index.js";
@@ -14,7 +10,7 @@ import { getResourceMetadataUrl } from "./wellKnown.js";
const INSTRUCTIONS = `Rybbit web analytics: read tools for traffic and behavior data, plus write tools to manage sites, goals, funnels, organization members, teams, and user profiles.
Start with list_sites to resolve the numeric site_id and organization_id used by other tools; its role field shows the API key's role per organization.
Omit time inputs to query all time, or pass start_date/end_date or past_minutes.
-Site and organization management tools (create_site, update_site_config, delete_site, delete_user, member and team tools) require the key's user to be an org admin or owner; other write tools require site access.
+Roles, lowest first: viewer (read only), member (goals, funnels, dashboards, own segments), editor (site configuration: update_site_config, delete_user), admin (create_site, delete_site, member and team tools), owner. A tool fails with "Insufficient role" when the key's user holds too low a role on the site or organization.
The tool list reflects the credential's granted scopes: a missing tool means the API key or OAuth grant lacks the matching scope (list_sites is always available).
delete_* tools permanently destroy data and cannot be undone β€” confirm with the user before calling them.
Prefer the aggregated tools over get_sessions/get_events/run_query; read get_query_schema before writing SQL for run_query.
@@ -50,87 +46,92 @@ function buildMcpServer(
export async function mcpRoutes(fastify: FastifyInstance, options: McpRouteOptions = {}) {
const authenticate = options.authenticate ?? authenticateMcpRequest;
- fastify.post("/mcp", { bodyLimit: 1024 * 1024 }, async (request: FastifyRequest, reply: FastifyReply) => {
- // Keep auth failures and per-user analytics responses out of shared caches.
- // Set on the raw response because the transport writes directly to it.
- reply.raw.setHeader("Cache-Control", "no-store");
+ // The MCP gate authenticates the bearer credential itself; tool calls then go
+ // through the REST routes in-process and inherit their permission checks.
+ const selfAuthenticated = { config: { access: "public" as const } };
- let authContext;
- try {
- authContext = await authenticate(request);
- } catch (error) {
- if (error instanceof McpAuthenticationError) {
- if (error.statusCode === 401) {
- // RFC 9728: point OAuth-capable clients at the protected-resource
- // metadata so they can discover the authorization server.
- const resourceMetadataUrl = getResourceMetadataUrl();
- reply.header(
- "WWW-Authenticate",
- resourceMetadataUrl
- ? `Bearer realm="rybbit-mcp", resource_metadata="${resourceMetadataUrl}"`
- : 'Bearer realm="rybbit-mcp"'
- );
- reply.header("Access-Control-Expose-Headers", "WWW-Authenticate");
- } else {
- reply.header(
- "Retry-After",
- String(error.retryAfterSeconds ?? (error.statusCode === 429 ? 60 : 30))
- );
+ fastify.post(
+ "/mcp",
+ { bodyLimit: 1024 * 1024, ...selfAuthenticated },
+ async (request: FastifyRequest, reply: FastifyReply) => {
+ // Keep auth failures and per-user analytics responses out of shared caches.
+ // Set on the raw response because the transport writes directly to it.
+ reply.raw.setHeader("Cache-Control", "no-store");
+
+ let authContext;
+ try {
+ authContext = await authenticate(request);
+ } catch (error) {
+ if (error instanceof McpAuthenticationError) {
+ if (error.statusCode === 401) {
+ // RFC 9728: point OAuth-capable clients at the protected-resource
+ // metadata so they can discover the authorization server.
+ const resourceMetadataUrl = getResourceMetadataUrl();
+ reply.header(
+ "WWW-Authenticate",
+ resourceMetadataUrl
+ ? `Bearer realm="rybbit-mcp", resource_metadata="${resourceMetadataUrl}"`
+ : 'Bearer realm="rybbit-mcp"'
+ );
+ reply.header("Access-Control-Expose-Headers", "WWW-Authenticate");
+ } else {
+ reply.header("Retry-After", String(error.retryAfterSeconds ?? (error.statusCode === 429 ? 60 : 30)));
+ }
+ return reply.status(error.statusCode).send({
+ jsonrpc: "2.0",
+ error: { code: -32001, message: error.message },
+ id: null,
+ });
}
- return reply.status(error.statusCode).send({
+
+ request.log.error({ err: error }, "Failed to authenticate MCP request");
+ return reply.status(500).send({
jsonrpc: "2.0",
- error: { code: -32001, message: error.message },
+ error: { code: -32603, message: "MCP authentication failed" },
id: null,
});
}
- request.log.error({ err: error }, "Failed to authenticate MCP request");
- return reply.status(500).send({
- jsonrpc: "2.0",
- error: { code: -32603, message: "MCP authentication failed" },
- id: null,
- });
- }
-
- // Hand the verified credential to the in-process proxy so each tool call's
- // REST guard reuses it instead of verifying (and rate-limiting) the key a
- // second time. Released when the request ends.
- const authorization = request.headers.authorization as string;
- const handoffToken = extractBearerToken(authorization);
- const handoffNonce = handoffToken ? registerBearerHandoff(handoffToken, authContext.identity) : undefined;
+ // Hand the verified credential to the in-process proxy so each tool call's
+ // REST guard reuses it instead of verifying (and rate-limiting) the key a
+ // second time. Released when the request ends.
+ const authorization = request.headers.authorization as string;
+ const handoffToken = extractBearerToken(authorization);
+ const handoffNonce = handoffToken ? registerBearerHandoff(handoffToken, authContext.identity) : undefined;
- const server = buildMcpServer(fastify, authorization, handoffNonce, {
- log: message => request.log.error(message),
- scopes: authContext.scopes,
- });
- const transport = new StreamableHTTPServerTransport({
- sessionIdGenerator: undefined,
- enableJsonResponse: true,
- });
+ const server = buildMcpServer(fastify, authorization, handoffNonce, {
+ log: message => request.log.error(message),
+ scopes: authContext.scopes,
+ });
+ const transport = new StreamableHTTPServerTransport({
+ sessionIdGenerator: undefined,
+ enableJsonResponse: true,
+ });
- // The transport writes directly to the raw response; keep Fastify out of it.
- reply.hijack();
- reply.raw.on("close", () => {
- releaseBearerHandoff(handoffNonce);
- transport.close();
- server.close();
- });
+ // The transport writes directly to the raw response; keep Fastify out of it.
+ reply.hijack();
+ reply.raw.on("close", () => {
+ releaseBearerHandoff(handoffNonce);
+ transport.close();
+ server.close();
+ });
- try {
- await server.connect(transport);
- await transport.handleRequest(request.raw, reply.raw, request.body);
- } catch (error) {
- request.log.error(error, "MCP request failed");
- if (!reply.raw.headersSent) {
- reply.raw.writeHead(500, { "content-type": "application/json" });
- reply.raw.end(
- JSON.stringify({ jsonrpc: "2.0", error: { code: -32603, message: "Internal server error" }, id: null })
- );
- } else {
- reply.raw.end();
+ try {
+ await server.connect(transport);
+ await transport.handleRequest(request.raw, reply.raw, request.body);
+ } catch (error) {
+ request.log.error(error, "MCP request failed");
+ if (!reply.raw.headersSent) {
+ reply.raw.writeHead(500, { "content-type": "application/json" });
+ reply.raw.end(
+ JSON.stringify({ jsonrpc: "2.0", error: { code: -32603, message: "Internal server error" }, id: null })
+ );
+ } else {
+ reply.raw.end();
+ }
}
}
- });
+ );
// Stateless server: no SSE notification stream to GET, no session to DELETE.
const methodNotAllowed = async (_request: FastifyRequest, reply: FastifyReply) =>
@@ -142,6 +143,6 @@ export async function mcpRoutes(fastify: FastifyInstance, options: McpRouteOptio
error: { code: -32000, message: "Method not allowed. This MCP server is stateless: send POST requests." },
id: null,
});
- fastify.get("/mcp", methodNotAllowed);
- fastify.delete("/mcp", methodNotAllowed);
+ fastify.get("/mcp", selfAuthenticated, methodNotAllowed);
+ fastify.delete("/mcp", selfAuthenticated, methodNotAllowed);
}
diff --git a/server/src/mcp/inputs.ts b/server/src/mcp/inputs.ts
index 166a29d7a..3d581cb07 100644
--- a/server/src/mcp/inputs.ts
+++ b/server/src/mcp/inputs.ts
@@ -182,9 +182,13 @@ export const fieldsInput = z
export const organizationIdInput = z.string().min(1).describe("Organization ID from list_sites");
+// Kept in sync with ORG_ROLES in @rybbit/shared permissions.ts (inlined like
+// the other enums here).
export const memberRoleInput = z
- .enum(["admin", "member", "owner"])
- .describe("Role in the organization; only an owner key can grant 'owner'");
+ .enum(["owner", "admin", "editor", "member", "viewer"])
+ .describe(
+ "Role in the organization, highest first: owner, admin, editor (configures sites), member (builds reports), viewer (read only). Nobody can grant a role above their own."
+ );
export const propertyFilterInput = z.object({
key: z.string(),
diff --git a/server/src/mcp/mcp.test.ts b/server/src/mcp/mcp.test.ts
index 40ccb5970..de6c39e94 100644
--- a/server/src/mcp/mcp.test.ts
+++ b/server/src/mcp/mcp.test.ts
@@ -200,6 +200,12 @@ describe("mcp endpoint", () => {
return { success: true };
});
+ fastify.put("/organizations/:organizationId/members/:memberId/sites", async request => {
+ captured.url = request.url;
+ captured.body = request.body;
+ return { memberId: "m_1", hasRestrictedSiteAccess: true, siteAccess: [] };
+ });
+
fastify.post("/organizations/:organizationId/members", async request => {
captured.url = request.url;
captured.body = request.body;
@@ -657,6 +663,25 @@ describe("mcp endpoint", () => {
expect(captured.body).toEqual({ anonymous_id: "anon_1", user_id: "app_user_9", traits: { plan: "pro" } });
});
+ it("update_member_site_access leaves the site role alone unless asked", async () => {
+ await callTool(app, "update_member_site_access", {
+ organization_id: "org_1",
+ member_id: "m_1",
+ has_restricted_site_access: true,
+ site_ids: [5],
+ });
+ expect(captured.body).toEqual({ hasRestrictedSiteAccess: true, siteIds: [5] });
+
+ await callTool(app, "update_member_site_access", {
+ organization_id: "org_1",
+ member_id: "m_1",
+ has_restricted_site_access: true,
+ site_ids: [5],
+ site_role: "editor",
+ });
+ expect(captured.body).toEqual({ hasRestrictedSiteAccess: true, siteIds: [5], siteRole: "editor" });
+ });
+
it("analyze_funnel sends steps as the POST body", async () => {
const steps = [
{ type: "page", value: "/pricing" },
@@ -676,7 +701,7 @@ describe("mcp endpoint", () => {
expect(result.content[0].text).toContain("403");
expect(result.content[0].text).toContain("You don't have access to this site");
expect(result.content[0].text).toContain("list_sites");
- expect(result.content[0].text).toContain("admin/owner role");
+ expect(result.content[0].text).toContain("Insufficient role");
});
it("rejects invalid tool arguments before hitting the API", async () => {
diff --git a/server/src/mcp/tools/organizations.ts b/server/src/mcp/tools/organizations.ts
index 9d2dbec0a..b94b19b9f 100644
--- a/server/src/mcp/tools/organizations.ts
+++ b/server/src/mcp/tools/organizations.ts
@@ -51,7 +51,7 @@ export function registerOrganizationTools(server: McpServer, api: RybbitApiClien
{
title: "Add organization member",
description:
- "Add an existing Rybbit user to the organization by email. The user must already have a Rybbit account. Requires an org admin/owner key; only an owner key can grant the owner role.",
+ "Add an existing Rybbit user to the organization by email. The user must already have a Rybbit account. Requires an org admin/owner key; nobody can grant a role above their own (only an owner key can grant owner).",
inputSchema: {
organization_id: organizationIdInput,
email: z.string().email().describe("Email of an existing Rybbit user"),
@@ -71,22 +71,34 @@ export function registerOrganizationTools(server: McpServer, api: RybbitApiClien
{
title: "Update member site access",
description:
- "Restrict a member to specific sites, or lift the restriction. Applies to member-role users only (admins/owners always see all sites). Requires an org admin/owner key.",
+ "Restrict a member to specific sites, or lift the restriction. Applies to editor, member, and viewer roles (admins/owners always see all sites). Requires an org admin/owner key.",
inputSchema: {
organization_id: organizationIdInput,
member_id: z.string().min(1).describe("Membership record id from list_members (not the user id)"),
has_restricted_site_access: z.boolean().describe("true = member sees only site_ids; false = member sees all org sites"),
site_ids: z.array(z.number().int().positive()).describe("Sites the member may access when restricted"),
+ // Inlined like the other enums here (SITE_GRANT_ROLES in @rybbit/shared).
+ site_role: z
+ .enum(["editor", "member", "viewer"])
+ .nullable()
+ .optional()
+ .describe("Raises the member's role on site_ids only (never lowers it). null clears it; omit to keep what the member's grants already carry."),
},
outputSchema: memberSiteAccessOutput,
annotations: idempotentWrite,
},
- guard(async ({ organization_id, member_id, has_restricted_site_access, site_ids }) =>
+ guard(async ({ organization_id, member_id, has_restricted_site_access, site_ids, site_role }) =>
ok(
await api.call(
"PUT",
`/organizations/${encodeURIComponent(organization_id)}/members/${encodeURIComponent(member_id)}/sites`,
- { body: { hasRestrictedSiteAccess: has_restricted_site_access, siteIds: site_ids } }
+ {
+ body: {
+ hasRestrictedSiteAccess: has_restricted_site_access,
+ siteIds: site_ids,
+ ...(site_role !== undefined ? { siteRole: site_role } : {}),
+ },
+ }
)
)
)
diff --git a/server/src/mcp/tools/shared.ts b/server/src/mcp/tools/shared.ts
index 52226e03f..f76de43a9 100644
--- a/server/src/mcp/tools/shared.ts
+++ b/server/src/mcp/tools/shared.ts
@@ -67,7 +67,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 > 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.",
+ 403: "The API key's user does not have access to this site or organization, or holds too low a role for this tool ('Insufficient role' names the role required). 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/server/src/mcp/tools/sites.ts b/server/src/mcp/tools/sites.ts
index 8eb8d2252..69dbaf98a 100644
--- a/server/src/mcp/tools/sites.ts
+++ b/server/src/mcp/tools/sites.ts
@@ -45,7 +45,7 @@ export function registerSiteTools(server: McpServer, api: RybbitApiClient, guard
{
title: "List sites",
description:
- "List the organizations and sites this API key can access. Call this first: it resolves the numeric site_id used by site tools and the organization_id used by organization tools, and its role field shows the key's role per organization (write tools need member access; site/org management needs admin or owner).",
+ "List the organizations and sites this API key can access. Call this first: it resolves the numeric site_id used by site tools and the organization_id used by organization tools, and its role field shows the key's role per organization (report-building tools need member or above, site configuration needs editor, site creation/deletion and member management need admin; site grants and teams can raise the role on individual sites).",
inputSchema: {},
outputSchema: listSitesOutput,
annotations: readOnly,
@@ -127,7 +127,7 @@ export function registerSiteTools(server: McpServer, api: RybbitApiClient, guard
{
title: "Update site configuration",
description:
- "Update a site's settings; only the fields you pass are changed. Requires the API key's user to be an org admin or owner. Use get_site first to see current values.",
+ "Update a site's settings; only the fields you pass are changed. Requires the API key's user to hold the editor role or above on the site. Use get_site first to see current values.",
inputSchema: {
site_id: siteIdInput,
name: z.string().optional(),
diff --git a/server/src/mcp/tools/users.ts b/server/src/mcp/tools/users.ts
index 79a706de1..1cb2c13ad 100644
--- a/server/src/mcp/tools/users.ts
+++ b/server/src/mcp/tools/users.ts
@@ -125,7 +125,7 @@ export function registerUserTools(server: McpServer, api: RybbitApiClient, guard
{
title: "Delete user (GDPR erasure)",
description:
- "Permanently delete one person's analytics data: events, session replays, profile, and device aliases. Irreversible; erasure completes asynchronously. Requires the API key's user to be an org admin or owner. Confirm with the user before calling.",
+ "Permanently delete one person's analytics data: events, session replays, profile, and device aliases. Irreversible; erasure completes asynchronously. Requires the API key's user to hold the editor role or above on the site. Confirm with the user before calling.",
inputSchema: { site_id: siteIdInput, user_id: userIdInput },
outputSchema: successOutput,
annotations: destructiveTool,
diff --git a/server/src/services/weekyReports/weeklyReportService.ts b/server/src/services/weekyReports/weeklyReportService.ts
index 8f8d4a68e..dc0774bd6 100644
--- a/server/src/services/weekyReports/weeklyReportService.ts
+++ b/server/src/services/weekyReports/weeklyReportService.ts
@@ -1,3 +1,4 @@
+import { isAdminRole, isOrgRole } from "@rybbit/shared";
import * as cron from "node-cron";
import { DateTime } from "luxon";
import { eq } from "drizzle-orm";
@@ -204,9 +205,15 @@ class WeeklyReportService {
continue;
}
+ // A membership whose role isn't one Rybbit knows reaches nothing
+ // (the same rule the request-time resolver applies).
+ if (!isOrgRole(memberData.role)) {
+ continue;
+ }
+
// Only report on sites the member can actually access
let allowedSites = report.sites;
- if (memberData.role === "member") {
+ if (!isAdminRole(memberData.role)) {
allowedSites = await filterSitesByMemberAccess(
report.sites,
report.organizationId,
diff --git a/shared/src/index.ts b/shared/src/index.ts
index 399b8ffd0..5e3e000e3 100644
--- a/shared/src/index.ts
+++ b/shared/src/index.ts
@@ -8,3 +8,4 @@ export * from "./time";
export * from "./performance";
export * from "./aiOperators";
export * from "./annotations";
+export * from "./permissions";
diff --git a/shared/src/permissions.ts b/shared/src/permissions.ts
new file mode 100644
index 000000000..869641747
--- /dev/null
+++ b/shared/src/permissions.ts
@@ -0,0 +1,166 @@
+// Roles and permissions β€” the one answer to "what may this role do?".
+//
+// Pure data, like scopes.ts: the server enforces it (route guards, handler
+// checks) and the client reads the permission names the server hands back.
+// Nothing outside this file compares role strings to decide what a user may
+// do; it asks roleHasPermission instead.
+//
+// A role is a rung on a ladder: every role holds all the permissions of the
+// roles below it. Each permission names the lowest role that holds it and the
+// bearer-credential scope it needs, so a request is allowed only when BOTH the
+// caller's role and (for API keys and OAuth tokens) its scopes admit it.
+
+import type { ScopeRequirement } from "./scopes";
+
+// Highest first.
+// - owner: everything, including billing and deleting the organization
+// - admin: members, teams, API keys, creating/deleting/transferring sites
+// - editor: configures sites β€” tracking settings, flags, experiments, imports,
+// Search Console β€” and manages everyone's saved segments/annotations
+// - member: builds reports β€” goals, funnels, dashboards, own segments/annotations
+// - viewer: reads everything the organization lets them see, changes nothing
+export const ORG_ROLES = ["owner", "admin", "editor", "member", "viewer"] as const;
+export type OrgRole = (typeof ORG_ROLES)[number];
+
+const ROLE_RANK: Record<OrgRole, number> = {
+ viewer: 1,
+ member: 2,
+ editor: 3,
+ admin: 4,
+ owner: 5,
+};
+
+export function isOrgRole(value: unknown): value is OrgRole {
+ return typeof value === "string" && Object.prototype.hasOwnProperty.call(ROLE_RANK, value);
+}
+
+/**
+ * Roles a site grant (a member's per-site access, or a team's) can carry.
+ * Admin authority is organization-wide, so grants stop at editor.
+ */
+export const SITE_GRANT_ROLES = ["editor", "member", "viewer"] as const satisfies readonly OrgRole[];
+export type SiteGrantRole = (typeof SITE_GRANT_ROLES)[number];
+
+export function isSiteGrantRole(value: unknown): value is SiteGrantRole {
+ return typeof value === "string" && (SITE_GRANT_ROLES as readonly string[]).includes(value);
+}
+
+/** Admins and owners: every site in the organization, never narrowed by site grants or teams. */
+export function isAdminRole(role: string | null | undefined): boolean {
+ return role === "admin" || role === "owner";
+}
+
+/** The higher of two roles; null when neither is a known role. */
+export function higherRole(a: string | null | undefined, b: string | null | undefined): OrgRole | null {
+ const left = isOrgRole(a) ? a : null;
+ const right = isOrgRole(b) ? b : null;
+ if (!left) return right;
+ if (!right) return left;
+ return ROLE_RANK[left] >= ROLE_RANK[right] ? left : right;
+}
+
+/**
+ * "deny-scoped": the permission has no scope taxonomy resource (account and
+ * billing surfaces), so scoped and organization-owned credentials never get it.
+ */
+export type PermissionScope = ScopeRequirement | "deny-scoped";
+
+export interface PermissionSpec {
+ /** The lowest role that holds this permission. */
+ minRole: OrgRole;
+ /** What a bearer credential must additionally be granted. */
+ scope: PermissionScope;
+}
+
+const read = (resource: ScopeRequirement["resource"]): ScopeRequirement => ({ resource, action: "read" });
+const write = (resource: ScopeRequirement["resource"]): ScopeRequirement => ({ resource, action: "write" });
+
+export const PERMISSIONS = {
+ // Reading a site's analytics and the organization it belongs to.
+ "analytics:read": { minRole: "viewer", scope: read("analytics") },
+ "sessions:read": { minRole: "viewer", scope: read("sessions") },
+ "events:read": { minRole: "viewer", scope: read("events") },
+ "users:read": { minRole: "viewer", scope: read("users") },
+ "funnels:read": { minRole: "viewer", scope: read("funnels") },
+ "goals:read": { minRole: "viewer", scope: read("goals") },
+ "annotations:read": { minRole: "viewer", scope: read("annotations") },
+ "segments:read": { minRole: "viewer", scope: read("segments") },
+ "dashboards:read": { minRole: "viewer", scope: read("dashboards") },
+ "flags:read": { minRole: "viewer", scope: read("flags") },
+ "experiments:read": { minRole: "viewer", scope: read("experiments") },
+ "replay:read": { minRole: "viewer", scope: read("replay") },
+ "gsc:read": { minRole: "viewer", scope: read("gsc") },
+ "sites:read": { minRole: "viewer", scope: read("sites") },
+ "sql:read": { minRole: "viewer", scope: read("sql") },
+ "org:read": { minRole: "viewer", scope: read("org") },
+
+ // Building reports: shared analysis objects, and a member's own segments and
+ // annotations (rows another user created need the :manage permission).
+ "users:write": { minRole: "member", scope: write("users") },
+ "funnels:write": { minRole: "member", scope: write("funnels") },
+ "goals:write": { minRole: "member", scope: write("goals") },
+ "dashboards:write": { minRole: "member", scope: write("dashboards") },
+ "annotations:write": { minRole: "member", scope: write("annotations") },
+ "segments:write": { minRole: "member", scope: write("segments") },
+
+ // Configuring a site, and managing saved segments and annotations other people
+ // created (org-wide ones are checked against the organization role).
+ "annotations:manage": { minRole: "editor", scope: write("annotations") },
+ "segments:manage": { minRole: "editor", scope: write("segments") },
+ "users:delete": { minRole: "editor", scope: write("users") },
+ "replay:delete": { minRole: "editor", scope: write("replay") },
+ "flags:write": { minRole: "editor", scope: write("flags") },
+ "experiments:write": { minRole: "editor", scope: write("experiments") },
+ "gsc:write": { minRole: "editor", scope: write("gsc") },
+ "sites:configure": { minRole: "editor", scope: write("sites") },
+ "imports:read": { minRole: "editor", scope: read("sites") },
+ "imports:write": { minRole: "editor", scope: write("sites") },
+
+ // Administering the organization.
+ "sites:create": { minRole: "admin", scope: write("sites") },
+ "sites:delete": { minRole: "admin", scope: write("sites") },
+ "sites:transfer": { minRole: "admin", scope: write("sites") },
+ "members:manage": { minRole: "admin", scope: write("org") },
+ "teams:manage": { minRole: "admin", scope: write("org") },
+ "apikeys:manage": { minRole: "admin", scope: "deny-scoped" },
+ // Enforced by better-auth's organization access control (orgRoles in the
+ // server's auth.ts); listed here so the client can ask for it by name.
+ "org:rename": { minRole: "admin", scope: "deny-scoped" },
+
+ // Owning the organization.
+ "billing:manage": { minRole: "owner", scope: "deny-scoped" },
+ "org:delete": { minRole: "owner", scope: "deny-scoped" },
+} as const satisfies Record<string, PermissionSpec>;
+
+export type Permission = keyof typeof PERMISSIONS;
+
+export const ALL_PERMISSIONS = Object.keys(PERMISSIONS) as Permission[];
+
+export function roleHasPermission(role: string | null | undefined, permission: Permission): boolean {
+ if (!isOrgRole(role)) {
+ return false;
+ }
+ return ROLE_RANK[role] >= ROLE_RANK[PERMISSIONS[permission].minRole];
+}
+
+/** Every permission the role holds, in declaration order. */
+export function permissionsForRole(role: string | null | undefined): Permission[] {
+ return ALL_PERMISSIONS.filter(permission => roleHasPermission(role, permission));
+}
+
+/**
+ * Whether someone holding `actorRole` may give another member `targetRole`:
+ * they must manage members, and never grant a role above their own (only an
+ * owner makes owners).
+ */
+export function canAssignRole(actorRole: string | null | undefined, targetRole: string): boolean {
+ if (!isOrgRole(actorRole) || !isOrgRole(targetRole)) {
+ return false;
+ }
+ return roleHasPermission(actorRole, "members:manage") && ROLE_RANK[actorRole] >= ROLE_RANK[targetRole];
+}
+
+/** The roles someone holding `actorRole` may give to others, highest first. */
+export function assignableRoles(actorRole: string | null | undefined): OrgRole[] {
+ return ORG_ROLES.filter(role => canAssignRole(actorRole, role));
+}