diff --git a/src/lib/db.ts b/src/lib/db.ts index 7a874a3b..8fc7d214 100644 --- a/src/lib/db.ts +++ b/src/lib/db.ts @@ -1,6 +1,7 @@ import { PrismaClient } from "../generated/prisma/client"; import { PrismaPg } from "@prisma/adapter-pg"; import { Pool } from "pg"; +import { headers } from "next/headers"; /** * Prisma client singleton — PostgreSQL only. @@ -15,6 +16,55 @@ const globalForPrisma = globalThis as unknown as { prisma: PrismaClient | undefined; }; +function applyTenantIsolation(client: any) { + // Use Prisma Client Extension to inject RLS + return client.$extends({ + query: { + $allModels: { + async $allOperations({ model, operation, args, query }: { model: string, operation: string, args: any, query: any }) { + let tenantSubdomain = null; + try { + const headersList = await headers(); + tenantSubdomain = headersList.get("x-tenant-subdomain"); + } catch (e) { + // Not in a request context (e.g. scripts, background jobs) + } + + if (tenantSubdomain && model !== 'Workspace' && model !== 'WorkspaceMember') { + args = args || {}; + + // Inject into data for creates + if (operation === 'create' || operation === 'createMany') { + if (Array.isArray(args.data)) { + args.data = args.data.map((d: any) => ({ ...d, tenantId: tenantSubdomain })); + } else if (args.data) { + args.data.tenantId = tenantSubdomain; + } + } + + // Inject into data for updates + if (operation === 'update' || operation === 'updateMany') { + if (args.data) args.data.tenantId = tenantSubdomain; + } + if (operation === 'upsert') { + if (args.create) args.create.tenantId = tenantSubdomain; + if (args.update) args.update.tenantId = tenantSubdomain; + } + + // Inject into where filters + if (['findUnique', 'findFirst', 'findMany', 'update', 'updateMany', 'delete', 'deleteMany', 'count', 'upsert'].includes(operation)) { + args.where = { ...(args.where || {}), tenantId: tenantSubdomain }; + } + + return query(args); + } + return query(args); + }, + }, + }, + }) as unknown as PrismaClient; // Cast to avoid complex type issues in consuming code for now +} + function createPrismaClient(): PrismaClient { const connectionString = process.env.DATABASE_URL; @@ -29,7 +79,8 @@ function createPrismaClient(): PrismaClient { const pool = new Pool({ connectionString }); const adapter = new PrismaPg(pool); - return new PrismaClient({ adapter } as any); + const client = new PrismaClient({ adapter } as any); + return applyTenantIsolation(client); } export const prisma = globalForPrisma.prisma ?? createPrismaClient();