πΈ Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
refactor(access): collapse org and site access checks into one module (#1117)
Goldflag480da7e5b437
diff --git a/server/src/api/memberAccess/updateMemberSiteAccess.ts b/server/src/api/memberAccess/updateMemberSiteAccess.tsindex 2bd3231b1..523822d83 100644--- a/server/src/api/memberAccess/updateMemberSiteAccess.ts+++ b/server/src/api/memberAccess/updateMemberSiteAccess.ts@@ -1,8 +1,9 @@-import { and, eq, inArray } from "drizzle-orm";+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 { invalidateSitesAccessCache } from "../../lib/auth-utils.js";interface UpdateMemberSiteAccessParams {@@ -54,12 +55,7 @@ export async function updateMemberSiteAccess(// Validate that all siteIds belong to this organizationif (siteIds && siteIds.length > 0) {- const validSites = await db- .select({ siteId: sites.siteId })- .from(sites)- .where(and(eq(sites.organizationId, organizationId), inArray(sites.siteId, siteIds)));-- const validSiteIds = new Set(validSites.map(s => s.siteId));+ const validSiteIds = new Set(await siteIdsInOrganization(siteIds, organizationId));const invalidSiteIds = siteIds.filter(id => !validSiteIds.has(id));if (invalidSiteIds.length > 0) {diff --git a/server/src/api/sites/getSitesFromOrg.ts b/server/src/api/sites/getSitesFromOrg.tsindex 555a377a7..b10d469cb 100644--- a/server/src/api/sites/getSitesFromOrg.ts+++ b/server/src/api/sites/getSitesFromOrg.ts@@ -1,11 +1,11 @@-import { and, eq } from "drizzle-orm";+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, member, organization, team, teamSiteAccess } from "../../db/postgres/schema.js";+import { sites, 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 } from "../../lib/siteAccess.js";+import { filterSitesByMemberAccess, getOrgMembership } from "../../lib/access.js";import { processResults } from "../analytics/utils/utils.js";import { getSubscriptionInner } from "../stripe/getSubscription.js";import { buildSiteSessionCountsQuery } from "./siteSessionCountsQuery.js";@@ -25,21 +25,14 @@ export async function getSitesFromOrg(const userId = req.user?.id ?? (await getUserIdFromRequest(req));// Run all database queries concurrently- const [memberCheck, allSitesData, orgInfo] = await Promise.all([- userId- ? db- .select()- .from(member)- .where(and(eq(member.organizationId, organizationId), eq(member.userId, userId)))- .limit(1)- : Promise.resolve([]),+ const [memberRecord, allSitesData, orgInfo] = await Promise.all([+ getOrgMembership(userId, organizationId),db.select().from(sites).where(eq(sites.organizationId, organizationId)),db.select().from(organization).where(eq(organization.id, organizationId)).limit(1),]);// Filter sites based on member's access restrictions and teamslet sitesData = allSitesData;- const memberRecord = memberCheck[0];if (memberRecord?.role === "member" && userId) {sitesData = await filterSitesByMemberAccess(diff --git a/server/src/api/sites/moveSite.test.ts b/server/src/api/sites/moveSite.test.tsindex ce6161114..31fe7e9cc 100644--- a/server/src/api/sites/moveSite.test.ts+++ b/server/src/api/sites/moveSite.test.ts@@ -13,12 +13,20 @@ const mocks = vi.hoisted(() => ({applySiteMove: vi.fn(async () => {}),}));+// The membership check now goes through the shared Site Access module.+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),+ };+});+vi.mock("../../db/postgres/postgres.js", () => ({db: {query: {sites: { findFirst: vi.fn(async () => state.site) },organization: { findFirst: vi.fn(async () => state.targetOrg) },- member: { findFirst: vi.fn(async () => state.targetMembership) },},// Only used to count the target organization's existing sites.select: vi.fn(() => ({diff --git a/server/src/api/sites/moveSite.ts b/server/src/api/sites/moveSite.tsindex e225279af..c0252e79b 100644--- a/server/src/api/sites/moveSite.ts+++ b/server/src/api/sites/moveSite.ts@@ -1,8 +1,9 @@-import { and, eq } from "drizzle-orm";+import { eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { z } from "zod";import { db } from "../../db/postgres/postgres.js";-import { member, organization, sites } from "../../db/postgres/schema.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 { applySiteMove } from "./applySiteMove.js";@@ -52,13 +53,11 @@ export async function moveSite(// Caller must be an admin/owner of the target organization. This runs BEFORE the// org-existence check so a caller without target-org access gets the same 403// whether or not the org exists β no org-ID existence oracle.- const targetMembership = await db.query.member.findFirst({- where: and(eq(member.userId, userId), eq(member.organizationId, targetOrganizationId)),- });+ const targetMembership = await getOrgMembership(userId, targetOrganizationId);if (!targetMembership) {return reply.status(403).send({ error: "You are not a member of the target organization" });}- if (targetMembership.role !== "admin" && targetMembership.role !== "owner") {+ if (!isOrgAdmin(targetMembership)) {return reply.status(403).send({ error: "You must be an admin or owner of the target organization" });}diff --git a/server/src/api/stripe/createCheckoutSession.test.ts b/server/src/api/stripe/createCheckoutSession.test.tsindex 7994aa005..94d00caf1 100644--- a/server/src/api/stripe/createCheckoutSession.test.ts+++ b/server/src/api/stripe/createCheckoutSession.test.ts@@ -29,7 +29,7 @@ import { createCheckoutSession } from "./createCheckoutSession.js";const DDL = `CREATE TABLE "organization" ("id" text PRIMARY KEY, "name" text NOT NULL, "slug" text, "createdAt" timestamp DEFAULT now(), "stripeCustomerId" text);CREATE TABLE "user" ("id" text PRIMARY KEY, "name" text, "email" text, "createdAt" timestamp DEFAULT now());-CREATE TABLE "member" ("id" text PRIMARY KEY, "organizationId" text NOT NULL, "userId" text NOT NULL, "role" text NOT NULL, "createdAt" timestamp DEFAULT now());+CREATE TABLE "member" ("id" text PRIMARY KEY, "organizationId" text NOT NULL, "userId" text NOT NULL, "role" text NOT NULL, "createdAt" timestamp DEFAULT now(), "has_restricted_site_access" boolean NOT NULL DEFAULT false);`;function replyStub() {diff --git a/server/src/api/stripe/createCheckoutSession.ts b/server/src/api/stripe/createCheckoutSession.tsindex 16028eb86..1b065cdfb 100644--- a/server/src/api/stripe/createCheckoutSession.ts+++ b/server/src/api/stripe/createCheckoutSession.ts@@ -1,8 +1,9 @@-import { eq, and } from "drizzle-orm";+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, member } from "../../db/postgres/schema.js";+import { organization, user as userSchema } from "../../db/postgres/schema.js";+import { getOrgMembership, isOrgOwner } from "../../lib/access.js";import { stripe } from "../../lib/stripe.js";interface CheckoutRequestBody {@@ -31,15 +32,9 @@ export async function createCheckoutSession(try {// 1. Verify user has permission to manage billing for this organization- const memberResult = await db- .select({- role: member.role,- })- .from(member)- .where(and(eq(member.userId, userId), eq(member.organizationId, organizationId)))- .limit(1);+ const membership = await getOrgMembership(userId, organizationId);- if (!memberResult.length || memberResult[0].role !== "owner") {+ if (!isOrgOwner(membership)) {return reply.status(403).send({error: "Only organization owners can manage billing",});diff --git a/server/src/api/stripe/createPortalSession.test.ts b/server/src/api/stripe/createPortalSession.test.tsindex 2ca6fa8a0..982ed3594 100644--- a/server/src/api/stripe/createPortalSession.test.ts+++ b/server/src/api/stripe/createPortalSession.test.ts@@ -28,7 +28,7 @@ import { createPortalSession } from "./createPortalSession.js";const DDL = `CREATE TABLE "organization" ("id" text PRIMARY KEY, "name" text NOT NULL, "slug" text, "createdAt" timestamp DEFAULT now(), "stripeCustomerId" text);-CREATE TABLE "member" ("id" text PRIMARY KEY, "organizationId" text NOT NULL, "userId" text NOT NULL, "role" text NOT NULL, "createdAt" timestamp DEFAULT now());+CREATE TABLE "member" ("id" text PRIMARY KEY, "organizationId" text NOT NULL, "userId" text NOT NULL, "role" text NOT NULL, "createdAt" timestamp DEFAULT now(), "has_restricted_site_access" boolean NOT NULL DEFAULT false);`;function replyStub() {diff --git a/server/src/api/stripe/createPortalSession.ts b/server/src/api/stripe/createPortalSession.tsindex e6da8cbd5..256aaba0e 100644--- a/server/src/api/stripe/createPortalSession.ts+++ b/server/src/api/stripe/createPortalSession.ts@@ -1,8 +1,9 @@import { FastifyReply, FastifyRequest } from "fastify";import { stripe } from "../../lib/stripe.js";import { db } from "../../db/postgres/postgres.js";-import { organization, member } from "../../db/postgres/schema.js";-import { eq, and } from "drizzle-orm";+import { organization } from "../../db/postgres/schema.js";+import { eq } from "drizzle-orm";+import { getOrgMembership, isOrgOwner } from "../../lib/access.js";import Stripe from "stripe";interface PortalRequestBody {@@ -27,15 +28,9 @@ export async function createPortalSession(request: FastifyRequest<{ Body: Portaltry {// 1. Verify user has permission to manage billing for this organization- const memberResult = await db- .select({- role: member.role,- })- .from(member)- .where(and(eq(member.userId, userId), eq(member.organizationId, organizationId)))- .limit(1);+ const membership = await getOrgMembership(userId, organizationId);- if (!memberResult.length || memberResult[0].role !== "owner") {+ if (!isOrgOwner(membership)) {return reply.status(403).send({error: "Only organization owners can manage billing",});diff --git a/server/src/api/stripe/getInvoices.test.ts b/server/src/api/stripe/getInvoices.test.tsindex 7bdcbcc6e..da198e931 100644--- a/server/src/api/stripe/getInvoices.test.ts+++ b/server/src/api/stripe/getInvoices.test.ts@@ -26,7 +26,7 @@ import { getInvoices } from "./getInvoices.js";const DDL = `CREATE TABLE "organization" ("id" text PRIMARY KEY, "name" text NOT NULL, "slug" text, "createdAt" timestamp DEFAULT now(), "stripeCustomerId" text);-CREATE TABLE "member" ("id" text PRIMARY KEY, "organizationId" text NOT NULL, "userId" text NOT NULL, "role" text NOT NULL, "createdAt" timestamp DEFAULT now());+CREATE TABLE "member" ("id" text PRIMARY KEY, "organizationId" text NOT NULL, "userId" text NOT NULL, "role" text NOT NULL, "createdAt" timestamp DEFAULT now(), "has_restricted_site_access" boolean NOT NULL DEFAULT false);`;function replyStub() {diff --git a/server/src/api/stripe/getInvoices.ts b/server/src/api/stripe/getInvoices.tsindex f517460c7..f947fc6db 100644--- a/server/src/api/stripe/getInvoices.ts+++ b/server/src/api/stripe/getInvoices.ts@@ -1,7 +1,8 @@-import { eq, and } from "drizzle-orm";+import { eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { db } from "../../db/postgres/postgres.js";-import { organization, member } from "../../db/postgres/schema.js";+import { organization } from "../../db/postgres/schema.js";+import { getOrgMembership, isOrgOwner } from "../../lib/access.js";import { stripe } from "../../lib/stripe.js";export async function getInvoices(@@ -29,13 +30,9 @@ export async function getInvoices(try {// Verify user has permission to manage billing for this organization- const memberResult = await db- .select({ role: member.role })- .from(member)- .where(and(eq(member.userId, userId), eq(member.organizationId, organizationId)))- .limit(1);+ const membership = await getOrgMembership(userId, organizationId);- if (!memberResult.length || memberResult[0].role !== "owner") {+ if (!isOrgOwner(membership)) {return reply.status(403).send({ error: "Only organization owners can manage billing" });}diff --git a/server/src/api/stripe/getSubscription.ts b/server/src/api/stripe/getSubscription.tsindex 74624a8f8..2b51fcd99 100644--- a/server/src/api/stripe/getSubscription.ts+++ b/server/src/api/stripe/getSubscription.ts@@ -1,9 +1,10 @@-import { eq, and } from "drizzle-orm";+import { eq } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { DateTime } from "luxon";import Stripe from "stripe";import { db } from "../../db/postgres/postgres.js";-import { organization, member } from "../../db/postgres/schema.js";+import { organization } from "../../db/postgres/schema.js";+import { getOrgMembership } from "../../lib/access.js";import {APPSUMO_MEMBER_LIMITS,APPSUMO_SITE_LIMITS,@@ -228,13 +229,9 @@ export async function getSubscription(}// Verify user is a member of this organization- const memberResult = await db- .select({ role: member.role })- .from(member)- .where(and(eq(member.userId, userId), eq(member.organizationId, organizationId)))- .limit(1);+ const membership = await getOrgMembership(userId, organizationId);- if (!memberResult.length) {+ if (!membership) {return reply.status(403).send({ error: "You do not have access to this organization" });}diff --git a/server/src/api/stripe/previewSubscriptionUpdate.test.ts b/server/src/api/stripe/previewSubscriptionUpdate.test.tsindex e51afc388..ea0fc8f08 100644--- a/server/src/api/stripe/previewSubscriptionUpdate.test.ts+++ b/server/src/api/stripe/previewSubscriptionUpdate.test.ts@@ -30,7 +30,7 @@ import { previewSubscriptionUpdate } from "./previewSubscriptionUpdate.js";const DDL = `CREATE TABLE "organization" ("id" text PRIMARY KEY, "name" text NOT NULL, "slug" text, "createdAt" timestamp DEFAULT now(), "stripeCustomerId" text);-CREATE TABLE "member" ("id" text PRIMARY KEY, "organizationId" text NOT NULL, "userId" text NOT NULL, "role" text NOT NULL, "createdAt" timestamp DEFAULT now());+CREATE TABLE "member" ("id" text PRIMARY KEY, "organizationId" text NOT NULL, "userId" text NOT NULL, "role" text NOT NULL, "createdAt" timestamp DEFAULT now(), "has_restricted_site_access" boolean NOT NULL DEFAULT false);`;function replyStub() {diff --git a/server/src/api/stripe/previewSubscriptionUpdate.ts b/server/src/api/stripe/previewSubscriptionUpdate.tsindex f82fe2107..dfdc87ac3 100644--- a/server/src/api/stripe/previewSubscriptionUpdate.ts+++ b/server/src/api/stripe/previewSubscriptionUpdate.ts@@ -1,8 +1,9 @@import { FastifyReply, FastifyRequest } from "fastify";import { stripe } from "../../lib/stripe.js";import { db } from "../../db/postgres/postgres.js";-import { organization, member } from "../../db/postgres/schema.js";-import { eq, and } from "drizzle-orm";+import { organization } from "../../db/postgres/schema.js";+import { eq } from "drizzle-orm";+import { getOrgMembership, isOrgOwner } from "../../lib/access.js";import Stripe from "stripe";interface PreviewSubscriptionBody {@@ -29,15 +30,9 @@ export async function previewSubscriptionUpdate(try {// 1. Verify user has permission to manage billing for this organization- const memberResult = await db- .select({- role: member.role,- })- .from(member)- .where(and(eq(member.userId, userId), eq(member.organizationId, organizationId)))- .limit(1);+ const membership = await getOrgMembership(userId, organizationId);- if (!memberResult.length || memberResult[0].role !== "owner") {+ if (!isOrgOwner(membership)) {return reply.status(403).send({error: "Only organization owners can manage billing",});diff --git a/server/src/api/stripe/submitCancellationFeedback.test.ts b/server/src/api/stripe/submitCancellationFeedback.test.tsindex 4df084342..dd9175a13 100644--- a/server/src/api/stripe/submitCancellationFeedback.test.ts+++ b/server/src/api/stripe/submitCancellationFeedback.test.ts@@ -15,7 +15,7 @@ import { sql } from "../../db/postgres/postgres.js";import { submitCancellationFeedback } from "./submitCancellationFeedback.js";const DDL = `-CREATE TABLE "member" ("id" text PRIMARY KEY, "organizationId" text NOT NULL, "userId" text NOT NULL, "role" text NOT NULL, "createdAt" timestamp DEFAULT now());+CREATE TABLE "member" ("id" text PRIMARY KEY, "organizationId" text NOT NULL, "userId" text NOT NULL, "role" text NOT NULL, "createdAt" timestamp DEFAULT now(), "has_restricted_site_access" boolean NOT NULL DEFAULT false);CREATE TABLE "cancellation_feedback" ("id" serial PRIMARY KEY,"organization_id" text NOT NULL,diff --git a/server/src/api/stripe/submitCancellationFeedback.ts b/server/src/api/stripe/submitCancellationFeedback.tsindex 2820baee1..3e248270a 100644--- a/server/src/api/stripe/submitCancellationFeedback.ts+++ b/server/src/api/stripe/submitCancellationFeedback.ts@@ -1,7 +1,7 @@import { FastifyReply, FastifyRequest } from "fastify";import { db } from "../../db/postgres/postgres.js";-import { cancellationFeedback, member } from "../../db/postgres/schema.js";-import { eq, and } from "drizzle-orm";+import { cancellationFeedback } from "../../db/postgres/schema.js";+import { getOrgMembership, isOrgOwner } from "../../lib/access.js";interface CancellationFeedbackBody {organizationId: string;@@ -43,13 +43,9 @@ export async function submitCancellationFeedback(try {// Verify user has permission (owner only)- const memberResult = await db- .select({ role: member.role })- .from(member)- .where(and(eq(member.userId, userId), eq(member.organizationId, organizationId)))- .limit(1);+ const membership = await getOrgMembership(userId, organizationId);- if (!memberResult.length || memberResult[0].role !== "owner") {+ if (!isOrgOwner(membership)) {return reply.status(403).send({error: "Only organization owners can submit cancellation feedback",});diff --git a/server/src/api/stripe/updateSubscription.test.ts b/server/src/api/stripe/updateSubscription.test.tsindex dfc5f6410..12331b898 100644--- a/server/src/api/stripe/updateSubscription.test.ts+++ b/server/src/api/stripe/updateSubscription.test.ts@@ -40,7 +40,7 @@ import { updateSubscription } from "./updateSubscription.js";const DDL = `CREATE TABLE "organization" ("id" text PRIMARY KEY, "name" text NOT NULL, "slug" text, "createdAt" timestamp DEFAULT now(), "stripeCustomerId" text);-CREATE TABLE "member" ("id" text PRIMARY KEY, "organizationId" text NOT NULL, "userId" text NOT NULL, "role" text NOT NULL, "createdAt" timestamp DEFAULT now());+CREATE TABLE "member" ("id" text PRIMARY KEY, "organizationId" text NOT NULL, "userId" text NOT NULL, "role" text NOT NULL, "createdAt" timestamp DEFAULT now(), "has_restricted_site_access" boolean NOT NULL DEFAULT false);`;function replyStub() {diff --git a/server/src/api/stripe/updateSubscription.ts b/server/src/api/stripe/updateSubscription.tsindex c6859117c..f2b54846c 100644--- a/server/src/api/stripe/updateSubscription.ts+++ b/server/src/api/stripe/updateSubscription.ts@@ -1,8 +1,9 @@import { FastifyReply, FastifyRequest } from "fastify";import { stripe } from "../../lib/stripe.js";import { db } from "../../db/postgres/postgres.js";-import { organization, member } from "../../db/postgres/schema.js";-import { eq, and } from "drizzle-orm";+import { organization } from "../../db/postgres/schema.js";+import { eq } from "drizzle-orm";+import { getOrgMembership, isOrgOwner } from "../../lib/access.js";import Stripe from "stripe";import { invalidateStripeSubscriptionCache } from "../../lib/subscriptionUtils.js";@@ -30,15 +31,9 @@ export async function updateSubscription(try {// 1. Verify user has permission to manage billing for this organization- const memberResult = await db- .select({- role: member.role,- })- .from(member)- .where(and(eq(member.userId, userId), eq(member.organizationId, organizationId)))- .limit(1);+ const membership = await getOrgMembership(userId, organizationId);- if (!memberResult.length || memberResult[0].role !== "owner") {+ if (!isOrgOwner(membership)) {return reply.status(403).send({error: "Only organization owners can manage billing",});diff --git a/server/src/api/teams/listTeams.ts b/server/src/api/teams/listTeams.tsindex e87680d9d..3f9d78e99 100644--- a/server/src/api/teams/listTeams.ts+++ b/server/src/api/teams/listTeams.ts@@ -1,7 +1,8 @@-import { eq, and, inArray } from "drizzle-orm";+import { eq, inArray } from "drizzle-orm";import { FastifyReply, FastifyRequest } from "fastify";import { db } from "../../db/postgres/postgres.js";-import { team, teamMember, teamSiteAccess, sites, member, user } from "../../db/postgres/schema.js";+import { team, teamMember, teamSiteAccess, sites, user } from "../../db/postgres/schema.js";+import { getOrgMembership, isOrgAdmin } from "../../lib/access.js";import { getUserIdFromRequest } from "../../lib/auth-utils.js";export async function listTeams(@@ -15,16 +16,7 @@ export async function listTeams(const userId = request.user?.id ?? (await getUserIdFromRequest(request));// Get user's membership in this org- const memberRecord = userId- ? await db- .select({ id: member.id, role: member.role })- .from(member)- .where(and(eq(member.organizationId, organizationId), eq(member.userId, userId)))- .limit(1)- : [];-- const isAdminOrOwner =- memberRecord.length > 0 && (memberRecord[0].role === "admin" || memberRecord[0].role === "owner");+ const isAdminOrOwner = isOrgAdmin(await getOrgMembership(userId, organizationId));// Get all teams in the orglet teamsData = await db.select().from(team).where(eq(team.organizationId, organizationId));diff --git a/server/src/api/user/addUserToOrganization.ts b/server/src/api/user/addUserToOrganization.tsindex cb0b8ed1e..059b470ad 100644--- a/server/src/api/user/addUserToOrganization.ts+++ b/server/src/api/user/addUserToOrganization.ts@@ -3,6 +3,7 @@ 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 { getIsUserAdmin } from "../../lib/auth-utils.js";function generateId(len = 32) {@@ -38,10 +39,8 @@ export async function addUserToOrganization(request: FastifyRequest<AddUserToOrgif (!userId) {return reply.status(401).send({ error: "Unauthorized" });}- callerMembership = await db.query.member.findFirst({- where: and(eq(member.userId, userId), eq(member.organizationId, organizationId)),- });- if (!callerMembership || (callerMembership.role !== "admin" && callerMembership.role !== "owner")) {+ callerMembership = await getOrgMembership(userId, organizationId);+ if (!isOrgAdmin(callerMembership)) {return reply.status(401).send({ error: "Unauthorized" });}}diff --git a/server/src/api/user/createUserInOrganization.ts b/server/src/api/user/createUserInOrganization.tsindex ea6d32651..b58f298ad 100644--- a/server/src/api/user/createUserInOrganization.ts+++ b/server/src/api/user/createUserInOrganization.ts@@ -4,6 +4,7 @@ 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 { getIsUserAdmin } from "../../lib/auth-utils.js";function generateId(len = 32) {@@ -50,10 +51,8 @@ export async function createUserInOrganization(request: FastifyRequest<CreateUseif (!userId) {return reply.status(401).send({ error: "Unauthorized" });}- callerMembership = await db.query.member.findFirst({- where: and(eq(member.userId, userId), eq(member.organizationId, organizationId)),- });- if (!callerMembership || (callerMembership.role !== "admin" && callerMembership.role !== "owner")) {+ callerMembership = await getOrgMembership(userId, organizationId);+ if (!isOrgAdmin(callerMembership)) {return reply.status(401).send({ error: "Unauthorized" });}}diff --git a/server/src/api/user/getMyOrganizations.ts b/server/src/api/user/getMyOrganizations.tsindex 94ed4fedb..5a8bf3624 100644--- a/server/src/api/user/getMyOrganizations.ts+++ b/server/src/api/user/getMyOrganizations.ts@@ -1,9 +1,9 @@import { FastifyRequest, FastifyReply } from "fastify";import { db } from "../../db/postgres/postgres.js";-import { and, eq } from "drizzle-orm";+import { eq } from "drizzle-orm";import { member, organization, sites, user } from "../../db/postgres/schema.js";import { getSessionFromReq, getUserIdFromRequest, wasRateLimited } from "../../lib/auth-utils.js";-import { filterSitesByMemberAccess } from "../../lib/siteAccess.js";+import { filterSitesByMemberAccess, getOrgMembership } from "../../lib/access.js";export const getMyOrganizations = async (request: FastifyRequest, reply: FastifyReply) => {try {@@ -49,7 +49,7 @@ export const getMyOrganizations = async (request: FastifyRequest, reply: Fastify// For each organization, get all members with user details and sitesconst organizationsWithMembersAndSites = await Promise.all(userOrganizations.map(async org => {- const [organizationMembers, allOrgSites, callerMember] = await Promise.all([+ const [organizationMembers, allOrgSites, callerMemberRecord] = await Promise.all([db.select({id: member.id,@@ -80,21 +80,12 @@ export const getMyOrganizations = async (request: FastifyRequest, reply: Fastify}).from(sites).where(eq(sites.organizationId, org.id)),- db- .select({- id: member.id,- role: member.role,- hasRestrictedSiteAccess: member.hasRestrictedSiteAccess,- })- .from(member)- .where(and(eq(member.organizationId, org.id), eq(member.userId, userId)))- .limit(1),+ getOrgMembership(userId, org.id),]);// Filter sites based on the caller's per-member access restrictions// and teams. Admins/owners see everything.let organizationSites = allOrgSites;- const callerMemberRecord = callerMember[0];if (callerMemberRecord?.role === "member") {organizationSites = await filterSitesByMemberAccess(diff --git a/server/src/lib/access.ts b/server/src/lib/access.tsnew file mode 100644index 000000000..8ef9b5009--- /dev/null+++ b/server/src/lib/access.ts@@ -0,0 +1,235 @@+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";++/**+ * Access β the one answer to "may this user touch this organization, or this+ * Site?".+ *+ * Two questions used to be answered in a dozen places each:+ *+ * 1. "Is this user in this organization, and as what?" β answered by three+ * different query shapes across ~15 handlers. Now: {@link getOrgMembership}.+ * 2. "Which of an organization's sites may a member-role user see?" β the+ * union of explicit grants, team sites and ungated sites, written out once+ * here and consumed by both entry points (`getSitesUserHasAccessTo` in+ * auth-utils, which spans organizations and credentials, and+ * {@link filterSitesByMemberAccess}, which filters one already-loaded+ * organization). Now: {@link resolveMemberSiteGrants} ++ * {@link memberCanAccessSite}.+ *+ * Admin/owner members bypass the site rule entirely β callers handle that.+ */++export interface OrgMembership {+ id: string;+ userId: string;+ organizationId: string;+ role: string;+ hasRestrictedSiteAccess: boolean;+}++/**+ * The membership row for a user in an organization, or null. This is the only+ * place that asks the question β callers that want a boolean check for null,+ * and callers that want a role read `.role` (or use the predicates below).+ */+export async function getOrgMembership(+ userId: string | undefined | null,+ organizationId: string | undefined | null+): Promise<OrgMembership | null> {+ if (!userId || !organizationId) {+ return null;+ }++ const rows = await db+ .select({+ id: member.id,+ userId: member.userId,+ organizationId: member.organizationId,+ role: member.role,+ hasRestrictedSiteAccess: member.hasRestrictedSiteAccess,+ })+ .from(member)+ .where(and(eq(member.userId, userId), eq(member.organizationId, organizationId)))+ .limit(1);++ return rows[0] ?? null;+}++/** 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";+}++/** Owner of the organization β the only role that may manage billing. */+export function isOrgOwner(membership: OrgMembership | null | undefined): boolean {+ return membership?.role === "owner";+}++/**+ * Which of these site ids currently belong to the organization.+ *+ * Every write into memberSiteAccess must pass its ids through here: a site can+ * move organizations (applySiteMove) or be deleted between the moment a grant+ * is authored and the moment it is stored, and a grant naming a site the+ * organization no longer owns is not a grant anybody authorized. Callers that+ * report the rejects derive them from the complement.+ */+export async function siteIdsInOrganization(siteIds: number[], organizationId: string): Promise<number[]> {+ if (siteIds.length === 0) {+ return [];+ }++ const rows = await db+ .select({ siteId: sites.siteId })+ .from(sites)+ .where(and(eq(sites.organizationId, organizationId), inArray(sites.siteId, siteIds)));++ return rows.map(row => row.siteId);+}++/**+ * 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}.+ */+export interface MemberSiteGrants {+ /** Explicit per-member grants (member_site_access). */+ explicitSiteIds: Set<number>;+ /** Sites gated behind any team in the scoped organizations. */+ teamGatedSiteIds: Set<number>;+ /** Sites reachable through the teams the user belongs to. */+ userTeamSiteIds: Set<number>;+}++const NO_GRANTS: MemberSiteGrants = {+ explicitSiteIds: new Set(),+ teamGatedSiteIds: new Set(),+ userTeamSiteIds: new Set(),+};++/**+ * Load the site grants for one user across the organizations where they hold a+ * member role.+ *+ * `grantedMemberIds` carries the member rows whose explicit grants apply.+ * Explicit grants are only recorded for members with restricted access, so+ * unrestricted members pass an empty list rather than paying for the query.+ */+export async function resolveMemberSiteGrants(options: {+ userId: string;+ organizationIds: string[];+ grantedMemberIds: string[];+}): Promise<MemberSiteGrants> {+ const { userId, organizationIds, grantedMemberIds } = options;++ if (organizationIds.length === 0 && grantedMemberIds.length === 0) {+ return NO_GRANTS;+ }++ const [explicitGrants, teamGated, userTeams] = await Promise.all([+ grantedMemberIds.length > 0+ ? db+ .select({ siteId: memberSiteAccess.siteId })+ .from(memberSiteAccess)+ .where(inArray(memberSiteAccess.memberId, grantedMemberIds))+ : Promise.resolve([]),+ organizationIds.length > 0+ ? db+ .select({ siteId: teamSiteAccess.siteId })+ .from(teamSiteAccess)+ .innerJoin(team, eq(teamSiteAccess.teamId, team.id))+ .where(inArray(team.organizationId, organizationIds))+ : Promise.resolve([]),+ organizationIds.length > 0+ ? db+ .select({ teamId: teamMember.teamId })+ .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 userTeamSites = await db+ .select({ siteId: teamSiteAccess.siteId })+ .from(teamSiteAccess)+ .where(+ inArray(+ teamSiteAccess.teamId,+ userTeams.map(t => t.teamId)+ )+ );+ for (const s of userTeamSites) {+ userTeamSiteIds.add(s.siteId);+ }+ }++ return {+ explicitSiteIds: new Set(explicitGrants.map(g => g.siteId)),+ teamGatedSiteIds: new Set(teamGated.map(s => s.siteId)),+ userTeamSiteIds,+ };+}++/**+ * The site-access rule, in one place:+ *+ * - explicit per-member grants always apply, even to sites gated by a team the+ * member is not on+ * - sites granted through the member's teams are always additive, regardless+ * of whether the member has restricted site access+ * - sites not gated by any team are visible only to unrestricted members+ */+export function memberCanAccessSite(+ grants: MemberSiteGrants,+ siteId: number,+ hasRestrictedSiteAccess: boolean+): boolean {+ if (grants.explicitSiteIds.has(siteId) || grants.userTeamSiteIds.has(siteId)) {+ return true;+ }+ if (hasRestrictedSiteAccess) {+ return false;+ }+ return !grants.teamGatedSiteIds.has(siteId);+}++/**+ * The closed set of sites a *restricted* member can reach β the narrowing+ * counterpart of {@link memberCanAccessSite}. Restricted access is entirely+ * grant-driven, so it can be enumerated instead of tested, which lets callers+ * load those sites by id rather than reading a whole organization and+ * discarding most of it.+ *+ * Keep this in step with the restricted branch of {@link 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]));+}++/**+ * Filters one organization's sites down to what a member-role user can access.+ *+ * The adapter for callers that already hold an organization's sites and the+ * caller's member row (org site lists, weekly reports). Callers must handle+ * admin/owner roles themselves β they bypass filtering.+ */+export async function filterSitesByMemberAccess<T extends { siteId: number }>(+ orgSites: T[],+ organizationId: string,+ userId: string,+ memberId: string,+ hasRestrictedSiteAccess: boolean+): Promise<T[]> {+ const grants = await resolveMemberSiteGrants({+ userId,+ organizationIds: [organizationId],+ grantedMemberIds: hasRestrictedSiteAccess ? [memberId] : [],+ });++ return orgSites.filter(site => memberCanAccessSite(grants, site.siteId, hasRestrictedSiteAccess));+}diff --git a/server/src/lib/auth-middleware.ts b/server/src/lib/auth-middleware.tsindex 6325130ba..4963b3973 100644--- a/server/src/lib/auth-middleware.ts+++ b/server/src/lib/auth-middleware.ts@@ -9,9 +9,9 @@ import {getUserIsInOrg,type BearerAuthResult,} from "./auth-utils.js";+import { getOrgMembership, isOrgAdmin } from "./access.js";import { hasScope, scopeToString, type ScopeRequirement } from "./scopes.js";import { resolveNumericSiteId } from "../utils.js";-import { db } from "../db/postgres/postgres.js";type AuthMiddleware = (request: FastifyRequest, reply: FastifyReply) => Promise<void>;@@ -389,16 +389,13 @@ export function requireOrgAdminFromParams(scope?: RouteScope): AuthMiddleware {}// Check org membership and role- const member = await db.query.member.findFirst({- where: (member, { and, eq }) =>- and(eq(member.userId, session.user.id), eq(member.organizationId, organizationId)),- });+ const membership = await getOrgMembership(session.user.id, organizationId);- if (!member) {+ if (!membership) {return reply.status(403).send({ error: "You are not a member of this organization" });}- if (member.role !== "admin" && member.role !== "owner") {+ if (!isOrgAdmin(membership)) {return reply.status(403).send({ error: "You must be an admin or owner" });}diff --git a/server/src/lib/auth-utils.test.ts b/server/src/lib/auth-utils.test.tsindex 5a9333cb4..bddb74c11 100644--- a/server/src/lib/auth-utils.test.ts+++ b/server/src/lib/auth-utils.test.ts@@ -54,8 +54,17 @@ import {getUserIdFromRequest,invalidateSitesAccessCache,} from "./auth-utils.js";+import {+ filterSitesByMemberAccess,+ getOrgMembership,+ isOrgAdmin,+ isOrgOwner,+ memberCanAccessSite,+ resolveMemberSiteGrants,+ restrictedMemberSiteIds,+ siteIdsInOrganization,+} from "./access.js";import { INTERNAL_BEARER_HANDOFF_HEADER, registerBearerHandoff, releaseBearerHandoff } from "./bearerAuth.js";-import { filterSitesByMemberAccess } from "./siteAccess.js";// Only the tables getSitesUserHasAccessTo touches. Column names must match the// drizzle schema exactly (unnamed columns use their TS property name verbatim).@@ -232,6 +241,36 @@ describe("getSitesUserHasAccessTo β team-based access", () => {});});+describe("getOrgMembership", () => {+ it("returns the membership row with the role and restriction flag", async () => {+ const membership = await getOrgMembership("user_peer", ORG);++ expect(membership).toMatchObject({+ id: "member_peer",+ userId: "user_peer",+ organizationId: ORG,+ role: "member",+ hasRestrictedSiteAccess: false,+ });+ expect(isOrgAdmin(membership)).toBe(false);+ expect(isOrgOwner(membership)).toBe(false);+ });++ it("classifies owners as both admin and owner", async () => {+ const membership = await getOrgMembership("user_owner", ORG);++ expect(isOrgAdmin(membership)).toBe(true);+ expect(isOrgOwner(membership)).toBe(true);+ });++ it("returns null for a non-member, and for a missing user or organization", async () => {+ expect(await getOrgMembership("user_stranger", ORG)).toBeNull();+ expect(await getOrgMembership("user_peer", "org_other")).toBeNull();+ expect(await getOrgMembership(undefined, ORG)).toBeNull();+ expect(await getOrgMembership("user_peer", undefined)).toBeNull();+ });+});+// Shared filter used by getSitesFromOrg, getMyOrganizations, and weekly reportsdescribe("filterSitesByMemberAccess", () => {const orgSites = Array.from({ length: 13 }, (_, i) => ({ siteId: i + 1 }));@@ -261,6 +300,117 @@ describe("filterSitesByMemberAccess", () => {});});+// Every write into memberSiteAccess passes its ids through this β an invitation+// accepted after one of its sites moved organizations must not become a grant.+describe("siteIdsInOrganization", () => {+ it("keeps only the ids the organization currently owns", async () => {+ await db.insert(sites).values({+ id: "hex_moved",+ siteId: 700,+ name: "moved-site",+ domain: "moved.example.com",+ organizationId: "org_elsewhere",+ });++ expect((await siteIdsInOrganization([1, 700, 13], ORG)).sort((a, b) => a - b)).toEqual([1, 13]);+ });++ it("drops ids for sites that no longer exist", async () => {+ expect(await siteIdsInOrganization([1, 9999], ORG)).toEqual([1]);+ });++ it("returns nothing for an empty list without querying", async () => {+ expect(await siteIdsInOrganization([], ORG)).toEqual([]);+ });+});++// restrictedMemberSiteIds lets the resolver load a restricted member's sites by+// id instead of reading a whole organization. It is only safe while it names+// exactly the ids the predicate would admit.+describe("restrictedMemberSiteIds matches the restricted branch of memberCanAccessSite", () => {+ 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"] : [],+ });+ }++ it("enumerates exactly the sites the predicate admits, for a member on a team", async () => {+ await db.insert(memberSiteAccess).values({ memberId: "member_peer", siteId: 12 });+ const grants = await grantsFor(true);++ const enumerated = restrictedMemberSiteIds(grants).sort((a, b) => a - b);+ const admitted = universe.filter(siteId => memberCanAccessSite(grants, siteId, true));++ expect(enumerated).toEqual(admitted);+ expect(enumerated.length).toBeGreaterThan(0);+ });++ it("enumerates nothing when the predicate admits nothing", async () => {+ await db.delete(teamMember);+ const grants = await grantsFor(true);++ expect(restrictedMemberSiteIds(grants)).toEqual([]);+ expect(universe.filter(siteId => memberCanAccessSite(grants, siteId, true))).toEqual([]);+ });+});++// The policy used to be written out twice β once inside getSitesUserHasAccessTo+// and once in filterSitesByMemberAccess β with nothing forcing them to move+// together. They now share one rule; this is the test that keeps them there.+describe("the two Site Access entry points agree", () => {+ const orgSites = Array.from({ length: 13 }, (_, i) => ({ siteId: i + 1 }));++ async function bothAnswersFor(restricted: boolean): Promise<{ resolver: number[]; filter: number[] }> {+ await db.update(member).set({ hasRestrictedSiteAccess: restricted }).where(eq(member.id, "member_peer"));++ const filtered = await filterSitesByMemberAccess(orgSites, ORG, "user_peer", "member_peer", restricted);+ return {+ resolver: await siteIdsFor("user_peer"),+ filter: filtered.map(s => s.siteId).sort((a, b) => a - b),+ };+ }++ it("agree for an unrestricted member on a team", async () => {+ const { resolver, filter } = await bothAnswersFor(false);+ expect(resolver).toEqual(filter);+ });++ it("agree for an unrestricted member on no team", async () => {+ await db.delete(teamMember);+ const { resolver, filter } = await bothAnswersFor(false);+ expect(resolver).toEqual(filter);+ });++ it("agree for a restricted member whose grant is not team-gated", async () => {+ await db.insert(memberSiteAccess).values({ memberId: "member_peer", siteId: 13 });+ const { resolver, filter } = await bothAnswersFor(true);+ expect(resolver).toEqual(filter);+ });++ it("agree for a restricted member granted a site gated by another team", async () => {+ await db.insert(memberSiteAccess).values({ memberId: "member_peer", siteId: 12 });+ const { resolver, filter } = await bothAnswersFor(true);+ expect(resolver).toEqual(filter);+ });++ it("agree for a restricted member with no team and no grants", async () => {+ await db.delete(teamMember);+ const { resolver, filter } = await bothAnswersFor(true);+ expect(resolver).toEqual([]);+ expect(filter).toEqual([]);+ });++ it("agree when no site in the organization is team-gated", async () => {+ await db.delete(teamSiteAccess);+ const { resolver, filter } = await bothAnswersFor(false);+ expect(resolver).toEqual(filter);+ });+});+describe("checkApiKey β scope carrying", () => {const request = (token = "rb_key") => ({ headers: { authorization: `Bearer ${token}` }, query: {} }) as any;diff --git a/server/src/lib/auth-utils.ts b/server/src/lib/auth-utils.tsindex 10a6d9ad8..a55b390aa 100644--- a/server/src/lib/auth-utils.ts+++ b/server/src/lib/auth-utils.ts@@ -2,7 +2,13 @@ import { and, eq, inArray } from "drizzle-orm";import { FastifyRequest } from "fastify";import NodeCache from "node-cache";import { db } from "../db/postgres/postgres.js";-import { member, memberSiteAccess, sites, user, team, teamMember, teamSiteAccess } from "../db/postgres/schema.js";+import { member, sites, user } from "../db/postgres/schema.js";+import {+ getOrgMembership,+ memberCanAccessSite,+ resolveMemberSiteGrants,+ restrictedMemberSiteIds,+} from "./access.js";import type { RateLimitDecision } from "./apiRateLimit.js";import { consumeRateLimitForIdentity } from "./apiRateLimitPolicy.js";import { auth } from "./auth.js";@@ -192,12 +198,12 @@ export async function getSitesUserHasAccessTo(req: FastifyRequest, adminOnly = freturn [];}- // Separate members by access type- // 1. Admin/owner members - full access to their orgs- // 2. Unrestricted members - full access to their orgs- // 3. Restricted members - only access to specific sites via member_site_access+ // 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 ruleconst fullAccessOrgIds: string[] = [];- const restrictedMemberIds: string[] = [];+ const memberRowByOrgId = new Map<string, (typeof memberRecords)[0]>();for (const record of memberRecords) {// If adminOnly is true, skip members with "member" role@@ -205,135 +211,74 @@ export async function getSitesUserHasAccessTo(req: FastifyRequest, adminOnly = fcontinue;}- // Admin/owner roles always have full access- if (record.role === "admin" || record.role === "owner") {- fullAccessOrgIds.push(record.organizationId);- }- // Member role with hasRestrictedSiteAccess = true - only specific sites- else if (record.role === "member" && record.hasRestrictedSiteAccess) {- restrictedMemberIds.push(record.id);- }- // Member role with hasRestrictedSiteAccess = false - full org access- else {+ if (record.role === "member") {+ memberRowByOrgId.set(record.organizationId, record);+ } else {fullAccessOrgIds.push(record.organizationId);}}- // Fetch sites in parallel- const [orgSites, restrictedSites] = await Promise.all([- // Get all sites from orgs with full access- fullAccessOrgIds.length > 0- ? db.select().from(sites).where(inArray(sites.organizationId, fullAccessOrgIds))- : Promise.resolve([]),- // Get specific sites for restricted members- restrictedMemberIds.length > 0- ? (async () => {- const siteAccess = await db- .select({ siteId: memberSiteAccess.siteId })- .from(memberSiteAccess)- .where(inArray(memberSiteAccess.memberId, restrictedMemberIds));- const siteIds = siteAccess.map(s => s.siteId);- if (siteIds.length === 0) return [];- return db.select().from(sites).where(inArray(sites.siteId, siteIds));- })()+ 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,]);- // Combine and dedupe by siteId- const siteMap = new Map<number, (typeof orgSites)[0]>();- for (const site of orgSites) {- siteMap.set(site.siteId, site);- }- for (const site of restrictedSites) {- if (!siteMap.has(site.siteId)) {- siteMap.set(site.siteId, site);- }+ if (!grants) {+ return eagerSites;}- // Apply team-based filtering for non-admin/owner members- // Members who have full org access (not restricted) still need team filtering- const memberOrgIds = memberRecords.filter(r => r.role === "member").map(r => r.organizationId);-- if (memberOrgIds.length > 0) {- // Find all team-gated sites in the member's orgs- const allTeamSites = await db- .select({ siteId: teamSiteAccess.siteId })- .from(teamSiteAccess)- .innerJoin(team, eq(teamSiteAccess.teamId, team.id))- .where(inArray(team.organizationId, memberOrgIds));-- const teamGatedSiteIds = new Set(allTeamSites.map(s => s.siteId));-- if (teamGatedSiteIds.size > 0) {- // Find teams the user belongs to- const userTeams = await db- .select({ teamId: teamMember.teamId })- .from(teamMember)- .where(eq(teamMember.userId, userId));-- const userTeamSiteIds = new Set<number>();- if (userTeams.length > 0) {- const userTeamSites = await db- .select({ siteId: teamSiteAccess.siteId })- .from(teamSiteAccess)- .where(- inArray(- teamSiteAccess.teamId,- userTeams.map(t => t.teamId)- )- );- for (const s of userTeamSites) {- userTeamSiteIds.add(s.siteId);- }- }-- // Team access is additive: a restricted member's siteMap only has- // their explicit grants, so team-granted sites must be added back- const memberOrgIdSet = new Set(memberOrgIds);- const missingTeamSiteIds = Array.from(userTeamSiteIds).filter(id => !siteMap.has(id));- if (missingTeamSiteIds.length > 0) {- const teamSites = await db.select().from(sites).where(inArray(sites.siteId, missingTeamSiteIds));- for (const site of teamSites) {- if (site.organizationId && memberOrgIdSet.has(site.organizationId)) {- siteMap.set(site.siteId, site);- }- }- }-- // For sites from admin/owner orgs, keep all (no team filtering)- // For sites from member orgs, apply team filtering- const adminOrgSiteIds = new Set<number>();- if (fullAccessOrgIds.length > 0) {- // Sites from orgs where user is admin/owner should not be team-filtered- for (const record of memberRecords) {- if (record.role === "admin" || record.role === "owner") {- for (const [siteId, site] of siteMap) {- if (site.organizationId === record.organizationId) {- adminOrgSiteIds.add(siteId);- }- }- }- }- }-- // Explicit per-member grants always win over team gating- const explicitGrantSiteIds = new Set(restrictedSites.map(s => s.siteId));-- // Remove team-gated sites the user can't access (only for member-role orgs)- for (const [siteId] of siteMap) {- if (- teamGatedSiteIds.has(siteId) &&- !userTeamSiteIds.has(siteId) &&- !adminOrgSiteIds.has(siteId) &&- !explicitGrantSiteIds.has(siteId)- ) {- siteMap.delete(siteId);+ 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 Array.from(siteMap.values());+ return accessible;} catch (error) {console.error("Error getting sites user has access to:", error);// Remove from cache on error so it can be retried@@ -545,17 +490,7 @@ export async function getUserHasAdminAccessToSite(req: FastifyRequest, siteId: sreturn sites.some(site => site.siteId === Number(siteId));}-export async function getUserIsInOrg(req: FastifyRequest, organizationId: string) {- const session = await getSessionFromReq(req);-- if (!session?.user.id) {- return false;- }-- // Check if user is a member of this organization- const userMembership = await db.query.member.findFirst({- where: and(eq(member.userId, session.user.id), eq(member.organizationId, organizationId)),- });-- return userMembership;+export async function getUserIsInOrg(req: FastifyRequest, organizationId: string): Promise<boolean> {+ const userId = req.user?.id ?? (await getSessionFromReq(req))?.user.id;+ return (await getOrgMembership(userId, organizationId)) !== null;}diff --git a/server/src/lib/auth.ts b/server/src/lib/auth.tsindex 98169c180..a5bcdb64e 100644--- a/server/src/lib/auth.ts+++ b/server/src/lib/auth.ts@@ -13,6 +13,7 @@ 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 { siteIdsInOrganization } from "./access.js";import { apiKeyLimitForPlan, countApiKeysForReference } from "./apiKeyLimits.js";import { invalidateSitesAccessCache } from "./auth-utils.js";import { ORG_API_KEY_CONFIG_ID } from "./bearerAuth.js";@@ -150,11 +151,7 @@ const pluginList = [});}- const validSites = await db- .select({ siteId: sites.siteId })- .from(sites)- .where(and(eq(sites.organizationId, invite.organizationId), inArray(sites.siteId, uniqueSiteIds)));- const validSiteIds = new Set(validSites.map(site => site.siteId));+ const validSiteIds = new Set(await siteIdsInOrganization(uniqueSiteIds, invite.organizationId));const invalidSiteIds = uniqueSiteIds.filter(siteId => !validSiteIds.has(siteId));if (invalidSiteIds.length > 0) {@@ -538,10 +535,28 @@ export const auth = betterAuth({// org access) on any failure.await db.update(member).set({ hasRestrictedSiteAccess: true }).where(eq(member.id, memberId));- const siteIdArray = (siteIds || []) as number[];- if (siteIdArray.length > 0) {+ // The ids were validated when the invitation was written, but a site+ // can move organizations or be deleted while the invite sits pending+ // (applySiteMove clears live grants for a moved site; it cannot reach+ // into unaccepted invitations). Re-check against the organization as+ // it stands now, so acceptance can only grant sites it still owns.+ const invitedSiteIds = (siteIds || []) as number[];+ const grantableSiteIds = await siteIdsInOrganization(invitedSiteIds, organizationId);++ if (grantableSiteIds.length !== invitedSiteIds.length) {+ authLogger.warn(+ {+ organizationId,+ memberId,+ droppedSiteIds: invitedSiteIds.filter(siteId => !grantableSiteIds.includes(siteId)),+ },+ "Invitation named sites the organization no longer owns; those grants were dropped"+ );+ }++ if (grantableSiteIds.length > 0) {await db.insert(memberSiteAccess).values(- siteIdArray.map(siteId => ({+ grantableSiteIds.map(siteId => ({memberId,siteId,}))diff --git a/server/src/lib/siteAccess.ts b/server/src/lib/siteAccess.tsdeleted file mode 100644index 52ee513de..000000000--- a/server/src/lib/siteAccess.ts+++ /dev/null@@ -1,71 +0,0 @@-import { and, eq, inArray } from "drizzle-orm";-import { db } from "../db/postgres/postgres.js";-import { memberSiteAccess, team, teamMember, teamSiteAccess } from "../db/postgres/schema.js";--/**- * Filters an organization's sites down to what a member-role user can access.- *- * Access is the union of:- * - explicit per-member grants (member_site_access) β these always apply,- * even to sites gated by a team the member is not on- * - sites granted through the member's teams β always additive, regardless- * of whether the member has restricted site access- * - sites not gated by any team β only when the member is unrestricted- *- * Callers must handle admin/owner roles themselves (they bypass filtering).- */-export async function filterSitesByMemberAccess<T extends { siteId: number }>(- orgSites: T[],- organizationId: string,- userId: string,- memberId: string,- hasRestrictedSiteAccess: boolean-): Promise<T[]> {- const [explicitGrants, teamGated, userTeams] = await Promise.all([- hasRestrictedSiteAccess- ? db- .select({ siteId: memberSiteAccess.siteId })- .from(memberSiteAccess)- .where(eq(memberSiteAccess.memberId, memberId))- : Promise.resolve([]),- db- .select({ siteId: teamSiteAccess.siteId })- .from(teamSiteAccess)- .innerJoin(team, eq(teamSiteAccess.teamId, team.id))- .where(eq(team.organizationId, organizationId)),- db- .select({ teamId: teamMember.teamId })- .from(teamMember)- .innerJoin(team, eq(teamMember.teamId, team.id))- .where(and(eq(teamMember.userId, userId), eq(team.organizationId, organizationId))),- ]);-- const explicitSiteIds = new Set(explicitGrants.map(g => g.siteId));- const teamGatedSiteIds = new Set(teamGated.map(s => s.siteId));-- const userTeamSiteIds = new Set<number>();- if (userTeams.length > 0) {- const userTeamSites = await db- .select({ siteId: teamSiteAccess.siteId })- .from(teamSiteAccess)- .where(- inArray(- teamSiteAccess.teamId,- userTeams.map(t => t.teamId)- )- );- for (const s of userTeamSites) {- userTeamSiteIds.add(s.siteId);- }- }-- return orgSites.filter(site => {- if (explicitSiteIds.has(site.siteId) || userTeamSiteIds.has(site.siteId)) {- return true;- }- if (hasRestrictedSiteAccess) {- return false;- }- return !teamGatedSiteIds.has(site.siteId);- });-}diff --git a/server/src/services/weekyReports/weeklyReportService.ts b/server/src/services/weekyReports/weeklyReportService.tsindex 3e6be1d2f..88546ad62 100644--- a/server/src/services/weekyReports/weeklyReportService.ts+++ b/server/src/services/weekyReports/weeklyReportService.ts@@ -7,7 +7,7 @@ import { clickhouse } from "../../db/clickhouse/clickhouse.js";import { getTimeStatement, processResults } from "../../api/analytics/utils/utils.js";import { createServiceLogger } from "../../lib/logger/logger.js";import { sendWeeklyReportEmail } from "../../lib/email/email.js";-import { filterSitesByMemberAccess } from "../../lib/siteAccess.js";+import { filterSitesByMemberAccess } from "../../lib/access.js";import { IS_CLOUD } from "../../lib/const.js";import {BreakdownDimension,