Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: dataroom scoped members
Marc Seitzc94fb284e9b0
diff --git a/components/datarooms/dataroom-document-card.tsx b/components/datarooms/dataroom-document-card.tsxindex f55ff518..7b75daec 100644--- a/components/datarooms/dataroom-document-card.tsx+++ b/components/datarooms/dataroom-document-card.tsx@@ -196,7 +196,7 @@ export default function DataroomDocumentCard({e.stopPropagation();return;}- router.push(`/documents/${dataroomDocument.document.id}`);+ router.push(`/datarooms/${dataroomId}/document/${dataroomDocument.id}`);};return (@@ -262,7 +262,7 @@ export default function DataroomDocumentCard({onClick={(e) => {e.stopPropagation();}}- href={`/documents/${dataroomDocument.document.id}`}+ href={`/datarooms/${dataroomId}/document/${dataroomDocument.id}`}className="z-10 flex shrink-0 items-center space-x-1 rounded-md bg-gray-200 px-1.5 py-0.5 transition-all duration-75 hover:scale-105 active:scale-100 dark:bg-gray-700 sm:px-2"><BarChart className="h-3 w-3 text-muted-foreground sm:h-4 sm:w-4" />diff --git a/components/datarooms/folders/sidebar-tree.tsx b/components/datarooms/folders/sidebar-tree.tsxindex 1b472378..94060b0b 100644--- a/components/datarooms/folders/sidebar-tree.tsx+++ b/components/datarooms/folders/sidebar-tree.tsx@@ -26,11 +26,13 @@ type MixedItem =const DocumentFileItem = memo(({document,+ dataroomId,router,}: {document: DataroomFolderWithDocuments["documents"][0] & {itemType: "document";};+ dataroomId: string;router: any;}) => {const documentDisplayName = useHierarchicalDisplayName(@@ -41,7 +43,9 @@ const DocumentFileItem = memo(return (<FileTree.Filename={documentDisplayName}- onToggle={() => router.push(`/documents/${document.document.id}`)}+ onToggle={() =>+ router.push(`/datarooms/${dataroomId}/document/${document.id}`)+ }/>);},@@ -92,7 +96,12 @@ const FolderComponent = memo();} else {return (- <DocumentFileItem key={item.id} document={item} router={router} />+ <DocumentFileItem+ key={item.id}+ document={item}+ dataroomId={dataroomId}+ router={router}+ />);}}),diff --git a/components/datarooms/settings/introduction-settings.tsx b/components/datarooms/settings/introduction-settings.tsxindex abc537d7..9c9bf19d 100644--- a/components/datarooms/settings/introduction-settings.tsx+++ b/components/datarooms/settings/introduction-settings.tsx@@ -7,6 +7,7 @@ import { CrownIcon, EyeIcon } from "lucide-react";import { toast } from "sonner";import { mutate } from "swr";+import { useSelfMembership } from "@/lib/hooks/use-self-membership";import { usePlan } from "@/lib/swr/use-billing";import { cn, uploadImage } from "@/lib/utils";@@ -25,6 +26,7 @@ import LoadingSpinner from "@/components/ui/loading-spinner";import { RichTextEditor } from "@/components/ui/rich-text-editor";import { ScrollArea } from "@/components/ui/scroll-area";import { Switch } from "@/components/ui/switch";+import { ButtonTooltip } from "@/components/ui/tooltip";interface IntroductionSettingsProps {dataroomId: string;@@ -478,6 +480,7 @@ export default function IntroductionSettings({const teamInfo = useTeam();const teamId = teamInfo?.currentTeam?.id;const { isDataroomsPlus, isTrial } = usePlan();+ const { isDataroomMember } = useSelfMembership();const [isFetching, setIsFetching] = useState(true);const [isSaving, setIsSaving] = useState(false);@@ -714,6 +717,20 @@ export default function IntroductionSettings({: "Enable introduction page"}/>+ ) : isDataroomMember ? (+ <ButtonTooltip content="Only team admins can upgrade the plan. Contact a team admin to enable this feature.">+ <span tabIndex={0}>+ <Button+ variant="outline"+ size="sm"+ className="gap-1.5"+ disabled+ >+ <CrownIcon className="h-4 w-4" />+ Upgrade to enable+ </Button>+ </span>+ </ButtonTooltip>) : (<UpgradePlanModalclickedPlan={PlanEnum.DataRoomsPlus}diff --git a/components/documents/document-header.tsx b/components/documents/document-header.tsxindex 2011ed27..c910637d 100644--- a/components/documents/document-header.tsx+++ b/components/documents/document-header.tsx@@ -8,6 +8,7 @@ import { DocumentAIDialog } from "@/ee/features/ai/components/document-ai-dialogimport { PlanEnum } from "@/ee/stripe/constants";import { Document, DocumentVersion } from "@prisma/client";import {+ ArchiveXIcon,ArrowRightIcon,BetweenHorizontalStartIcon,ChevronRight,@@ -28,6 +29,7 @@ import { toast } from "sonner";import { mutate } from "swr";import { getFile } from "@/lib/files/get-file";+import { useSelfMembership } from "@/lib/hooks/use-self-membership";import { usePlan } from "@/lib/swr/use-billing";import useDataroomsSimple from "@/lib/swr/use-datarooms-simple";import { useTeamAI } from "@/lib/swr/use-team-ai";@@ -78,16 +80,30 @@ export default function DocumentHeader({teamId,actions,onBulkImportLinks,+ dataroomId,+ dataroomDocumentId,}: {prismaDocument: DocumentWithVersion;primaryVersion: DocumentVersion;teamId: string;actions?: React.ReactNode[];onBulkImportLinks?: () => void;+ /**+ * When the header is rendered inside a data room (the dataroom document+ * page), these identify the DataroomDocument so dataroom members can remove+ * it from the room instead of deleting the underlying document.+ */+ dataroomId?: string;+ dataroomDocumentId?: string;}) {const router = useRouter();const teamInfo = useTeam();const { datarooms } = useDataroomsSimple();+ const { isDataroomMember } = useSelfMembership();+ // Data room members may only remove a document from the room, never delete+ // the underlying document. Requires the dataroom context to be provided.+ const canRemoveFromDataroom = Boolean(dataroomId && dataroomDocumentId);+ const showRemoveFromDataroom = isDataroomMember && canRemoveFromDataroom;const { theme, systemTheme } = useTheme();const isLight =theme === "light" || (theme === "system" && systemTheme === "light");@@ -462,6 +478,45 @@ export default function DocumentHeader({);};+ const handleRemoveFromDataroom = async () => {+ if (!dataroomId || !dataroomDocumentId) return;++ toast.promise(+ fetch(+ `/api/teams/${teamId}/datarooms/${dataroomId}/documents/${dataroomDocumentId}`,+ {+ method: "DELETE",+ },+ ).then(async (res) => {+ if (!res.ok) {+ const error = await res.json().catch(() => ({}));+ throw new Error(error.message || "Failed to remove document");+ }+ setIsFirstClick(false);+ setMenuOpen(false);+ router.push(`/datarooms/${dataroomId}/documents`);+ }),+ {+ loading: "Removing document...",+ success: "Document removed from data room.",+ error: (err) => err.message || "Failed to remove document. Try again.",+ },+ );+ };++ const handleRemoveButtonClick = (event: any) => {+ event.stopPropagation();+ event.preventDefault();++ if (isFirstClick) {+ handleRemoveFromDataroom();+ setIsFirstClick(false);+ setMenuOpen(false);+ } else {+ setIsFirstClick(true);+ }+ };+const handleMenuStateChange = (open: boolean) => {if (isFirstClick) {setMenuOpen(true); // Keep the dropdown open on the first click@@ -857,13 +912,29 @@ export default function DocumentHeader({<DropdownMenuSeparator />- <DropdownMenuItem- className="text-destructive focus:bg-destructive focus:text-destructive-foreground"- onClick={(event) => handleButtonClick(event, prismaDocument.id)}- >- <TrashIcon className="mr-2 h-4 w-4" />- {isFirstClick ? "Really delete?" : "Delete document"}- </DropdownMenuItem>+ {isDataroomMember ? (+ // Data room members can only remove a document from the room,+ // never delete the underlying document for the whole team.+ showRemoveFromDataroom ? (+ <DropdownMenuItem+ className="text-destructive focus:bg-destructive focus:text-destructive-foreground"+ onClick={handleRemoveButtonClick}+ >+ <ArchiveXIcon className="mr-2 h-4 w-4" />+ {isFirstClick ? "Really remove?" : "Remove from data room"}+ </DropdownMenuItem>+ ) : null+ ) : (+ <DropdownMenuItem+ className="text-destructive focus:bg-destructive focus:text-destructive-foreground"+ onClick={(event) =>+ handleButtonClick(event, prismaDocument.id)+ }+ >+ <TrashIcon className="mr-2 h-4 w-4" />+ {isFirstClick ? "Really delete?" : "Delete document"}+ </DropdownMenuItem>+ )}</DropdownMenuContent></DropdownMenu></div>diff --git a/components/documents/stats.tsx b/components/documents/stats.tsxindex 6c779342..24c49dc8 100644--- a/components/documents/stats.tsx+++ b/components/documents/stats.tsx@@ -1,4 +1,4 @@-import { useRouter, useSearchParams } from "next/navigation";+import { usePathname, useRouter, useSearchParams } from "next/navigation";import { useState } from "react";@@ -13,24 +13,34 @@ import StatsChart from "./stats-chart";export const StatsComponent = ({documentId,numPages,+ dataroomId,}: {documentId: string;numPages: number;+ /**+ * When set, the stats are scoped to this data room's visits only (used on the+ * dataroom-scoped document page).+ */+ dataroomId?: string;}) => {const searchParams = useSearchParams();+ const pathname = usePathname();const router = useRouter();const initialExclude = searchParams?.get("excludeInternal") === "true";const [excludeTeamMembers, setExcludeTeamMembers] =useState<boolean>(initialExclude);- const statsData = useStats({ excludeTeamMembers });+ const statsData = useStats({ excludeTeamMembers, documentId, dataroomId });const onToggle = (checked: boolean) => {setExcludeTeamMembers(checked);const params = new URLSearchParams(searchParams?.toString());params.set("excludeInternal", checked.toString());- router.push(`${documentId}/?${params.toString()}`);+ // Update the query on the current route. Keep the pathname explicit so this+ // works both on /documents/[id] and the dataroom-scoped document page where+ // the route's last segment is not the document id.+ router.push(`${pathname}?${params.toString()}`);};return (diff --git a/components/layouts/app.tsx b/components/layouts/app.tsxindex 5b661947..987d7636 100644--- a/components/layouts/app.tsx+++ b/components/layouts/app.tsx@@ -1,9 +1,11 @@import { useRouter } from "next/router";-import { useCallback, useState } from "react";+import { useCallback, useEffect, useState } from "react";import Cookies from "js-cookie";+import { useSelfMembership } from "@/lib/hooks/use-self-membership";+import { AppBreadcrumb } from "@/components/layouts/breadcrumb";import { MobileBottomNav } from "@/components/layouts/mobile-bottom-nav";import { MobileHeader } from "@/components/layouts/mobile-header";@@ -35,6 +37,46 @@ function getInitialSidebarState(isDataroom: boolean): boolean {return true;}+/**+ * UX-only redirect guard for dataroom-scoped members. The API wrapper is the+ * real security boundary; this just keeps the scoped member from landing on+ * pages they cannot use. Redirects off non-dataroom paths and off datarooms+ * they are not assigned to, sending them to the datarooms list.+ */+function DataroomMemberRouteGuard() {+ const router = useRouter();+ const { isDataroomMember, allowedDataroomIds, loading } = useSelfMembership();++ useEffect(() => {+ if (loading || !isDataroomMember) return;++ const path = router.pathname;+ const onDataroomsArea =+ path === "/datarooms" || path.startsWith("/datarooms/[id]");++ if (!onDataroomsArea) {+ router.replace("/datarooms");+ return;+ }++ if (path.startsWith("/datarooms/[id]")) {+ const id = String(router.query.id || "");+ if (id && !allowedDataroomIds.includes(id)) {+ router.replace("/datarooms");+ }+ }+ }, [+ router,+ router.pathname,+ router.query.id,+ isDataroomMember,+ loading,+ allowedDataroomIds,+ ]);++ return null;+}+export default function AppLayout({ children }: { children: React.ReactNode }) {const router = useRouter();const isDataroom = router.pathname.startsWith("/datarooms/[id]");@@ -52,6 +94,7 @@ export default function AppLayout({ children }: { children: React.ReactNode }) {return (<SidebarProvider open={sidebarOpen} onOpenChange={handleSidebarOpenChange}>+ <DataroomMemberRouteGuard />{/* Single flex child of SidebarProvider so fixed mobile chrome is not laid out as extra row siblings (WebKit / in-app browsers). */}<div className="relative flex min-h-0 min-w-0 flex-1 flex-col"><div className="flex min-h-0 min-w-0 flex-1 flex-col gap-x-1 overflow-x-hidden bg-gray-50 dark:bg-black md:flex-row">diff --git a/components/layouts/breadcrumb.tsx b/components/layouts/breadcrumb.tsxindex 199eac20..1c76aad4 100644--- a/components/layouts/breadcrumb.tsx+++ b/components/layouts/breadcrumb.tsx@@ -4,6 +4,7 @@ import { useRouter } from "next/router";import React, { useEffect, useMemo, useRef, useState } from "react";import { useDataroom } from "@/lib/swr/use-dataroom";+import { useDataroomDocumentOverview } from "@/lib/swr/use-dataroom-document";import { useDocument } from "@/lib/swr/use-document";import { useFolderWithParents } from "@/lib/swr/use-folders";import useViewer from "@/lib/swr/use-viewer";@@ -203,6 +204,41 @@ const SingleDataroomBreadcrumb = ({ path }: { path: string }) => {);};+const SingleDataroomDocumentBreadcrumb = () => {+ const { dataroom, document } = useDataroomDocumentOverview();++ return (+ <Breadcrumb>+ <BreadcrumbList>+ <BreadcrumbItem>+ <BreadcrumbLink asChild>+ <Link href="/datarooms">Datarooms</Link>+ </BreadcrumbLink>+ </BreadcrumbItem>+ <BreadcrumbSeparator />+ <BreadcrumbItem>+ <TruncatedBreadcrumbLink+ href={`/datarooms/${dataroom?.id}/documents`}+ text={dataroom?.name}+ />+ </BreadcrumbItem>+ <BreadcrumbSeparator />+ <BreadcrumbItem>+ <BreadcrumbLink asChild>+ <Link href={`/datarooms/${dataroom?.id}/documents`}>Documents</Link>+ </BreadcrumbLink>+ </BreadcrumbItem>+ <BreadcrumbSeparator />+ <BreadcrumbItem>+ <BreadcrumbPage className="max-w-[200px] truncate">+ {document?.name || "Loading..."}+ </BreadcrumbPage>+ </BreadcrumbItem>+ </BreadcrumbList>+ </Breadcrumb>+ );+};+const SettingsBreadcrumb = () => {const router = useRouter();const path = router.pathname;@@ -511,6 +547,11 @@ export const AppBreadcrumb = () => {return <DataroomBreadcrumb />;}+ // Single dataroom document route+ if (path === "/datarooms/[id]/document/[documentId]" && id) {+ return <SingleDataroomDocumentBreadcrumb />;+ }+// Single dataroom routeif (path.startsWith("/datarooms/[id]") && id) {return <SingleDataroomBreadcrumb path={path} />;diff --git a/components/layouts/mobile-bottom-nav.tsx b/components/layouts/mobile-bottom-nav.tsxindex a3a9d394..432acf07 100644--- a/components/layouts/mobile-bottom-nav.tsx+++ b/components/layouts/mobile-bottom-nav.tsx@@ -3,6 +3,7 @@ import { useRouter } from "next/router";import { useState } from "react";+import { PlanEnum } from "@/ee/stripe/constants";import {BarChart3Icon,FolderIcon,@@ -12,8 +13,8 @@ import {ShieldCheckIcon,} from "lucide-react";+import { useSelfMembership } from "@/lib/hooks/use-self-membership";import { usePlan } from "@/lib/swr/use-billing";-import { PlanEnum } from "@/ee/stripe/constants";import { cn } from "@/lib/utils";import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";@@ -26,6 +27,8 @@ export function MobileBottomNav() {const router = useRouter();const [moreOpen, setMoreOpen] = useState(false);const { isBusiness, isDatarooms, isDataroomsPlus, isTrial } = usePlan();+ // Dataroom-scoped members only ever see their assigned data rooms.+ const { isDataroomMember } = useSelfMembership();const dataroomsEnabled =isBusiness || isDatarooms || isDataroomsPlus || isTrial;@@ -44,8 +47,9 @@ export function MobileBottomNav() {return router.pathname.includes(match);};- const moreIsActive =- !["dashboard", "documents", "datarooms"].some((m) => isActive(m));+ const moreIsActive = !["dashboard", "documents", "datarooms"].some((m) =>+ isActive(m),+ );const tabClass = (active: boolean) =>cn(@@ -81,7 +85,7 @@ export function MobileBottomNav() {const base = `/datarooms/${dataroomId}`;return (<>- <nav className="fixed inset-x-0 bottom-0 z-50 border-t border-border bg-background pb-[env(safe-area-inset-bottom,0px)] [-webkit-tap-highlight-color:transparent] touch-manipulation md:hidden">+ <nav className="fixed inset-x-0 bottom-0 z-50 touch-manipulation border-t border-border bg-background pb-[env(safe-area-inset-bottom,0px)] [-webkit-tap-highlight-color:transparent] md:hidden"><div className="flex min-h-[4.5rem] items-end justify-between gap-0.5 px-0.5"><Linkhref={`${base}/documents`}@@ -127,9 +131,37 @@ export function MobileBottomNav() {);}+ // Scoped members get a minimal nav: only their data rooms plus the More+ // sheet (for team switching). Everything else is hidden, mirroring the+ // desktop sidebar.+ if (isDataroomMember) {+ return (+ <>+ <nav className="fixed inset-x-0 bottom-0 z-50 touch-manipulation border-t border-border bg-background pb-[env(safe-area-inset-bottom,0px)] [-webkit-tap-highlight-color:transparent] md:hidden">+ <div className="flex min-h-[4.5rem] items-end justify-around gap-0.5 px-0.5">+ <Link href="/datarooms" className={tabClass(isActive("datarooms"))}>+ <ServerIcon className="h-6 w-6" />+ <span>Data Rooms</span>+ </Link>+ <button+ type="button"+ onClick={() => setMoreOpen(true)}+ className={tabClass(!isActive("datarooms"))}+ >+ <MoreHorizontalIcon className="h-6 w-6" />+ <span>More</span>+ </button>+ </div>+ </nav>++ <MobileMoreMenu open={moreOpen} onClose={() => setMoreOpen(false)} />+ </>+ );+ }+return (<>- <nav className="fixed inset-x-0 bottom-0 z-50 border-t border-border bg-background pb-[env(safe-area-inset-bottom,0px)] [-webkit-tap-highlight-color:transparent] touch-manipulation md:hidden">+ <nav className="fixed inset-x-0 bottom-0 z-50 touch-manipulation border-t border-border bg-background pb-[env(safe-area-inset-bottom,0px)] [-webkit-tap-highlight-color:transparent] md:hidden"><div className="flex min-h-[4.5rem] items-end justify-between gap-0.5 px-0.5"><Link href="/dashboard" className={tabClass(isActive("dashboard"))}><HouseIcon className="h-6 w-6" />diff --git a/components/layouts/mobile-more-menu.tsx b/components/layouts/mobile-more-menu.tsxindex bdc150c4..cfff0d76 100644--- a/components/layouts/mobile-more-menu.tsx+++ b/components/layouts/mobile-more-menu.tsx@@ -4,6 +4,7 @@ import { useRouter } from "next/router";import { useEffect, useState } from "react";import { useTeam } from "@/context/team-context";+import { PlanEnum } from "@/ee/stripe/constants";import {BrushIcon,ChevronDownIcon,@@ -13,10 +14,10 @@ import {} from "lucide-react";import { useIsAdmin } from "@/lib/hooks/use-is-admin";+import { useSelfMembership } from "@/lib/hooks/use-self-membership";import { usePlan } from "@/lib/swr/use-billing";import useLimits from "@/lib/swr/use-limits";import { useSlackIntegration } from "@/lib/swr/use-slack-integration";-import { PlanEnum } from "@/ee/stripe/constants";import { Team } from "@/lib/types";import { cn, nFormatter } from "@/lib/utils";@@ -37,11 +38,13 @@ export function MobileMoreMenu({ open, onClose }: MobileMoreMenuProps) {const { isFree, isTrial } = usePlan();const { limits } = useLimits();const { isAdmin } = useIsAdmin();+ // Scoped members can't reach team-wide areas (visitors, branding, settings).+ const { isDataroomMember } = useSelfMembership();const { integration: slackIntegration } = useSlackIntegration({enabled: !!currentTeam?.id,});- const [settingsExpanded, setSettingsExpanded] = useState(- () => router.pathname.includes("settings"),+ const [settingsExpanded, setSettingsExpanded] = useState(() =>+ router.pathname.includes("settings"),);const switchTeam = (team: Pick<Team, "id" | "name">) => {@@ -79,7 +82,7 @@ export function MobileMoreMenu({ open, onClose }: MobileMoreMenuProps) {];return (- <div className="fixed inset-0 z-50 flex flex-col bg-background pt-[env(safe-area-inset-top,0px)] pb-[env(safe-area-inset-bottom,0px)] [-webkit-tap-highlight-color:transparent] touch-manipulation md:hidden">+ <div className="fixed inset-0 z-50 flex touch-manipulation flex-col bg-background pb-[env(safe-area-inset-bottom,0px)] pt-[env(safe-area-inset-top,0px)] [-webkit-tap-highlight-color:transparent] md:hidden"><div className="flex h-14 shrink-0 items-center justify-between border-b border-border px-4"><span className="text-lg font-semibold">More</span><button@@ -101,101 +104,103 @@ export function MobileMoreMenu({ open, onClose }: MobileMoreMenuProps) {)}<div className="space-y-1">- {isFree && !isTrial ? (- <UpgradePlanModal- clickedPlan={PlanEnum.Pro}- trigger="mobile_more_visitors"- highlightItem={["visitors"]}- >- <button- className="flex w-full items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"- >- <ContactIcon className="h-5 w-5" />- Visitors- </button>- </UpgradePlanModal>- ) : (- <Link- href="/visitors"- onClick={onClose}- className={cn(- "flex items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium transition-colors",- router.pathname.includes("visitors")- ? "bg-muted text-foreground"- : "text-muted-foreground hover:bg-muted hover:text-foreground",+ {!isDataroomMember && (+ <>+ {isFree && !isTrial ? (+ <UpgradePlanModal+ clickedPlan={PlanEnum.Pro}+ trigger="mobile_more_visitors"+ highlightItem={["visitors"]}+ >+ <button className="flex w-full items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground">+ <ContactIcon className="h-5 w-5" />+ Visitors+ </button>+ </UpgradePlanModal>+ ) : (+ <Link+ href="/visitors"+ onClick={onClose}+ className={cn(+ "flex items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium transition-colors",+ router.pathname.includes("visitors")+ ? "bg-muted text-foreground"+ : "text-muted-foreground hover:bg-muted hover:text-foreground",+ )}+ >+ <ContactIcon className="h-5 w-5" />+ Visitors+ </Link>)}- >- <ContactIcon className="h-5 w-5" />- Visitors- </Link>- )}- <Link- href="/branding"- onClick={onClose}- className={cn(- "flex items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium transition-colors",- router.pathname.includes("branding")- ? "bg-muted text-foreground"- : "text-muted-foreground hover:bg-muted hover:text-foreground",- )}- >- <BrushIcon className="h-5 w-5" />- Branding- </Link>-- {/* Settings with expandable sub-items */}- <div>- <button- onClick={() => setSettingsExpanded((v) => !v)}- className={cn(- "flex w-full items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium transition-colors",- router.pathname.includes("settings")- ? "bg-muted text-foreground"- : "text-muted-foreground hover:bg-muted hover:text-foreground",- )}- >- <CogIcon className="h-5 w-5" />- Settings- <ChevronDownIcon+ <Link+ href="/branding"+ onClick={onClose}className={cn(- "ml-auto h-4 w-4 transition-transform",- settingsExpanded && "rotate-180",+ "flex items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium transition-colors",+ router.pathname.includes("branding")+ ? "bg-muted text-foreground"+ : "text-muted-foreground hover:bg-muted hover:text-foreground",)}- />- </button>- {settingsExpanded && (- <div className="ml-8 mt-1 space-y-0.5 border-l border-border pl-3">- {settingsSubItems.map((sub) => (- <Link- key={sub.href}- href={sub.href}- onClick={onClose}+ >+ <BrushIcon className="h-5 w-5" />+ Branding+ </Link>++ {/* Settings with expandable sub-items */}+ <div>+ <button+ onClick={() => setSettingsExpanded((v) => !v)}+ className={cn(+ "flex w-full items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium transition-colors",+ router.pathname.includes("settings")+ ? "bg-muted text-foreground"+ : "text-muted-foreground hover:bg-muted hover:text-foreground",+ )}+ >+ <CogIcon className="h-5 w-5" />+ Settings+ <ChevronDownIconclassName={cn(- "block rounded-md px-3 py-2 text-sm transition-colors",- router.pathname.includes(- sub.href.replace("/settings/", "settings/"),- )- ? "font-medium text-foreground"- : "text-muted-foreground hover:text-foreground",+ "ml-auto h-4 w-4 transition-transform",+ settingsExpanded && "rotate-180",)}- >- {sub.label}- </Link>- ))}+ />+ </button>+ {settingsExpanded && (+ <div className="ml-8 mt-1 space-y-0.5 border-l border-border pl-3">+ {settingsSubItems.map((sub) => (+ <Link+ key={sub.href}+ href={sub.href}+ onClick={onClose}+ className={cn(+ "block rounded-md px-3 py-2 text-sm transition-colors",+ router.pathname.includes(+ sub.href.replace("/settings/", "settings/"),+ )+ ? "font-medium text-foreground"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ {sub.label}+ </Link>+ ))}+ </div>+ )}</div>- )}- </div>- {!slackIntegration && (- <Link- href="/settings/slack"- onClick={onClose}- className="flex items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"- >- <SlackIcon className="h-5 w-5" />- Connect Slack- </Link>+ {!slackIntegration && (+ <Link+ href="/settings/slack"+ onClick={onClose}+ className="flex items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"+ >+ <SlackIcon className="h-5 w-5" />+ Connect Slack+ </Link>+ )}+ </>)}</div>diff --git a/components/sidebar/app-sidebar.tsx b/components/sidebar/app-sidebar.tsxindex 591537d8..598abf57 100644--- a/components/sidebar/app-sidebar.tsx+++ b/components/sidebar/app-sidebar.tsx@@ -21,6 +21,7 @@ import {import { useFeatureFlags } from "@/lib/hooks/use-feature-flags";import { useIsAdmin } from "@/lib/hooks/use-is-admin";+import { useSelfMembership } from "@/lib/hooks/use-self-membership";import { usePlan } from "@/lib/swr/use-billing";import useDataroomsSimple from "@/lib/swr/use-datarooms-simple";import useLimits from "@/lib/swr/use-limits";@@ -71,7 +72,11 @@ export function AppSidebarContent() {// Check if current user is admin (for gating Security)const { isAdmin } = useIsAdmin();+ // Dataroom-scoped members only ever see their assigned datarooms.+ const { isDataroomMember } = useSelfMembership();+// Fetch datarooms for the current team (simple mode - no filters or extra data)+ // For scoped members the API already restricts this to their assigned rooms.const { datarooms } = useDataroomsSimple();useEffect(() => {@@ -220,13 +225,40 @@ export function AppSidebarContent() {};// Filter out items that should be hidden based on feature flags- const filteredNavMain = data.navMain.filter((item) => {+ let filteredNavMain = data.navMain.filter((item) => {if (item.title === "Workflows" && !features?.workflows) {return false;}return true;});+ // Dataroom-scoped members get a single Datarooms section listing only their+ // assigned rooms. Dashboard, All Documents, Visitors, Workflows, Branding and+ // Settings are hidden — they have no access to those areas.+ if (isDataroomMember) {+ const scopedDataroomItems =+ datarooms && datarooms.length > 0+ ? datarooms.map((dataroom) => ({+ title: dataroom.internalName || dataroom.name,+ url: `/datarooms/${dataroom.id}/documents`,+ current:+ router.pathname.includes("/datarooms/[id]") &&+ String(router.query.id) === String(dataroom.id),+ }))+ : undefined;++ filteredNavMain = [+ {+ title: "Data Rooms",+ url: "/datarooms",+ icon: ServerIcon,+ current: router.pathname === "/datarooms",+ isActive: router.pathname.includes("datarooms"),+ items: scopedDataroomItems,+ },+ ] as typeof filteredNavMain;+ }+return (<><SidebarHeader className="gap-y-0 pt-0">diff --git a/components/sidebar/dataroom-sidebar.tsx b/components/sidebar/dataroom-sidebar.tsxindex 8e042b3e..ff81de7c 100644--- a/components/sidebar/dataroom-sidebar.tsx+++ b/components/sidebar/dataroom-sidebar.tsx@@ -27,6 +27,7 @@ import {UsersIcon,} from "lucide-react";+import { useSelfMembership } from "@/lib/hooks/use-self-membership";import { useDataroom } from "@/lib/swr/use-dataroom";import { cn } from "@/lib/utils";@@ -120,9 +121,48 @@ export function DataroomSidebarContent() {const router = useRouter();const { dataroom } = useDataroom();const { state, isMobile } = useSidebar();+ const { isDataroomMember } = useSelfMembership();const dataroomId = dataroom?.id ?? (router.query.id as string);const [isLinkSheetOpen, setIsLinkSheetOpen] = useState(false);+ // Dataroom-scoped members manage the room but cannot delete/freeze it.+ const settingsItems = [+ {+ title: "General",+ href: `/datarooms/${dataroomId}/settings`,+ icon: CogIcon,+ },+ {+ title: "Introduction",+ href: `/datarooms/${dataroomId}/settings/introduction`,+ icon: BookOpenIcon,+ },+ {+ title: "Notifications",+ href: `/datarooms/${dataroomId}/settings/notifications`,+ icon: BellIcon,+ },+ {+ title: "Downloads",+ href: `/datarooms/${dataroomId}/settings/downloads`,+ icon: DownloadIcon,+ },+ {+ title: "File Permissions",+ href: `/datarooms/${dataroomId}/settings/file-permissions`,+ icon: ShieldIcon,+ },+ ...(isDataroomMember+ ? []+ : [+ {+ title: "Danger Zone",+ href: `/datarooms/${dataroomId}/settings/danger`,+ icon: TriangleAlertIcon,+ },+ ]),+ ];+const navItems = [{title: "Documents",@@ -184,38 +224,7 @@ export function DataroomSidebarContent() {href: `/datarooms/${dataroomId}/settings`,icon: CogIcon,segment: "settings",- items: [- {- title: "General",- href: `/datarooms/${dataroomId}/settings`,- icon: CogIcon,- },- {- title: "Introduction",- href: `/datarooms/${dataroomId}/settings/introduction`,- icon: BookOpenIcon,- },- {- title: "Notifications",- href: `/datarooms/${dataroomId}/settings/notifications`,- icon: BellIcon,- },- {- title: "Downloads",- href: `/datarooms/${dataroomId}/settings/downloads`,- icon: DownloadIcon,- },- {- title: "File Permissions",- href: `/datarooms/${dataroomId}/settings/file-permissions`,- icon: ShieldIcon,- },- {- title: "Danger Zone",- href: `/datarooms/${dataroomId}/settings/danger`,- icon: TriangleAlertIcon,- },- ],+ items: settingsItems,},];@@ -226,6 +235,7 @@ export function DataroomSidebarContent() {if (item.segment === "documents") {return (currentPath.includes(`/datarooms/${dataroomId}/documents`) ||+ currentPath.includes(`/datarooms/${dataroomId}/document/`) ||currentPath === `/datarooms/${dataroomId}`);}diff --git a/components/sidebar/team-switcher.tsx b/components/sidebar/team-switcher.tsxindex d0ad0532..5e150af1 100644--- a/components/sidebar/team-switcher.tsx+++ b/components/sidebar/team-switcher.tsx@@ -5,6 +5,8 @@ import * as React from "react";import { useLimits } from "@/ee/limits/swr-handler";import { PlanEnum } from "@/ee/stripe/constants";import { ChevronsUpDown, UserRoundPlusIcon } from "lucide-react";++import { useSelfMembership } from "@/lib/hooks/use-self-membership";import { usePlan } from "@/lib/swr/use-billing";import { Team } from "@/lib/types";import { cn } from "@/lib/utils";@@ -46,6 +48,8 @@ export function TeamSwitcher({const { isMobile } = useSidebar();const { canAddUsers, showUpgradePlanModal } = useLimits();const { isTrial, isDataroomsPremium } = usePlan();+ // Dataroom-scoped members can't invite teammates; hide the invite control.+ const { isDataroomMember } = useSelfMembership();const switchTeam = (team: Team) => {localStorage.setItem("currentTeamId", team.id);@@ -109,13 +113,15 @@ export function TeamSwitcher({{isDataroomsPremium ? (<AddTeamModal setCurrentTeam={setCurrentTeam}><DropdownMenuItem- className="gap-2 p-2 cursor-pointer"+ className="cursor-pointer gap-2 p-2"onSelect={(e) => e.preventDefault()}><div className="flex size-6 items-center justify-center rounded-md border bg-background"><UserRoundPlusIcon className="size-4" /></div>- <div className="font-medium text-muted-foreground">Add new team</div>+ <div className="font-medium text-muted-foreground">+ Add new team+ </div></DropdownMenuItem></AddTeamModal>) : (@@ -125,56 +131,63 @@ export function TeamSwitcher({highlightItem={["teams"]}><DropdownMenuItem- className="gap-2 p-2 cursor-pointer"+ className="cursor-pointer gap-2 p-2"onSelect={(e) => e.preventDefault()}><div className="flex size-6 items-center justify-center rounded-md border bg-background"><UserRoundPlusIcon className="size-4" /></div>- <div className="font-medium text-muted-foreground">Add new team</div>+ <div className="font-medium text-muted-foreground">+ Add new team+ </div></DropdownMenuItem></UpgradePlanModal>)}</DropdownMenuContent></DropdownMenu></SidebarMenuItem>- <SidebarMenuItem>- {showUpgradePlanModal ? (- <UpgradePlanModal- clickedPlan={PlanEnum.Business}- trigger={"invite_team_members"}- highlightItem={["users"]}- >- <SidebarMenuButton- size="lg"- className="size-12 justify-center border data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground group-data-[collapsible=icon]:hidden"+ {!isDataroomMember && (+ <SidebarMenuItem>+ {showUpgradePlanModal ? (+ <UpgradePlanModal+ clickedPlan={PlanEnum.Business}+ trigger={"invite_team_members"}+ highlightItem={["users"]}>- <UserRoundPlusIcon className="!size-5" strokeWidth={1.5} />- </SidebarMenuButton>- </UpgradePlanModal>- ) : canAddUsers ? (- <AddTeamMembers- open={isTeamMemberInviteModalOpen}- setOpen={setTeamMemberInviteModalOpen}- >- <SidebarMenuButton- size="lg"- className="size-12 justify-center border data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground group-data-[collapsible=icon]:hidden"+ <SidebarMenuButton+ size="lg"+ className="size-12 justify-center border data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground group-data-[collapsible=icon]:hidden"+ >+ <UserRoundPlusIcon className="!size-5" strokeWidth={1.5} />+ </SidebarMenuButton>+ </UpgradePlanModal>+ ) : canAddUsers ? (+ <AddTeamMembers+ open={isTeamMemberInviteModalOpen}+ setOpen={setTeamMemberInviteModalOpen}>- <UserRoundPlusIcon className="!size-5" strokeWidth={1.5} />- </SidebarMenuButton>- </AddTeamMembers>- ) : (- <AddSeatModal open={isAddSeatModalOpen} setOpen={setAddSeatModalOpen}>- <SidebarMenuButton- size="lg"- className="size-12 justify-center border data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground group-data-[collapsible=icon]:hidden"+ <SidebarMenuButton+ size="lg"+ className="size-12 justify-center border data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground group-data-[collapsible=icon]:hidden"+ >+ <UserRoundPlusIcon className="!size-5" strokeWidth={1.5} />+ </SidebarMenuButton>+ </AddTeamMembers>+ ) : (+ <AddSeatModal+ open={isAddSeatModalOpen}+ setOpen={setAddSeatModalOpen}>- <UserRoundPlusIcon className="!size-5" strokeWidth={1.5} />- </SidebarMenuButton>- </AddSeatModal>- )}- </SidebarMenuItem>+ <SidebarMenuButton+ size="lg"+ className="size-12 justify-center border data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground group-data-[collapsible=icon]:hidden"+ >+ <UserRoundPlusIcon className="!size-5" strokeWidth={1.5} />+ </SidebarMenuButton>+ </AddSeatModal>+ )}+ </SidebarMenuItem>+ )}</SidebarMenu>);}diff --git a/components/teams/add-team-member-modal.tsx b/components/teams/add-team-member-modal.tsxindex 32872538..b2b11227 100644--- a/components/teams/add-team-member-modal.tsx+++ b/components/teams/add-team-member-modal.tsx@@ -18,8 +18,19 @@ 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 { useAnalytics } from "@/lib/analytics";+import { usePlan } from "@/lib/swr/use-billing";+import useDataroomsSimple from "@/lib/swr/use-datarooms-simple";++type InviteRole = "ADMIN" | "MANAGER" | "MEMBER" | "DATAROOM_MEMBER";export function AddTeamMembers({open,@@ -31,11 +42,21 @@ export function AddTeamMembers({children?: React.ReactNode;}) {const [email, setEmail] = useState<string>("");+ const [role, setRole] = useState<InviteRole>("MEMBER");+ const [selectedDataroomIds, setSelectedDataroomIds] = useState<string[]>([]);const [loading, setLoading] = useState<boolean>(false);const teamInfo = useTeam();const teamId = teamInfo?.currentTeam?.id;const analytics = useAnalytics();const router = useRouter();+ const { datarooms } = useDataroomsSimple();+ const { isDatarooms } = usePlan();++ const toggleDataroom = (id: string) => {+ setSelectedDataroomIds((prev) =>+ prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id],+ );+ };const emailSchema = z.string().trim()@@ -53,6 +74,11 @@ export function AddTeamMembers({return;}+ if (role === "DATAROOM_MEMBER" && selectedDataroomIds.length === 0) {+ toast.error("Select at least one data room for a data room member.");+ return;+ }+setLoading(true);const response = await fetch(`/api/teams/${teamId}/invite`, {method: "POST",@@ -61,6 +87,8 @@ export function AddTeamMembers({},body: JSON.stringify({email: validation.data,+ role,+ dataroomIds: role === "DATAROOM_MEMBER" ? selectedDataroomIds : [],}),});@@ -99,16 +127,80 @@ export function AddTeamMembers({</DialogDescription></DialogHeader><form onSubmit={handleSubmit}>- <Label htmlFor="domain" className="opacity-80">+ <Label htmlFor="email" className="opacity-80"></Label><Inputid="email"placeholder="[email protected]"- className="mb-8 mt-1 w-full"+ className="mb-4 mt-1 w-full"onChange={(e) => setEmail(e.target.value)}/>+ <Label htmlFor="role" className="opacity-80">+ Role+ </Label>+ <Select+ value={role}+ onValueChange={(value) => setRole(value as InviteRole)}+ >+ <SelectTrigger id="role" className="mb-4 mt-1 w-full">+ <SelectValue placeholder="Select a role" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="ADMIN">Admin</SelectItem>+ <SelectItem value="MANAGER">Manager</SelectItem>+ <SelectItem value="MEMBER">Member</SelectItem>+ <SelectItem+ value="DATAROOM_MEMBER"+ disabled={!isDatarooms}+ trailingContent={+ !isDatarooms ? (+ <span className="ml-auto pl-3 text-xs text-muted-foreground">+ Data Rooms plan+ </span>+ ) : undefined+ }+ >+ Data room member+ </SelectItem>+ </SelectContent>+ </Select>++ {role === "DATAROOM_MEMBER" ? (+ <div className="mb-8">+ <Label className="opacity-80">Data rooms</Label>+ <p className="mb-2 mt-1 text-xs text-muted-foreground">+ The member can only manage the selected data rooms.+ </p>+ <div className="max-h-44 space-y-1 overflow-y-auto rounded-md border p-2">+ {datarooms && datarooms.length > 0 ? (+ datarooms.map((dataroom) => (+ <label+ key={dataroom.id}+ className="flex cursor-pointer items-center gap-2 rounded px-2 py-1 text-sm hover:bg-muted"+ >+ <input+ type="checkbox"+ checked={selectedDataroomIds.includes(dataroom.id)}+ onChange={() => toggleDataroom(dataroom.id)}+ />+ <span className="truncate">+ {dataroom.internalName || dataroom.name}+ </span>+ </label>+ ))+ ) : (+ <p className="px-2 py-1 text-sm text-muted-foreground">+ No data rooms available.+ </p>+ )}+ </div>+ </div>+ ) : (+ <div className="mb-8" />+ )}+<DialogFooter><Button type="submit" className="h-9 w-full">{loading ? "Sending email..." : "Add member"}diff --git a/components/visitors/visitor-chart.tsx b/components/visitors/visitor-chart.tsxindex 303bb75b..deabcfc7 100644--- a/components/visitors/visitor-chart.tsx+++ b/components/visitors/visitor-chart.tsx@@ -32,7 +32,7 @@ export default function VisitorChart({}[];} | null;}) {- const { stats, error } = useVisitorStats(viewId);+ const { stats, error } = useVisitorStats(viewId, documentId);if (error && error.status === 404) {return <ErrorPage statusCode={404} />;diff --git a/components/visitors/visitor-useragent.tsx b/components/visitors/visitor-useragent.tsxindex ab15c2c5..c5082fb1 100644--- a/components/visitors/visitor-useragent.tsx+++ b/components/visitors/visitor-useragent.tsx@@ -2,8 +2,14 @@ import { useVisitorUserAgent } from "@/lib/swr/use-stats";import VisitorUserAgentBase from "./visitor-useragent-base";-export default function VisitorUserAgent({ viewId }: { viewId: string }) {- const { userAgent, error } = useVisitorUserAgent(viewId);+export default function VisitorUserAgent({+ viewId,+ documentId,+}: {+ viewId: string;+ documentId?: string;+}) {+ const { userAgent, error } = useVisitorUserAgent(viewId, documentId);if (error) {return null;diff --git a/components/visitors/visitors-table.tsx b/components/visitors/visitors-table.tsxindex 5a4808c3..a08ab211 100644--- a/components/visitors/visitors-table.tsx+++ b/components/visitors/visitors-table.tsx@@ -101,9 +101,41 @@ const isSignedAgreementResponse = (export default function VisitorsTable({primaryVersion,isVideo = false,+ documentId,+ dataroomId,+ viewScope = "all",+ title = "All visitors",+ emptyMessage = "No views yet. Try sharing a link.",+ hideWhenEmpty = false,}: {primaryVersion: DocumentVersion;isVideo?: boolean;+ /**+ * Explicit document id. Defaults to router.query.id when omitted. Pass this+ * on the dataroom-scoped document page where router.query.id is the dataroom+ * id, not the document id.+ */+ documentId?: string;+ /**+ * Scope the visits to a single data room. Required for `viewScope` to take+ * effect. Passed on the dataroom-scoped document page.+ */+ dataroomId?: string;+ /**+ * `dataroom` → only this room's visits; `other` → only the document's+ * direct-link visits; `all` → every visit (default). Only `dataroom`/`other`+ * require `dataroomId`.+ */+ viewScope?: "all" | "dataroom" | "other";+ /** Heading shown above the table. */+ title?: string;+ /** Message rendered when there are no visits to show. */+ emptyMessage?: string;+ /**+ * When true, the whole section is hidden (renders nothing) while loading or+ * when there are no visits. Used for the optional "other visits" section.+ */+ hideWhenEmpty?: boolean;}) {const teamInfo = useTeam();const teamId = teamInfo?.currentTeam?.id;@@ -113,6 +145,10 @@ export default function VisitorsTable({const { views, mutate: mutateViews } = useDocumentVisits(currentPage,pageSize,+ documentId,+ dataroomId && viewScope !== "all"+ ? { dataroomId, scope: viewScope }+ : undefined,);const { plan, isTrial, isPaused } = usePlan();const isFreePlan = plan === "free";@@ -190,9 +226,14 @@ export default function VisitorsTable({// mutate the views on the current pagemutateViews();- // mutate the stats+ // mutate the stats (covers both the plain and dataroom-scoped stats keys)+ const statsKeyPrefix = `/api/teams/${teamId}/documents/${encodeURIComponent(+ targetId,+ )}/stats`;mutate(- `/api/teams/${teamId}/documents/${encodeURIComponent(targetId)}/stats`,+ (key) => typeof key === "string" && key.startsWith(statsKeyPrefix),+ undefined,+ { revalidate: true },);toast.success(@@ -203,10 +244,21 @@ export default function VisitorsTable({setIsLoading(false);};+ const hasNoViews =+ !!views &&+ views.viewsWithDuration.length === 0 &&+ views.hiddenViewCount === 0;++ // Optional sections (e.g. "other visits from document link") hide themselves+ // entirely while loading or when empty, so no empty header is shown.+ if (hideWhenEmpty && (!views || hasNoViews)) {+ return null;+ }+return (<div className="w-full"><div className="mb-2 flex items-center gap-2 md:mb-4">- <h2>All visitors</h2>+ <h2>{title}</h2>{views && views.totalViews > 0 && (<Badge variant="outline" className="text-muted-foreground">{views.totalViews}@@ -230,7 +282,7 @@ export default function VisitorsTable({<TableRow><TableCell colSpan={5}><div className="flex h-40 w-full items-center justify-center">- <p>No views yet. Try sharing a link.</p>+ <p>{emptyMessage}</p></div></TableCell></TableRow>@@ -589,7 +641,10 @@ export default function VisitorsTable({/>)}{!isFreePlan ? (- <VisitorUserAgent viewId={view.id} />+ <VisitorUserAgent+ viewId={view.id}+ documentId={view.documentId ?? undefined}+ />) : (<VisitorUserAgentPlaceholder />)}diff --git a/lib/api/auth/with-session-team.ts b/lib/api/auth/with-session-team.tsnew file mode 100644index 00000000..476162ee--- /dev/null+++ b/lib/api/auth/with-session-team.ts@@ -0,0 +1,313 @@+import { NextApiRequest, NextApiResponse } from "next";+import { NextRequest, NextResponse } from "next/server";++import { Role } from "@prisma/client";+import { getServerSession } from "next-auth";++import { authOptions } from "@/lib/auth/auth-options";+import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";++import {+ type PermissionAction,+ getPermissionsByRole,+ isDataroomScopedRole,+} from "@/lib/api/rbac/permissions";+import {+ canAccessDataroom,+ getAllowedDataroomIds,+} from "@/lib/api/rbac/entitlements";++/**+ * Unified session-based `withTeam` wrapper for internal (NextAuth) routes.+ *+ * It centralises the membership/role logic that today is copy-pasted as inline+ * `prisma.userTeam.findUnique` checks across every team route, and adds RBAC+ * permissions plus a per-room entitlement check for the dataroom-scoped role.+ *+ * Crucially it is **default-deny for DATAROOM_MEMBER**: a scoped member is+ * rejected on any wrapped route unless the route explicitly opts in by+ * declaring a `requiredPermissions` set the role holds (and, when a+ * `dataroomParam`/`resolveDataroomId` is configured, passes the room+ * entitlement). This makes "don't leak to scoped members" auditable instead of+ * relying on per-handler guards.+ */++export interface SessionTeamMembership {+ role: Role;+ status: string;+ blockedAt: Date | null;+}++export interface SessionTeamContext {+ userId: string;+ teamId: string;+ membership: SessionTeamMembership;+ role: Role;+ permissions: Set<PermissionAction>;+ /** Dataroom ids the scoped member is assigned to (empty for non-scoped roles). */+ allowedDataroomIds: string[];+ /** The resolved dataroom id, when a `dataroomParam`/resolver was configured. */+ dataroomId?: string;+ team: { id: string; plan: string };+}++export interface WithSessionTeamOptions {+ /** Permission verbs the caller's role must hold. Required for scoped members to opt in. */+ requiredPermissions?: PermissionAction[];+ /** Restrict to an explicit set of roles (independent of permissions). */+ requiredRoles?: Role[];+ /** Predicate over the team plan string; return false to 403. */+ requiredPlan?: (plan: string) => boolean;+ /**+ * Name of the route param/query key holding the dataroom id. When set and the+ * caller is a scoped member, the room entitlement is enforced.+ */+ dataroomParam?: string;+ /**+ * Custom resolver for the dataroom id (e.g. read from the request body). Takes+ * precedence over `dataroomParam`. Return null/undefined to skip the room+ * entitlement check (the route is responsible for its own scoping in that case).+ */+ resolveDataroomId?: (args: {+ params: Record<string, string | string[] | undefined>;+ req: NextRequest | NextApiRequest;+ }) => Promise<string | null | undefined> | string | null | undefined;+}++type AuthError = { status: number; message: string };++function isAuthError(x: unknown): x is AuthError {+ return (+ typeof x === "object" &&+ x !== null &&+ "status" in x &&+ "message" in x &&+ typeof (x as AuthError).status === "number"+ );+}++function firstString(v: string | string[] | undefined): string | undefined {+ if (Array.isArray(v)) return v[0];+ return v ?? undefined;+}++/**+ * Shared core: given a resolved session + teamId + the request params/body+ * accessors, run every gate and either resolve a {@link SessionTeamContext} or+ * an {@link AuthError}.+ */+async function resolveSessionTeam({+ session,+ teamId,+ params,+ req,+ opts,+}: {+ session: { user?: unknown } | null;+ teamId: string | undefined;+ params: Record<string, string | string[] | undefined>;+ req: NextRequest | NextApiRequest;+ opts: WithSessionTeamOptions;+}): Promise<SessionTeamContext | AuthError> {+ if (!session || !session.user) {+ return { status: 401, message: "Unauthorized" };+ }+ if (!teamId) {+ return { status: 400, message: "Missing teamId" };+ }++ const userId = (session.user as CustomUser).id;++ const membership = await prisma.userTeam.findUnique({+ where: { userId_teamId: { userId, teamId } },+ select: {+ role: true,+ status: true,+ blockedAt: true,+ team: { select: { id: true, plan: true } },+ },+ });++ if (!membership) {+ return { status: 401, message: "Unauthorized" };+ }+ if (membership.status !== "ACTIVE" || membership.blockedAt) {+ return {+ status: 403,+ message: "Your access to this team is not active.",+ };+ }++ const role = membership.role;+ const permissions = getPermissionsByRole(role);++ // Role gate (independent of permissions).+ if (opts.requiredRoles && !opts.requiredRoles.includes(role)) {+ return {+ status: 403,+ message: "You are not permitted to perform this action.",+ };+ }++ // Permission gate.+ const required = opts.requiredPermissions ?? [];+ if (!required.every((p) => permissions.has(p))) {+ return {+ status: 403,+ message: "You do not have permission to perform this action.",+ };+ }++ // Default-deny for the scoped role: it must opt in via at least one declared+ // permission. A route with no `requiredPermissions` never admits a scoped+ // member, even if it forgot a more specific guard.+ const scoped = isDataroomScopedRole(role);+ if (scoped && required.length === 0) {+ return {+ status: 403,+ message: "You do not have permission to perform this action.",+ };+ }++ // Plan gate.+ if (opts.requiredPlan && !opts.requiredPlan(membership.team.plan)) {+ return {+ status: 403,+ message: "This feature requires a different plan.",+ };+ }++ // Per-room entitlement (only computed/enforced for the scoped role).+ let allowedDataroomIds: string[] = [];+ let dataroomId: string | undefined;++ if (scoped) {+ allowedDataroomIds = await getAllowedDataroomIds(userId, teamId);++ let resolved: string | null | undefined;+ if (opts.resolveDataroomId) {+ resolved = await opts.resolveDataroomId({ params, req });+ } else if (opts.dataroomParam) {+ resolved =+ firstString(params[opts.dataroomParam]) ??+ firstString(+ (req as NextApiRequest).query?.[opts.dataroomParam] as+ | string+ | string[]+ | undefined,+ );+ }++ if (resolved) {+ dataroomId = resolved;+ if (!canAccessDataroom(role, allowedDataroomIds, resolved)) {+ return {+ status: 403,+ message: "You do not have access to this data room.",+ };+ }+ }+ }++ return {+ userId,+ teamId,+ membership: {+ role: membership.role,+ status: membership.status,+ blockedAt: membership.blockedAt,+ },+ role,+ permissions,+ allowedDataroomIds,+ dataroomId,+ team: membership.team,+ };+}++/* ------------------------------------------------------------------ */+/* App Router variant */+/* ------------------------------------------------------------------ */++export interface AppRouterTeamContext extends SessionTeamContext {+ req: NextRequest;+ params: Record<string, string>;+}++export type AppRouterTeamHandler = (+ ctx: AppRouterTeamContext,+) => Promise<NextResponse> | NextResponse;++export function withTeam(+ handler: AppRouterTeamHandler,+ opts: WithSessionTeamOptions = {},+) {+ return async (+ req: NextRequest,+ context: {+ params: Promise<Record<string, string>> | Record<string, string>;+ },+ ): Promise<NextResponse> => {+ const params =+ context?.params && typeof (context.params as any).then === "function"+ ? await (context.params as Promise<Record<string, string>>)+ : ((context?.params as Record<string, string>) ?? {});++ const session = await getServerSession(authOptions);+ const result = await resolveSessionTeam({+ session,+ teamId: params.teamId,+ params,+ req,+ opts,+ });++ if (isAuthError(result)) {+ return NextResponse.json(+ { error: result.message },+ { status: result.status },+ );+ }++ return handler({ ...result, req, params });+ };+}++/* ------------------------------------------------------------------ */+/* Pages Router variant */+/* ------------------------------------------------------------------ */++export interface PagesRouterTeamContext extends SessionTeamContext {+ req: NextApiRequest;+ res: NextApiResponse;+}++export type PagesRouterTeamHandler = (+ ctx: PagesRouterTeamContext,+) => unknown | Promise<unknown>;++export function withTeamApi(+ handler: PagesRouterTeamHandler,+ opts: WithSessionTeamOptions = {},+) {+ return async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {+ const session = await getServerSession(req, res, authOptions);+ const teamId = firstString(req.query.teamId);++ const result = await resolveSessionTeam({+ session,+ teamId,+ params: req.query,+ req,+ opts,+ });++ if (isAuthError(result)) {+ res.status(result.status).json({ error: result.message });+ return;+ }++ await handler({ ...result, req, res });+ };+}diff --git a/lib/api/rbac/entitlements.ts b/lib/api/rbac/entitlements.tsnew file mode 100644index 00000000..00177a47--- /dev/null+++ b/lib/api/rbac/entitlements.ts@@ -0,0 +1,115 @@+import { Role } from "@prisma/client";++import prisma from "@/lib/prisma";++import { isDataroomScopedRole } from "./permissions";++/**+ * Dataroom-entitlement helpers ("which rooms"), complementing+ * {@link getPermissionsByRole} ("what verbs"). Only DATAROOM_MEMBER is scoped.+ */++/** Returns the dataroom ids a user is explicitly assigned to within a team. */+export async function getAllowedDataroomIds(+ userId: string,+ teamId: string,+): Promise<string[]> {+ const rows = await prisma.userDataroom.findMany({+ where: { userId, teamId },+ select: { dataroomId: true },+ });+ return rows.map((r) => r.dataroomId);+}++/** Whether `role` may access `dataroomId`. Scoped roles need it in `allowedIds`. */+export function canAccessDataroom(+ role: Role | string,+ allowedIds: string[],+ dataroomId: string,+): boolean {+ if (!isDataroomScopedRole(role)) return true;+ return allowedIds.includes(dataroomId);+}++/**+ * Whether `role` may perform room-manager actions on `dataroomId`: upload+ * (documents.write), links (links.read/write), and folders (datarooms.write).+ * NOTE: destructive ops (delete/freeze) stay ADMIN/MANAGER-only via `requiredRoles`.+ */+export function canManageDataroom(+ role: Role | string,+ allowedIds: string[],+ dataroomId: string,+): boolean {+ return canAccessDataroom(role, allowedIds, dataroomId);+}++/** Scoped roles may access a document only if it lives in an assigned dataroom. */+export async function assertDocumentAccess({+ role,+ userId,+ teamId,+ documentId,+ allowedIds,+}: {+ role: Role | string;+ userId: string;+ teamId: string;+ documentId: string;+ allowedIds?: string[];+}): Promise<boolean> {+ if (!isDataroomScopedRole(role)) return true;++ const ids = allowedIds ?? (await getAllowedDataroomIds(userId, teamId));+ if (ids.length === 0) return false;++ const match = await prisma.dataroomDocument.findFirst({+ where: {+ documentId,+ dataroomId: { in: ids },+ },+ select: { id: true },+ });+ return !!match;+}++/** Scoped roles may access a link only if it resolves to an assigned dataroom. */+export async function assertLinkAccess({+ role,+ userId,+ teamId,+ linkId,+ allowedIds,+}: {+ role: Role | string;+ userId: string;+ teamId: string;+ linkId: string;+ allowedIds?: string[];+}): Promise<boolean> {+ if (!isDataroomScopedRole(role)) return true;++ const ids = allowedIds ?? (await getAllowedDataroomIds(userId, teamId));+ if (ids.length === 0) return false;++ const link = await prisma.link.findUnique({+ where: { id: linkId },+ select: { dataroomId: true, documentId: true, teamId: true },+ });+ if (!link || link.teamId !== teamId) return false;++ if (link.dataroomId) {+ return ids.includes(link.dataroomId);+ }+ if (link.documentId) {+ return assertDocumentAccess({+ role,+ userId,+ teamId,+ documentId: link.documentId,+ allowedIds: ids,+ });+ }+ // Links with neither dataroom nor document are denied for scoped roles.+ return false;+}diff --git a/lib/api/rbac/guard.ts b/lib/api/rbac/guard.tsnew file mode 100644index 00000000..68ead8a3--- /dev/null+++ b/lib/api/rbac/guard.ts@@ -0,0 +1,167 @@+import { NextApiResponse } from "next";++import prisma from "@/lib/prisma";++import {+ assertDocumentAccess,+ assertLinkAccess,+ canAccessDataroom,+} from "./entitlements";+import { isDataroomScopedRole } from "./permissions";++/**+ * Lightweight inline guard for team routes that have NOT yet been migrated to+ * the `withTeam` session wrapper. It enforces two invariants for the+ * dataroom-scoped role on top of a route's existing membership check:+ *+ * 1. If `dataroomId` is provided, a scoped member must be assigned to that+ * room (closes cross-room IDOR for assigned-vs-unassigned rooms).+ * 2. If `dataroomId` is NOT provided (a team-level route), a scoped member is+ * denied outright (default-deny — these routes are not part of the scoped+ * surface).+ *+ * Returns `true` if the request was denied (and a response was sent); the+ * caller should `return` immediately. Returns `false` when access is allowed.+ *+ * Non-scoped roles (ADMIN/MANAGER/MEMBER) are never affected by this guard.+ */+export async function enforceDataroomMemberScope({+ userId,+ teamId,+ dataroomId,+ res,+ role,+}: {+ userId: string;+ teamId: string;+ dataroomId?: string | null;+ res: NextApiResponse;+ /** Optional pre-loaded role to avoid an extra query. */+ role?: string;+}): Promise<boolean> {+ let resolvedRole = role;+ if (resolvedRole === undefined) {+ const membership = await prisma.userTeam.findUnique({+ where: { userId_teamId: { userId, teamId } },+ select: { role: true },+ });+ resolvedRole = membership?.role;+ }++ if (!resolvedRole || !isDataroomScopedRole(resolvedRole)) {+ return false;+ }++ if (!dataroomId) {+ res+ .status(403)+ .json({ error: "You do not have permission to perform this action." });+ return true;+ }++ const allowed = await prisma.userDataroom.findUnique({+ where: { userId_dataroomId: { userId, dataroomId } },+ select: { dataroomId: true },+ });++ if (!canAccessDataroom(resolvedRole, allowed ? [dataroomId] : [], dataroomId)) {+ res+ .status(403)+ .json({ error: "You do not have access to this data room." });+ return true;+ }++ return false;+}++/**+ * Inline link guard. Denies a scoped member that tries to act on a link which+ * resolves to a dataroom/document outside their assigned rooms. Returns `true`+ * (and sends a 403) when denied. Non-scoped roles always pass.+ */+export async function enforceLinkMemberScope({+ userId,+ teamId,+ linkId,+ res,+ role,+}: {+ userId: string;+ teamId: string;+ linkId: string;+ res: NextApiResponse;+ role?: string;+}): Promise<boolean> {+ let resolvedRole = role;+ if (resolvedRole === undefined) {+ const membership = await prisma.userTeam.findUnique({+ where: { userId_teamId: { userId, teamId } },+ select: { role: true },+ });+ resolvedRole = membership?.role;+ }++ if (!resolvedRole || !isDataroomScopedRole(resolvedRole)) {+ return false;+ }++ const allowed = await assertLinkAccess({+ role: resolvedRole,+ userId,+ teamId,+ linkId,+ });++ if (!allowed) {+ res.status(403).json({ error: "You do not have access to this link." });+ return true;+ }++ return false;+}++/**+ * Inline document guard. Denies a scoped member that tries to act on a document+ * which does not live in any of their assigned rooms. Returns `true` (and sends+ * a 403) when denied. Non-scoped roles always pass.+ */+export async function enforceDocumentMemberScope({+ userId,+ teamId,+ documentId,+ res,+ role,+}: {+ userId: string;+ teamId: string;+ documentId: string;+ res: NextApiResponse;+ role?: string;+}): Promise<boolean> {+ let resolvedRole = role;+ if (resolvedRole === undefined) {+ const membership = await prisma.userTeam.findUnique({+ where: { userId_teamId: { userId, teamId } },+ select: { role: true },+ });+ resolvedRole = membership?.role;+ }++ if (!resolvedRole || !isDataroomScopedRole(resolvedRole)) {+ return false;+ }++ const allowed = await assertDocumentAccess({+ role: resolvedRole,+ userId,+ teamId,+ documentId,+ });++ if (!allowed) {+ res.status(403).json({ error: "You do not have access to this document." });+ return true;+ }++ return false;+}diff --git a/lib/api/rbac/index.ts b/lib/api/rbac/index.tsnew file mode 100644index 00000000..58af18f5--- /dev/null+++ b/lib/api/rbac/index.ts@@ -0,0 +1,18 @@+export type { PermissionAction } from "./permissions";+export {+ getPermissionsByRole,+ hasAllPermissions,+ isDataroomScopedRole,+} from "./permissions";+export {+ getAllowedDataroomIds,+ canAccessDataroom,+ canManageDataroom,+ assertDocumentAccess,+ assertLinkAccess,+} from "./entitlements";+export {+ enforceDataroomMemberScope,+ enforceLinkMemberScope,+ enforceDocumentMemberScope,+} from "./guard";diff --git a/lib/api/rbac/permissions.ts b/lib/api/rbac/permissions.tsnew file mode 100644index 00000000..25002778--- /dev/null+++ b/lib/api/rbac/permissions.ts@@ -0,0 +1,119 @@+import { Role } from "@prisma/client";++/**+ * Granular permission verbs used by the session `withTeam` wrapper. A role maps+ * to a set of these via {@link getPermissionsByRole}; routes declare the verb(s)+ * they require. This is the "what verbs" layer (the "which rooms" layer is the+ * UserDataroom entitlement check, which a role alone cannot encode).+ */+export type PermissionAction =+ | "datarooms.read"+ | "datarooms.write"+ // Read access to the team-wide "All Documents" list/search.+ | "documents.read"+ // Create/upload documents and attach them to datarooms.+ | "documents.write"+ | "links.read"+ | "links.write"+ // Read analytics scoped to an individual dataroom/document.+ | "analytics.read"+ // Read team-wide analytics (the global dashboard).+ | "analytics.team"+ | "team.read"+ | "team.write"+ // Manage members (invite/remove/change role).+ | "members.write"+ | "tokens.write"+ | "webhooks.write"+ | "domains.write"+ | "branding.write"+ // SAML / SSO configuration (admin only).+ | "sso.write";++const ALL_PERMISSIONS: PermissionAction[] = [+ "datarooms.read",+ "datarooms.write",+ "documents.read",+ "documents.write",+ "links.read",+ "links.write",+ "analytics.read",+ "analytics.team",+ "team.read",+ "team.write",+ "members.write",+ "tokens.write",+ "webhooks.write",+ "domains.write",+ "branding.write",+ "sso.write",+];++// MANAGER gets everything except the admin-only structural operations.+const MANAGER_DENIED: PermissionAction[] = ["members.write", "sso.write"];++// MEMBER keeps today's broad behaviour: team read/write minus the+// admin/manager-only structural operations.+const MEMBER_DENIED: PermissionAction[] = [+ "members.write",+ "tokens.write",+ "webhooks.write",+ "domains.write",+ "sso.write",+];++// The minimal verb set a DATAROOM_MEMBER holds. Notably this excludes+// `documents.read` (the team-wide All Documents list), `analytics.team`, and+// every `team.*`/`members.write` verb. The per-room entitlement check (see+// `lib/api/rbac/entitlements.ts`) further restricts which datarooms these+// verbs apply to.+const DATAROOM_MEMBER_PERMISSIONS: PermissionAction[] = [+ "datarooms.read",+ "datarooms.write",+ "documents.write",+ "links.read",+ "links.write",+ "analytics.read",+];++/**+ * Returns the set of permission verbs granted to a role. The set is the single+ * source of truth for "what verbs" a role can perform, mirroring Dub's+ * `getPermissionsByRole`.+ */+export function getPermissionsByRole(+ role: Role | string,+): Set<PermissionAction> {+ switch (role) {+ case "ADMIN":+ return new Set(ALL_PERMISSIONS);+ case "MANAGER":+ return new Set(+ ALL_PERMISSIONS.filter((p) => !MANAGER_DENIED.includes(p)),+ );+ case "MEMBER":+ return new Set(ALL_PERMISSIONS.filter((p) => !MEMBER_DENIED.includes(p)));+ case "DATAROOM_MEMBER":+ return new Set(DATAROOM_MEMBER_PERMISSIONS);+ default:+ // Unknown / future roles are denied everything by default.+ return new Set<PermissionAction>();+ }+}++/**+ * True when `role` holds every required permission verb.+ */+export function hasAllPermissions(+ role: Role | string,+ required: PermissionAction[],+): boolean {+ if (required.length === 0) return true;+ const granted = getPermissionsByRole(role);+ return required.every((p) => granted.has(p));+}++/** True for the dataroom-scoped role, which needs per-room entitlement checks. */+export function isDataroomScopedRole(role: Role | string): boolean {+ return role === "DATAROOM_MEMBER";+}diff --git a/lib/hooks/use-self-membership.ts b/lib/hooks/use-self-membership.tsnew file mode 100644index 00000000..e9f891f1--- /dev/null+++ b/lib/hooks/use-self-membership.ts@@ -0,0 +1,46 @@+import { useMemo } from "react";++import { useSession } from "next-auth/react";++import { useGetTeam } from "@/lib/swr/use-team";+import { CustomUser, TeamRole } from "@/lib/types";++export interface SelfMembership {+ role: TeamRole | null;+ isDataroomMember: boolean;+ allowedDataroomIds: string[];+ loading: boolean;+}++/**+ * Returns the current user's membership scope within the active team:+ * their role, whether they are a dataroom-scoped member, and the dataroom ids+ * they are assigned to. Mirrors `useIsAdmin()` and reuses the SWR-cached team.+ */+export function useSelfMembership(): SelfMembership {+ const { data: session, status } = useSession();+ const { team, loading: teamLoading } = useGetTeam();++ const sessionLoading = status === "loading";+ const loading = teamLoading || sessionLoading;++ const userId = (session?.user as CustomUser)?.id;++ return useMemo(() => {+ const membership = team?.users?.find((u) => u.userId === userId);+ const role = (membership?.role as TeamRole | undefined) ?? null;+ const isDataroomMember = role === "DATAROOM_MEMBER";+ const allowedDataroomIds = isDataroomMember+ ? (team?.userDatarooms ?? [])+ .filter((ud) => ud.userId === userId)+ .map((ud) => ud.dataroomId)+ : [];++ return {+ role,+ isDataroomMember: !loading && isDataroomMember,+ allowedDataroomIds,+ loading,+ };+ }, [team, userId, loading]);+}diff --git a/lib/swr/use-dataroom-document.ts b/lib/swr/use-dataroom-document.tsnew file mode 100644index 00000000..cac251a5--- /dev/null+++ b/lib/swr/use-dataroom-document.ts@@ -0,0 +1,98 @@+import { useRouter } from "next/router";++import { useTeam } from "@/context/team-context";+import useSWR from "swr";++import { DocumentWithVersion } from "@/lib/types";+import { fetcher } from "@/lib/utils";++interface DataroomDocumentOverview {+ dataroomDocumentId: string;+ documentId: string;+ dataroom: { id: string; name: string };+ dataroomFolder: { id: string; name: string; path: string } | null;+ document: DocumentWithVersion & {+ hasPageLinks: boolean;+ isEmpty: boolean;+ primaryVersion: any;+ };+ limits: {+ canAddLinks: boolean;+ canAddDocuments: boolean;+ canAddUsers: boolean;+ };+ featureFlags: {+ annotations: boolean;+ };+ team: {+ plan: string;+ isTrial: boolean;+ };+ counts: {+ links: number;+ views: number;+ /**+ * Number of direct document-link visits (no data room). Only populated for+ * full team members; always 0 for dataroom-scoped members.+ */+ otherViewCount: number;+ };+}++/**+ * Loads a single document's overview from within a data room, addressed by the+ * DataroomDocument id. Uses the dataroom-scoped endpoint so dataroom-scoped+ * members can read it. Resolves to the underlying Document id, which the page+ * threads into the existing (scope-guarded) document endpoints.+ */+export function useDataroomDocumentOverview() {+ const router = useRouter();+ const teamInfo = useTeam();++ const { id: dataroomId, documentId: dataroomDocumentId } =+ router.query as {+ id: string;+ documentId: string;+ };++ const teamId = teamInfo?.currentTeam?.id;++ const { data, error, mutate } = useSWR<DataroomDocumentOverview>(+ teamId &&+ dataroomId &&+ dataroomDocumentId &&+ `/api/teams/${teamId}/datarooms/${dataroomId}/documents/${encodeURIComponent(+ dataroomDocumentId,+ )}/overview`,+ fetcher,+ {+ dedupingInterval: 30000,+ revalidateOnFocus: false,+ revalidateOnReconnect: false,+ revalidateIfStale: false,+ refreshInterval: 0,+ onError: (err) => {+ if (err.status === 404) {+ router.replace(`/datarooms/${dataroomId}/documents`);+ }+ },+ },+ );++ return {+ data,+ documentId: data?.documentId,+ dataroomDocumentId: data?.dataroomDocumentId,+ dataroom: data?.dataroom,+ document: data?.document,+ primaryVersion: data?.document?.primaryVersion,+ limits: data?.limits,+ featureFlags: data?.featureFlags,+ team: data?.team,+ counts: data?.counts,+ isEmpty: data?.document?.isEmpty || false,+ loading: !error && !data,+ error,+ mutate,+ };+}diff --git a/lib/swr/use-document.ts b/lib/swr/use-document.tsindex 7e5d8b92..fb98faa4 100644--- a/lib/swr/use-document.ts+++ b/lib/swr/use-document.ts@@ -54,14 +54,18 @@ export function useDocument() {};}-export function useDocumentLinks() {+export function useDocumentLinks(documentId?: string) {const router = useRouter();const teamInfo = useTeam();- const { id } = router.query as {+ const { id: routerId } = router.query as {id: string;};+ // Allow an explicit documentId (e.g. the dataroom-scoped document page where+ // router.query.id is the dataroom id, not the document id).+ const id = documentId ?? routerId;+const {data: links,error,@@ -126,18 +130,49 @@ type TStatsData = {hiddenFromPause: number;};-export function useDocumentVisits(page: number, limit: number) {+export function useDocumentVisits(+ page: number,+ limit: number,+ documentId?: string,+ options?: {+ /**+ * Scope the visits to a single data room. Required for the `scope` filter+ * to take effect (the dataroom-scoped document page passes this).+ */+ dataroomId?: string;+ /**+ * `dataroom` → only this room's visits; `other` → only the document's+ * direct-link visits (no data room). Only applies when `dataroomId` is set.+ */+ scope?: "dataroom" | "other";+ },+) {const router = useRouter();const teamInfo = useTeam();const teamId = teamInfo?.currentTeam?.id;- const { id } = router.query as {+ const { id: routerId } = router.query as {id: string;};+ // Allow an explicit documentId (e.g. the dataroom-scoped document page where+ // router.query.id is the dataroom id, not the document id).+ const id = documentId ?? routerId;++ const { dataroomId, scope } = options ?? {};++ const query = new URLSearchParams({+ page: String(page),+ limit: String(limit),+ });+ if (dataroomId) {+ query.set("dataroomId", dataroomId);+ if (scope) query.set("scope", scope);+ }+const cacheKey =teamId && id- ? `/api/teams/${teamId}/documents/${id}/views?page=${page}&limit=${limit}`+ ? `/api/teams/${teamId}/documents/${id}/views?${query.toString()}`: null;const {diff --git a/lib/swr/use-stats.ts b/lib/swr/use-stats.tsindex 2aacb205..921a19a5 100644--- a/lib/swr/use-stats.ts+++ b/lib/swr/use-stats.ts@@ -19,20 +19,39 @@ export type TStatsData = {export function useStats({excludeTeamMembers,-}: { excludeTeamMembers?: boolean } = {}) {+ documentId,+ dataroomId,+}: {+ excludeTeamMembers?: boolean;+ documentId?: string;+ /**+ * When provided, stats are scoped to this data room's visits only (e.g. the+ * dataroom-scoped document page), excluding the document's direct-link visits.+ */+ dataroomId?: string;+} = {}) {// this gets the data for a document's graph of all viewsconst router = useRouter();const teamInfo = useTeam();const teamId = teamInfo?.currentTeam?.id;- const { id } = router.query as {+ const { id: routerId } = router.query as {id: string;};+ // Allow an explicit documentId (e.g. the dataroom-scoped document page where+ // router.query.id is the dataroom id, not the document id).+ const id = documentId ?? routerId;++ const query = new URLSearchParams();+ if (excludeTeamMembers) query.set("excludeTeamMembers", "true");+ if (dataroomId) query.set("dataroomId", dataroomId);+ const queryString = query.toString();+const { data: stats, error } = useSWR<TStatsData>(id &&teamId &&- `/api/teams/${teamId}/documents/${encodeURIComponent(id)}/stats${excludeTeamMembers ? "?excludeTeamMembers=true" : ""}`,+ `/api/teams/${teamId}/documents/${encodeURIComponent(id)}/stats${queryString ? `?${queryString}` : ""}`,fetcher,{dedupingInterval: 10000,@@ -53,15 +72,19 @@ interface StatsViewData {};}-export function useVisitorStats(viewId: string) {+export function useVisitorStats(viewId: string, documentIdOverride?: string) {// this gets the data for a single visitor's graphconst router = useRouter();const teamInfo = useTeam();- const { id: documentId } = router.query as {+ const { id: routerId } = router.query as {id: string;};+ // Allow an explicit documentId (e.g. the dataroom-scoped document page where+ // router.query.id is the dataroom id, not the document id).+ const documentId = documentIdOverride ?? routerId;+const { data: stats, error } = useSWR<StatsViewData>(documentId &&viewId &&@@ -81,14 +104,21 @@ export function useVisitorStats(viewId: string) {};}-export function useVisitorUserAgent(viewId: string) {+export function useVisitorUserAgent(+ viewId: string,+ documentIdOverride?: string,+) {const router = useRouter();const teamInfo = useTeam();- const { id: documentId } = router.query as {+ const { id: routerId } = router.query as {id: string;};+ // Allow an explicit documentId (e.g. the dataroom-scoped document page where+ // router.query.id is the dataroom id, not the document id).+ const documentId = documentIdOverride ?? routerId;+const { data: userAgent, error } = useSWRImmutable<{country: string;city: string;diff --git a/lib/types.ts b/lib/types.tsindex c4f21ad3..7f564647 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -312,11 +312,13 @@ export interface Team {replicateDataroomFolders?: boolean;}+export type TeamRole = "ADMIN" | "MANAGER" | "MEMBER" | "DATAROOM_MEMBER";+export interface TeamDetail {id: string;name: string;users: {- role: "ADMIN" | "MANAGER" | "MEMBER";+ role: TeamRole;status: "ACTIVE" | "BLOCKED_TRIAL_EXPIRED";teamId: string;userId: string;@@ -331,6 +333,11 @@ export interface TeamDetail {id: string;};}[];+ // Per-member dataroom assignments (scoped DATAROOM_MEMBER role).+ userDatarooms?: {+ userId: string;+ dataroomId: string;+ }[];}export const WatermarkConfigSchema = z.object({diff --git a/pages/api/analytics/index.ts b/pages/api/analytics/index.tsindex c3eb9f58..4cfc41cf 100644--- a/pages/api/analytics/index.ts+++ b/pages/api/analytics/index.ts@@ -4,6 +4,7 @@ import { addDays } from "date-fns";import { getServerSession } from "next-auth";import { z } from "zod";+import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";import prisma from "@/lib/prisma";import {getTotalDocumentDuration,@@ -81,6 +82,14 @@ export default async function handler(return res.status(401).json({ error: "Unauthorized" });}+ // Team-wide analytics is not part of the dataroom-scoped surface.+ const denied = await enforceDataroomMemberScope({+ userId: (session.user as CustomUser).id,+ teamId,+ res,+ });+ if (denied) return;+// Get pause date filter if team is pausedconst pauseStartsAt = team.pauseStartsAt;// Get team timezone for analytics display (defaults to UTC)diff --git a/pages/api/links/[id]/index.ts b/pages/api/links/[id]/index.tsindex ae0c34cd..3bee5cbc 100644--- a/pages/api/links/[id]/index.ts+++ b/pages/api/links/[id]/index.ts@@ -8,6 +8,7 @@ import {fetchDataroomLinkData,fetchDocumentLinkData,} from "@/lib/api/links/link-data";+import { enforceLinkMemberScope } from "@/lib/api/rbac/guard";import prisma from "@/lib/prisma";import { CustomUser, WatermarkConfigSchema } from "@/lib/types";import {@@ -261,6 +262,15 @@ export default async function handle(.json({ error: "Link not found or unauthorized" });}+ // Dataroom-scoped members may only modify links within their rooms.+ const editDenied = await enforceLinkMemberScope({+ userId,+ teamId,+ linkId: existingLink.id,+ res,+ });+ if (editDenied) return;+if (existingLink.dataroom?.isFrozen) {return res.status(403).json({error:@@ -816,6 +826,17 @@ export default async function handle(return res.status(401).end("Unauthorized to delete this link");}+ // Dataroom-scoped members may only delete links within their rooms.+ if (linkToBeDeleted.teamId) {+ const deleteDenied = await enforceLinkMemberScope({+ userId,+ teamId: linkToBeDeleted.teamId,+ linkId: linkToBeDeleted.id,+ res,+ });+ if (deleteDenied) return;+ }+// Generate a random suffix for the deleted slug to free up the original slugconst generateDeletedSuffix = customAlphabet("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",diff --git a/pages/api/links/index.ts b/pages/api/links/index.tsindex 7a73a49b..50a31656 100644--- a/pages/api/links/index.ts+++ b/pages/api/links/index.ts@@ -5,6 +5,12 @@ import { LinkAudienceType, Tag } from "@prisma/client";import { waitUntil } from "@vercel/functions";import { getServerSession } from "next-auth/next";+import {+ assertDocumentAccess,+ canAccessDataroom,+ getAllowedDataroomIds,+} from "@/lib/api/rbac/entitlements";+import { isDataroomScopedRole } from "@/lib/api/rbac/permissions";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import { CustomUser, WatermarkConfigSchema } from "@/lib/types";@@ -86,13 +92,39 @@ export default async function handler(teamId,},},- select: { teamId: true },+ select: { teamId: true, role: true },});if (!teamAccess) {return res.status(401).json({ error: "Unauthorized." });}+ // Dataroom-scoped members may only create links for documents/datarooms+ // within their assigned rooms.+ if (isDataroomScopedRole(teamAccess.role)) {+ const allowedIds = await getAllowedDataroomIds(userId, teamId);+ if (dataroomLink) {+ if (!canAccessDataroom(teamAccess.role, allowedIds, targetId)) {+ return res+ .status(403)+ .json({ error: "You do not have access to this data room." });+ }+ } else if (documentLink) {+ const hasAccess = await assertDocumentAccess({+ role: teamAccess.role,+ userId,+ teamId,+ documentId: targetId,+ allowedIds,+ });+ if (!hasAccess) {+ return res+ .status(403)+ .json({ error: "You do not have access to this document." });+ }+ }+ }+// Check if team is pausedconst teamIsPaused = await isTeamPausedById(teamId);if (teamIsPaused) {diff --git a/pages/api/teams/[teamId]/billing/invoices.ts b/pages/api/teams/[teamId]/billing/invoices.tsindex 0f4601a5..51a63724 100644--- a/pages/api/teams/[teamId]/billing/invoices.ts+++ b/pages/api/teams/[teamId]/billing/invoices.ts@@ -4,6 +4,7 @@ import { stripeInstance } from "@/ee/stripe";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { getServerSession } from "next-auth/next";+import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";@@ -28,6 +29,11 @@ export default async function handle(const userId = (session.user as CustomUser).id;const { teamId } = req.query as { teamId: string };+ // Billing is a team-level action: dataroom-scoped members cannot view invoices.+ if (await enforceDataroomMemberScope({ userId, teamId, res })) {+ return;+ }+try {// Get team with stripeIdconst team = await prisma.team.findUnique({diff --git a/pages/api/teams/[teamId]/billing/manage.ts b/pages/api/teams/[teamId]/billing/manage.tsindex de627a45..19a57b48 100644--- a/pages/api/teams/[teamId]/billing/manage.ts+++ b/pages/api/teams/[teamId]/billing/manage.ts@@ -9,6 +9,7 @@ import { waitUntil } from "@vercel/functions";import { getServerSession } from "next-auth/next";import { identifyUser, trackAnalytics } from "@/lib/analytics";+import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";@@ -36,6 +37,13 @@ export default async function handle(const userEmail = (session.user as CustomUser).email;const { teamId } = req.query as { teamId: string };++ // Billing management is a team-level action: dataroom-scoped members are+ // denied (they cannot upgrade plans or otherwise manage billing).+ if (await enforceDataroomMemberScope({ userId, teamId, res })) {+ return;+ }+const {priceId,upgradePlan,diff --git a/pages/api/teams/[teamId]/billing/upgrade.ts b/pages/api/teams/[teamId]/billing/upgrade.tsindex 2983d808..9355b94e 100644--- a/pages/api/teams/[teamId]/billing/upgrade.ts+++ b/pages/api/teams/[teamId]/billing/upgrade.ts@@ -8,6 +8,7 @@ import { waitUntil } from "@vercel/functions";import { getServerSession } from "next-auth/next";import { identifyUser, trackAnalytics } from "@/lib/analytics";+import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";import { getDubDiscountForExternalUserId } from "@/lib/dub";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";@@ -54,6 +55,11 @@ export default async function handle(const { id: userId, email: userEmail } = session.user as CustomUser;+ // Billing is a team-level action: dataroom-scoped members cannot upgrade.+ if (await enforceDataroomMemberScope({ userId, teamId, res })) {+ return;+ }+const team = await prisma.team.findUnique({where: {id: teamId,diff --git a/pages/api/teams/[teamId]/change-role.ts b/pages/api/teams/[teamId]/change-role.tsindex a2fce9b1..7d1f81e8 100644--- a/pages/api/teams/[teamId]/change-role.ts+++ b/pages/api/teams/[teamId]/change-role.ts@@ -22,9 +22,14 @@ export default async function handle(const { teamId } = req.query as { teamId: string };const userId = (session.user as CustomUser).id;- const { userToBeChanged, role } = req.body as {+ const {+ userToBeChanged,+ role,+ dataroomIds: rawDataroomIds,+ } = req.body as {userToBeChanged: string;- role: "MEMBER" | "MANAGER" | "ADMIN";+ role: "MEMBER" | "MANAGER" | "ADMIN" | "DATAROOM_MEMBER";+ dataroomIds?: string[];};try {@@ -46,21 +51,79 @@ export default async function handle(return res.status(403).json("Only admins can change user roles");}+ // Managing the dataroom-scoped role (and its room assignments) is an+ // ADMIN/MANAGER-only operation.+ if (+ role === "DATAROOM_MEMBER" &&+ userTeam.role !== "ADMIN" &&+ userTeam.role !== "MANAGER"+ ) {+ return res+ .status(403)+ .json("Only admins and managers can manage data room members");+ }+if (userTeam?.role === "ADMIN" && userTeam.userId === userToBeChanged) {return res.status(401).json("You can't change the Admin");}- await prisma.userTeam.update({- where: {- userId_teamId: {- userId: userToBeChanged,- teamId,+ const dataroomIds =+ role === "DATAROOM_MEMBER" && Array.isArray(rawDataroomIds)+ ? Array.from(+ new Set(rawDataroomIds.filter((id) => typeof id === "string")),+ )+ : [];++ if (role === "DATAROOM_MEMBER" && dataroomIds.length === 0) {+ return res+ .status(400)+ .json("Select at least one data room for a data room member.");+ }++ if (dataroomIds.length > 0) {+ const validDatarooms = await prisma.dataroom.findMany({+ where: { id: { in: dataroomIds }, teamId },+ select: { id: true },+ });+ if (validDatarooms.length !== dataroomIds.length) {+ return res.status(400).json("One or more data rooms are invalid.");+ }+ }++ await prisma.$transaction(async (tx) => {+ await tx.userTeam.update({+ where: {+ userId_teamId: {+ userId: userToBeChanged,+ teamId,+ },},- },- data: {- role,- },+ data: {+ role,+ },+ });++ if (role === "DATAROOM_MEMBER") {+ // Replace the member's room assignments with the provided set.+ await tx.userDataroom.deleteMany({+ where: { userId: userToBeChanged, teamId },+ });+ await tx.userDataroom.createMany({+ data: dataroomIds.map((dataroomId) => ({+ userId: userToBeChanged,+ teamId,+ dataroomId,+ })),+ skipDuplicates: true,+ });+ } else {+ // Promoting away from the scoped role clears any assignments.+ await tx.userDataroom.deleteMany({+ where: { userId: userToBeChanged, teamId },+ });+ }});+return res.status(204).end();} catch (error) {errorhandler(error, res);diff --git a/pages/api/teams/[teamId]/datarooms/[id]/branding.ts b/pages/api/teams/[teamId]/datarooms/[id]/branding.tsindex cf328f9b..62ad6176 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/branding.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/branding.ts@@ -14,6 +14,7 @@ import {type DataroomViewerLayoutPreset,} from "@/ee/features/branding/lib/dataroom-viewer-layout";import { validateRedirectUrl } from "@/lib/api/domains/validate-redirect-url";+import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";import {teamPlanAllowsCustomWelcomeAndCta,teamPlanAllowsLayoutCustomization,@@ -108,6 +109,18 @@ export default async function handle(id: string;};+ // Scoped members may only manage branding for their assigned rooms.+ if (+ await enforceDataroomMemberScope({+ userId: (session.user as CustomUser).id,+ teamId,+ dataroomId,+ res,+ })+ ) {+ return;+ }+try {const team = await prisma.team.findUnique({where: {diff --git a/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/index.tsindex 385f013b..e5348566 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/index.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/index.ts@@ -3,6 +3,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { getServerSession } from "next-auth/next";+import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";@@ -27,6 +28,13 @@ export default async function handle(currentPathName: string;};+ // Scoped members may only manage documents within their assigned rooms.+ if (+ await enforceDataroomMemberScope({ userId, teamId, dataroomId, res })+ ) {+ return;+ }+try {// Check if the user is part of the teamconst team = await prisma.team.findUnique({@@ -85,6 +93,13 @@ export default async function handle(documentId,} = req.query as { teamId: string; id: string; documentId: string };+ // Scoped members may only manage documents within their assigned rooms.+ if (+ await enforceDataroomMemberScope({ userId, teamId, dataroomId, res })+ ) {+ return;+ }+try {const teamAccess = await prisma.userTeam.findUnique({where: {diff --git a/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/overview.ts b/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/overview.tsnew file mode 100644index 00000000..dd986f3a--- /dev/null+++ b/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/overview.ts@@ -0,0 +1,263 @@+import { NextApiRequest, NextApiResponse } from "next";++import { getLimits } from "@/ee/limits/server";+import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { Prisma } from "@prisma/client";+import { getServerSession } from "next-auth/next";++import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";+import { isDataroomScopedRole } from "@/lib/api/rbac/permissions";+import { getFeatureFlags } from "@/lib/featureFlags";+import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";+import { serializeFileSize } from "@/lib/utils";++/**+ * Dataroom-scoped document overview.+ *+ * Mirrors `/documents/:id/overview` but is addressed by the DataroomDocument id+ * and gated by `enforceDataroomMemberScope`, so a dataroom-scoped member can+ * load a document's analytics from inside a room they are assigned to without+ * being granted access to the team-wide `/documents/:id` surface.+ *+ * `documentId` in the route is the DataroomDocument id; the resolved underlying+ * Document id is returned as `documentId` so the client can drive the existing+ * (already scope-guarded) document endpoints for links/stats/views.+ */+export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method !== "GET") {+ res.setHeader("Allow", ["GET"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }++ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const {+ teamId,+ id: dataroomId,+ documentId: dataroomDocumentId,+ } = req.query as {+ teamId: string;+ id: string;+ documentId: string;+ };++ const userId = (session.user as CustomUser).id;++ const membership = await prisma.userTeam.findUnique({+ where: { userId_teamId: { userId, teamId } },+ select: { role: true },+ });++ // Scoped members may only read documents within their assigned rooms.+ if (+ await enforceDataroomMemberScope({+ userId,+ teamId,+ dataroomId,+ res,+ role: membership?.role,+ })+ ) {+ return;+ }++ const isScopedMember = isDataroomScopedRole(membership?.role ?? "");++ try {+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ users: {+ some: {+ userId,+ },+ },+ },+ select: { plan: true },+ });++ if (!team) {+ return res.status(401).end("Unauthorized");+ }++ // Resolve the DataroomDocument → underlying Document, ensuring the document+ // actually lives in this room (closes cross-room access).+ const dataroomDocument = await prisma.dataroomDocument.findUnique({+ where: {+ id: dataroomDocumentId,+ dataroomId,+ },+ select: {+ id: true,+ dataroomId: true,+ folder: {+ select: {+ id: true,+ name: true,+ path: true,+ },+ },+ dataroom: {+ select: {+ id: true,+ name: true,+ },+ },+ document: {+ select: {+ id: true,+ name: true,+ description: true,+ file: true,+ originalFile: true,+ type: true,+ contentType: true,+ storageType: true,+ numPages: true,+ ownerId: true,+ teamId: true,+ agentsEnabled: true,+ advancedExcelEnabled: true,+ downloadOnly: true,+ createdAt: true,+ updatedAt: true,+ folderId: true,+ isExternalUpload: true,+ versions: {+ where: { isPrimary: true },+ orderBy: { createdAt: "desc" },+ take: 1,+ },+ folder: {+ select: {+ name: true,+ path: true,+ },+ },+ datarooms: {+ select: {+ dataroom: {+ select: {+ id: true,+ name: true,+ },+ },+ folder: {+ select: {+ id: true,+ name: true,+ path: true,+ },+ },+ },+ },+ _count: {+ select: {+ links: true,+ views: { where: { isArchived: false } },+ },+ },+ },+ },+ },+ });++ if (+ !dataroomDocument ||+ dataroomDocument.document.teamId !== teamId ||+ !dataroomDocument.document.versions ||+ dataroomDocument.document.versions.length === 0+ ) {+ return res.status(404).json({+ error: "Not Found",+ message: "The requested document does not exist in this data room",+ });+ }++ const document = dataroomDocument.document;++ const [limits, featureFlags] = await Promise.all([+ getLimits({ teamId, userId }),+ getFeatureFlags({ teamId }),+ ]);++ const primaryVersion = document.versions[0];+ const hasLinks = document._count.links > 0;+ const hasViews = document._count.views > 0;++ // Direct document-link visits (no data room). Surfaced as a small count so+ // full team members know the document has activity outside this room. Never+ // exposed to dataroom-scoped members.+ const otherViewCount = isScopedMember+ ? 0+ : await prisma.view.count({+ where: {+ documentId: document.id,+ dataroomId: null,+ isArchived: false,+ },+ });++ let hasPageLinks = false;+ if (primaryVersion && team.plan.includes("free")) {+ const pageLinksCount = await prisma.documentPage.count({+ where: {+ versionId: primaryVersion.id,+ pageLinks: {+ not: Prisma.JsonNull,+ },+ },+ });+ hasPageLinks = pageLinksCount > 0;+ }++ const response = {+ dataroomDocumentId: dataroomDocument.id,+ documentId: document.id,+ dataroom: dataroomDocument.dataroom,+ dataroomFolder: dataroomDocument.folder,+ document: {+ ...serializeFileSize(document),+ primaryVersion: serializeFileSize(primaryVersion),+ hasPageLinks,+ isEmpty: !hasLinks && !hasViews,+ },+ limits: {+ canAddLinks: limits?.links ? limits?.usage?.links < limits.links : true,+ canAddDocuments: limits?.documents+ ? limits?.usage?.documents < limits.documents+ : true,+ canAddUsers: limits?.users ? limits?.usage?.users < limits.users : true,+ },+ featureFlags: {+ annotations: featureFlags.annotations,+ },+ team: {+ plan: team?.plan || "free",+ isTrial: team?.plan.includes("drtrial") || false,+ },+ counts: {+ links: document._count.links,+ views: document._count.views,+ otherViewCount,+ },+ };++ res.setHeader(+ "Cache-Control",+ "private, max-age=60, stale-while-revalidate=300",+ );++ return res.status(200).json(response);+ } catch (error) {+ console.error("Dataroom document overview error:", error);+ return res.status(500).json({ error: "Internal server error" });+ }+}diff --git a/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/stats.ts b/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/stats.tsindex b1af3d58..9182d07f 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/stats.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/documents/[documentId]/stats.ts@@ -4,6 +4,7 @@ import { authOptions } from "@/pages/api/auth/[...nextauth]";import { View } from "@prisma/client";import { getServerSession } from "next-auth/next";+import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import {@@ -35,6 +36,13 @@ export default async function handle(const userId = (session.user as CustomUser).id;+ // Scoped members may only read stats within their assigned rooms.+ if (+ await enforceDataroomMemberScope({ userId, teamId, dataroomId, res })+ ) {+ return;+ }+try {// Check if the user is part of the teamconst team = await prisma.team.findUnique({diff --git a/pages/api/teams/[teamId]/datarooms/[id]/documents/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/documents/index.tsindex db105812..9e84e4ee 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/documents/index.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/documents/index.ts@@ -6,16 +6,16 @@ import {processDocumentForAITask,} from "@/ee/features/ai/lib/trigger";import { isTeamPausedById } from "@/ee/features/billing/cancellation/lib/is-team-paused";-import { authOptions } from "@/pages/api/auth/[...nextauth]";import { runs } from "@trigger.dev/sdk";import { waitUntil } from "@vercel/functions";-import { getServerSession } from "next-auth/next";+import { withTeamApi } from "@/lib/api/auth/with-session-team";+import { assertDocumentAccess } from "@/lib/api/rbac/entitlements";+import { isDataroomScopedRole } from "@/lib/api/rbac/permissions";import { errorhandler } from "@/lib/errorHandler";import { getFeatureFlags } from "@/lib/featureFlags";import prisma from "@/lib/prisma";import { sendDataroomChangeNotificationTask } from "@/lib/trigger/dataroom-change-notification";-import { CustomUser } from "@/lib/types";import { log, serializeFileSize } from "@/lib/utils";import { sortItemsByIndexAndName } from "@/lib/utils/sort-items-by-index-name";@@ -24,40 +24,12 @@ export const config = {supportsResponseStreaming: true,};-export default async function handle(- req: NextApiRequest,- res: NextApiResponse,-) {- if (req.method === "GET") {- // GET /api/teams/:teamId/datarooms/:id/documents- const session = await getServerSession(req, res, authOptions);- if (!session) {- return res.status(401).end("Unauthorized");- }-- const userId = (session.user as CustomUser).id;- const { teamId, id: dataroomId } = req.query as {- teamId: string;- id: string;- };+// GET /api/teams/:teamId/datarooms/:id/documents+const getHandler = withTeamApi(+ async ({ req, res }) => {+ const { id: dataroomId } = req.query as { id: string };try {- // Check if the user is part of the team- const team = await prisma.team.findUnique({- where: {- id: teamId,- users: {- some: {- userId: userId,- },- },- },- });-- if (!team) {- return res.status(401).end("Unauthorized");- }-const documents = await prisma.dataroomDocument.findMany({where: {dataroomId: dataroomId,@@ -109,20 +81,14 @@ export default async function handle(.status(500).json({ error: "Error fetching documents from dataroom" });}- } else if (req.method === "POST") {- // POST /api/teams/:teamId/datarooms/:id/documents- const session = await getServerSession(req, res, authOptions);- if (!session) {- res.status(401).end("Unauthorized");- return;- }-- const { teamId, id: dataroomId } = req.query as {- teamId: string;- id: string;- };+ },+ { requiredPermissions: ["datarooms.read"], dataroomParam: "id" },+);- const userId = (session.user as CustomUser).id;+// POST /api/teams/:teamId/datarooms/:id/documents+const postHandler = withTeamApi(+ async ({ req, res, teamId, userId, role, allowedDataroomIds }) => {+ const { id: dataroomId } = req.query as { id: string };// Assuming data is an object with `name` and `description` propertiesconst { documentId, folderPathName } = req.body as {@@ -131,23 +97,33 @@ export default async function handle(};try {- // Check if the user is part of the team- const team = await prisma.team.findUnique({- where: {- id: teamId,- users: {- some: {- userId: userId,- },- },- },- select: {- id: true,- },- });-- if (!team) {- return res.status(401).end("Unauthorized");+ // For dataroom-scoped members, the document being attached must either be+ // owned by them (a fresh upload) or already live in one of their assigned+ // rooms — otherwise an arbitrary team document could be pulled into the+ // room and viewed.+ if (isDataroomScopedRole(role)) {+ const document = await prisma.document.findFirst({+ where: { id: documentId, teamId },+ select: { ownerId: true },+ });+ if (!document) {+ return res.status(404).json({ error: "Document not found" });+ }+ const ownsDocument = document.ownerId === userId;+ const hasRoomAccess =+ ownsDocument ||+ (await assertDocumentAccess({+ role,+ userId,+ teamId,+ documentId,+ allowedIds: allowedDataroomIds,+ }));+ if (!hasRoomAccess) {+ return res+ .status(403)+ .json({ error: "You cannot add this document to a data room." });+ }}// Check if team is paused@@ -355,8 +331,19 @@ export default async function handle(});errorhandler(error, res);}+ },+ { requiredPermissions: ["documents.write"], dataroomParam: "id" },+);++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "GET") {+ return getHandler(req, res);+ } else if (req.method === "POST") {+ return postHandler(req, res);} else {- // We only allow GET requestsres.setHeader("Allow", ["GET", "POST"]);return res.status(405).end(`Method ${req.method} Not Allowed`);}diff --git a/pages/api/teams/[teamId]/datarooms/[id]/documents/move.ts b/pages/api/teams/[teamId]/datarooms/[id]/documents/move.tsindex 907e0ab7..54e5f750 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/documents/move.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/documents/move.ts@@ -1,49 +1,23 @@import { NextApiRequest, NextApiResponse } from "next";-import { authOptions } from "@/pages/api/auth/[...nextauth]";-import { getServerSession } from "next-auth/next";-+import { withTeamApi } from "@/lib/api/auth/with-session-team";import prisma from "@/lib/prisma";-import { CustomUser } from "@/lib/types";-export default async function handle(- req: NextApiRequest,- res: NextApiResponse,-) {- if (req.method === "PATCH") {- // PATCH /api/teams/:teamId/datarooms/:id/documents/move- const session = await getServerSession(req, res, authOptions);- if (!session) {- res.status(401).end("Unauthorized");- return;- }- const userId = (session.user as CustomUser).id;- const { teamId, id: dataroomId } = req.query as {- teamId: string;- id: string;- };+// PATCH /api/teams/:teamId/datarooms/:id/documents/move+const patchHandler = withTeamApi(+ async ({ req, res, teamId }) => {+ const { id: dataroomId } = req.query as { id: string };const { documentIds, folderId } = req.body as {documentIds: string[];folderId: string | null;};- // Ensure the user is an admin of the team- const team = await prisma.team.findUnique({- where: { id: teamId },- include: {- datarooms: {- where: { id: dataroomId },- },- users: {- where: {- role: { in: ["ADMIN", "MANAGER"] },- userId: userId,- },- },- },+ // Ensure the dataroom belongs to the team.+ const dataroom = await prisma.dataroom.findUnique({+ where: { id: dataroomId, teamId },+ select: { id: true },});-- if (!team || team.users.length === 0 || team.datarooms.length === 0) {+ if (!dataroom) {return res.status(403).end("Forbidden");}@@ -72,15 +46,24 @@ export default async function handle(return res.status(404).end("No documents were updated");}- console.log("Documents moved successfully", updatedDocuments.count);-return res.status(200).json({message: "Document moved successfully",updatedCount: updatedDocuments.count,newPath: folder?.path,});+ },+ // Moving documents is a room-manager action: scoped members may do it within+ // an assigned room (canManageDataroom), full roles anywhere.+ { requiredPermissions: ["datarooms.write"], dataroomParam: "id" },+);++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "PATCH") {+ return patchHandler(req, res);} else {- // We only allow PATCH requestsres.setHeader("Allow", ["PATCH"]);return res.status(405).end(`Method ${req.method} Not Allowed`);}diff --git a/pages/api/teams/[teamId]/datarooms/[id]/duplicate.ts b/pages/api/teams/[teamId]/datarooms/[id]/duplicate.tsindex 859186b3..6c0c52ef 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/duplicate.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/duplicate.ts@@ -2,18 +2,16 @@ import { NextApiRequest, NextApiResponse } from "next";import { isTeamPausedById } from "@/ee/features/billing/cancellation/lib/is-team-paused";import { getLimits } from "@/ee/limits/server";-import { authOptions } from "@/pages/api/auth/[...nextauth]";import {Dataroom,DataroomBrand,DataroomDocument,DataroomFolder,} from "@prisma/client";-import { getServerSession } from "next-auth/next";+import { withTeamApi } from "@/lib/api/auth/with-session-team";import { newId } from "@/lib/id-helper";import prisma from "@/lib/prisma";-import { CustomUser } from "@/lib/types";interface DataroomWithContents extends Dataroom {documents: DataroomDocument[];@@ -128,47 +126,12 @@ async function duplicateFolders();}-export default async function handle(- req: NextApiRequest,- res: NextApiResponse,-) {- if (req.method === "POST") {- // POST /api/teams/:teamId/datarooms/:id/duplicate- const session = await getServerSession(req, res, authOptions);- if (!session) {- res.status(401).end("Unauthorized");- return;- }-- const { teamId, id: dataroomId } = req.query as {- teamId: string;- id: string;- };- const userId = (session.user as CustomUser).id;+// POST /api/teams/:teamId/datarooms/:id/duplicate+const postHandler = withTeamApi(+ async ({ req, res, teamId, userId, team }) => {+ const { id: dataroomId } = req.query as { id: string };try {- const team = await prisma.team.findUnique({- where: {- id: teamId,- users: {- some: {- userId: userId,- },- },- },- include: {- _count: {- select: {- datarooms: true,- },- },- },- });-- if (!team) {- return res.status(401).end("Unauthorized");- }-if (team.plan.includes("drtrial")) {return res.status(403).json({message:@@ -198,13 +161,16 @@ export default async function handle(}// Check if the team has reached the limit of datarooms- const limits = await getLimits({ teamId, userId });- if (limits && limits.datarooms !== null && team._count.datarooms >= limits.datarooms) {- console.log(- "Dataroom limit reached",- limits.datarooms,- team._count.datarooms,- );+ const [dataroomCount, limits] = await Promise.all([+ prisma.dataroom.count({ where: { teamId } }),+ getLimits({ teamId, userId }),+ ]);+ if (+ limits &&+ limits.datarooms !== null &&+ dataroomCount >= limits.datarooms+ ) {+ console.log("Dataroom limit reached", limits.datarooms, dataroomCount);return res.status(400).json({message:"You've reached the limit of datarooms. Consider upgrading your plan.",@@ -277,6 +243,22 @@ export default async function handle(console.error("Request error", error);res.status(500).json({ message: "Error duplicating dataroom" });}+ },+ {+ // Duplicating a dataroom creates a new team-level dataroom; scoped members+ // are excluded (they hold datarooms.write only for rooms they already+ // manage, and the copy would never be assigned to them).+ requiredPermissions: ["datarooms.write"],+ requiredRoles: ["ADMIN", "MANAGER", "MEMBER"],+ },+);++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "POST") {+ return postHandler(req, res);} else {// We only allow POST requestsres.setHeader("Allow", ["POST"]);diff --git a/pages/api/teams/[teamId]/datarooms/[id]/folders/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/folders/index.tsindex 63cb302e..74b2971a 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/folders/index.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/folders/index.ts@@ -4,6 +4,7 @@ import { authOptions } from "@/pages/api/auth/[...nextauth]";import { DefaultPermissionStrategy, ItemType } from "@prisma/client";import { getServerSession } from "next-auth/next";+import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";import { resolveFreeFolderPath } from "@/lib/folders/bulk-create";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";@@ -220,6 +221,11 @@ export default async function handle(include_documents?: string;};+ // Scoped members may only read folders for their assigned rooms.+ if (await enforceDataroomMemberScope({ userId, teamId, dataroomId, res })) {+ return;+ }+try {// Check team membership and dataroom ownership together.const team = await prisma.team.findUnique({@@ -431,6 +437,11 @@ export default async function handle(color?: string;};+ // Scoped members may only create folders within their assigned rooms.+ if (await enforceDataroomMemberScope({ userId, teamId, dataroomId, res })) {+ return;+ }+const parentFolderPath = path ? "/" + path : "/";try {diff --git a/pages/api/teams/[teamId]/datarooms/[id]/groups/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/groups/index.tsindex eed778e7..fc3c4e98 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/groups/index.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/groups/index.ts@@ -5,6 +5,7 @@ import { authOptions } from "@/pages/api/auth/[...nextauth]";import { ItemType } from "@prisma/client";import { getServerSession } from "next-auth/next";+import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";@@ -29,6 +30,11 @@ export default async function handle(const folderId = req.query?.folderId as string;const userId = (session.user as CustomUser).id;+ // Scoped members may only read groups for their assigned rooms.+ if (await enforceDataroomMemberScope({ userId, teamId, dataroomId, res })) {+ return;+ }+try {const teamAccess = await prisma.userTeam.findUnique({where: {@@ -154,6 +160,11 @@ export default async function handle(const { name } = req.body as { name: string };+ // Scoped members may only create groups within their assigned rooms.+ if (await enforceDataroomMemberScope({ userId, teamId, dataroomId, res })) {+ return;+ }+try {// Check if the user is part of the teamconst teamAccess = await prisma.userTeam.findUnique({diff --git a/pages/api/teams/[teamId]/datarooms/[id]/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/index.tsindex 637efa19..ab1eb6d0 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/index.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/index.ts@@ -1,45 +1,18 @@import { NextApiRequest, NextApiResponse } from "next";-import { authOptions } from "@/pages/api/auth/[...nextauth]";import { DefaultPermissionStrategy } from "@prisma/client";-import { getServerSession } from "next-auth/next";+import { withTeamApi } from "@/lib/api/auth/with-session-team";import { errorhandler } from "@/lib/errorHandler";import { getFeatureFlags } from "@/lib/featureFlags";import prisma from "@/lib/prisma";-import { CustomUser } from "@/lib/types";-export default async function handle(- req: NextApiRequest,- res: NextApiResponse,-) {- if (req.method === "GET") {- // GET /api/teams/:teamId/datarooms/:id- const session = await getServerSession(req, res, authOptions);- if (!session) {- return res.status(401).end("Unauthorized");- }-- const { teamId, id: dataroomId } = req.query as {- teamId: string;- id: string;- };-- const userId = (session.user as CustomUser).id;+// GET /api/teams/:teamId/datarooms/:id+const getHandler = withTeamApi(+ async ({ req, res, teamId }) => {+ const { id: dataroomId } = req.query as { id: string };try {- const teamAccess = await prisma.userTeam.findUnique({- where: {- userId_teamId: {- userId: userId,- teamId: teamId,- },- },- });- if (!teamAccess) {- return res.status(401).end("Unauthorized");- }-const dataroom = await prisma.dataroom.findUnique({where: {id: dataroomId,@@ -79,41 +52,16 @@ export default async function handle(} catch (error) {errorhandler(error, res);}- } else if (req.method === "PATCH") {- // PATCH /api/teams/:teamId/datarooms/:id- const session = await getServerSession(req, res, authOptions);- if (!session) {- return res.status(401).end("Unauthorized");- }-- const { teamId, id: dataroomId } = req.query as {- teamId: string;- id: string;- };+ },+ { requiredPermissions: ["datarooms.read"], dataroomParam: "id" },+);- const userId = (session.user as CustomUser).id;+// PATCH /api/teams/:teamId/datarooms/:id+const patchHandler = withTeamApi(+ async ({ req, res, teamId, userId, team }) => {+ const { id: dataroomId } = req.query as { id: string };try {- // Check if the user is part of the team- const team = await prisma.team.findUnique({- where: {- id: teamId,- users: {- some: {- userId: userId,- },- },- },- select: {- id: true,- plan: true,- },- });-- if (!team) {- return res.status(401).end("Unauthorized");- }-const {name,internalName,@@ -143,7 +91,10 @@ export default async function handle(};const featureFlags = await getFeatureFlags({ teamId: team.id });- const isDataroomsPlus = team.plan.includes("datarooms-plus") || team.plan.includes("datarooms-premium") || team.plan.includes("datarooms-unlimited");+ const isDataroomsPlus =+ team.plan.includes("datarooms-plus") ||+ team.plan.includes("datarooms-premium") ||+ team.plan.includes("datarooms-unlimited");const isTrial = team.plan.includes("drtrial");if (@@ -172,8 +123,11 @@ export default async function handle(},data: {...(name && { name }),- ...(internalName !== undefined && {- internalName: internalName === null || internalName === "" ? null : internalName.trim()+ ...(internalName !== undefined && {+ internalName:+ internalName === null || internalName === ""+ ? null+ : internalName.trim(),}),...(typeof enableChangeNotifications === "boolean" && {enableChangeNotifications,@@ -269,43 +223,16 @@ export default async function handle(} catch (error) {errorhandler(error, res);}- } else if (req.method === "DELETE") {- // DELETE /api/teams/:teamId/datarooms/:id- const session = await getServerSession(req, res, authOptions);- if (!session) {- return res.status(401).end("Unauthorized");- }+ },+ { requiredPermissions: ["datarooms.write"], dataroomParam: "id" },+);- const userId = (session.user as CustomUser).id;- const { teamId, id: dataroomId } = req.query as {- teamId: string;- id: string;- };+// DELETE /api/teams/:teamId/datarooms/:id+const deleteHandler = withTeamApi(+ async ({ req, res, teamId }) => {+ const { id: dataroomId } = req.query as { id: string };try {- const teamAccess = await prisma.userTeam.findUnique({- where: {- userId_teamId: {- userId: userId,- teamId: teamId,- },- },- select: {- role: true,- },- });-- if (!teamAccess) {- return res.status(401).end("Unauthorized");- }-- if (teamAccess.role !== "ADMIN" && teamAccess.role !== "MANAGER") {- return res.status(403).json({- message:- "You are not permitted to perform this action. Only admin and managers can delete datarooms.",- });- }-await prisma.dataroom.delete({where: {id: dataroomId,@@ -317,9 +244,23 @@ export default async function handle(} catch (error) {errorhandler(error, res);}+ },+ // Deleting a dataroom stays an ADMIN/MANAGER-only structural operation.+ { requiredRoles: ["ADMIN", "MANAGER"] },+);++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "GET") {+ return getHandler(req, res);+ } else if (req.method === "PATCH") {+ return patchHandler(req, res);+ } else if (req.method === "DELETE") {+ return deleteHandler(req, res);} else {- // We only allow GET, and PATCH requests- res.setHeader("Allow", ["GET", "PATCH"]);+ res.setHeader("Allow", ["GET", "PATCH", "DELETE"]);return res.status(405).end(`Method ${req.method} Not Allowed`);}}diff --git a/pages/api/teams/[teamId]/datarooms/[id]/links.ts b/pages/api/teams/[teamId]/datarooms/[id]/links.tsindex 21f82a85..e4df94d0 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/links.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/links.ts@@ -2,6 +2,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { getServerSession } from "next-auth/next";+import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import { CustomUser, LinkWithViews } from "@/lib/types";@@ -27,6 +28,11 @@ export default async function handle(const userId = (session.user as CustomUser).id;+ // Scoped members may only read links for their assigned rooms.+ if (await enforceDataroomMemberScope({ userId, teamId, dataroomId, res })) {+ return;+ }+try {// Check if the user is part of the teamconst team = await prisma.team.findUnique({diff --git a/pages/api/teams/[teamId]/datarooms/[id]/search.ts b/pages/api/teams/[teamId]/datarooms/[id]/search.tsindex 5719789e..239cab2b 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/search.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/search.ts@@ -3,6 +3,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { getServerSession } from "next-auth/next";+import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";@@ -31,6 +32,11 @@ export default async function handle(query?: string;};+ // Scoped members may only search within their assigned rooms.+ if (await enforceDataroomMemberScope({ userId, teamId, dataroomId, res })) {+ return;+ }+if (!query || query.trim().length === 0) {return res.status(200).json({ documents: [], folders: [] });}diff --git a/pages/api/teams/[teamId]/datarooms/[id]/stats.ts b/pages/api/teams/[teamId]/datarooms/[id]/stats.tsindex c5eb8126..ac59330f 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/stats.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/stats.ts@@ -3,6 +3,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { View } from "@prisma/client";import { getServerSession } from "next-auth/next";+import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import { getTotalDataroomDuration } from "@/lib/tinybird";@@ -37,6 +38,11 @@ export default async function handle(const userId = (session.user as CustomUser).id;+ // Scoped members may only read stats for their assigned rooms.+ if (await enforceDataroomMemberScope({ userId, teamId, dataroomId, res })) {+ return;+ }+try {// Check if the user is part of the teamconst team = await prisma.team.findUnique({diff --git a/pages/api/teams/[teamId]/datarooms/[id]/viewers/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/viewers/index.tsindex d6cea228..5d33a141 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/viewers/index.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/viewers/index.ts@@ -3,6 +3,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { getServerSession } from "next-auth/next";+import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";@@ -25,6 +26,11 @@ export default async function handle(};const userId = (session.user as CustomUser).id;+ // Scoped members may only read viewers for their assigned rooms.+ if (await enforceDataroomMemberScope({ userId, teamId, dataroomId, res })) {+ return;+ }+try {const team = await prisma.team.findUnique({where: {diff --git a/pages/api/teams/[teamId]/datarooms/[id]/views-count.ts b/pages/api/teams/[teamId]/datarooms/[id]/views-count.tsindex 4a2136d0..7cf3cf30 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/views-count.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/views-count.ts@@ -3,6 +3,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { getServerSession } from "next-auth/next";+import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";@@ -22,6 +23,13 @@ export default async function handler(const groupId = req.query.groupId as string | undefined;const userId = (session.user as CustomUser).id;+ // Scoped members may only read counts for their assigned rooms.+ if (+ await enforceDataroomMemberScope({ userId, teamId, dataroomId: id, res })+ ) {+ return;+ }+if (req.method === "GET") {try {// Verify user has access to the dataroomdiff --git a/pages/api/teams/[teamId]/datarooms/[id]/views/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/views/index.tsindex 02ac62d3..a269d719 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/views/index.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/views/index.ts@@ -3,6 +3,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { getServerSession } from "next-auth/next";+import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";@@ -25,6 +26,11 @@ export default async function handle(};const userId = (session.user as CustomUser).id;+ // Scoped members may only read views for their assigned rooms.+ if (await enforceDataroomMemberScope({ userId, teamId, dataroomId, res })) {+ return;+ }+try {const team = await prisma.team.findUnique({where: {diff --git a/pages/api/teams/[teamId]/datarooms/index.ts b/pages/api/teams/[teamId]/datarooms/index.tsindex bfab6c6b..b1ea8e11 100644--- a/pages/api/teams/[teamId]/datarooms/index.ts+++ b/pages/api/teams/[teamId]/datarooms/index.ts@@ -2,63 +2,55 @@ import { NextApiRequest, NextApiResponse } from "next";import { isTeamPausedById } from "@/ee/features/billing/cancellation/lib/is-team-paused";import { getLimits } from "@/ee/limits/server";-import { authOptions } from "@/pages/api/auth/[...nextauth]";import { Prisma } from "@prisma/client";-import { getServerSession } from "next-auth/next";+import { withTeamApi } from "@/lib/api/auth/with-session-team";+import { isDataroomScopedRole } from "@/lib/api/rbac/permissions";import { newId } from "@/lib/id-helper";import prisma from "@/lib/prisma";-import { CustomUser } from "@/lib/types";export const config = {maxDuration: 180,};-export default async function handle(- req: NextApiRequest,- res: NextApiResponse,-) {- if (req.method === "GET") {- // GET /api/teams/:teamId/datarooms- const session = await getServerSession(req, res, authOptions);- if (!session) {- return res.status(401).end("Unauthorized");- }-- const userId = (session.user as CustomUser).id;- const { teamId, search, status, tags, simple } = req.query as {- teamId: string;+const DATAROOM_PLANS = [+ "business",+ "datarooms",+ "datarooms-plus",+ "datarooms-premium",+ "datarooms-unlimited",+ "business+old",+ "datarooms+old",+ "datarooms-plus+old",+ "datarooms-premium+old",+ "datarooms-unlimited+old",+ "free+drtrial",+ "datarooms+drtrial",+ "business+drtrial",+ "datarooms-plus+drtrial",+ "datarooms-premium+drtrial",+ "datarooms-unlimited+drtrial",+];++// GET /api/teams/:teamId/datarooms+const getHandler = withTeamApi(+ async ({ req, res, teamId, role, allowedDataroomIds }) => {+ const { search, tags, simple } = req.query as {search?: string;- status?: string;tags?: string;simple?: string;};- // Simple mode: return minimal data without filters, tags, or aggregationsconst isSimpleMode = simple === "true";+ const scoped = isDataroomScopedRole(role);try {- const teamAccess = await prisma.userTeam.findUnique({- where: {- userId_teamId: {- userId: userId,- teamId: teamId,- },- },- select: {- teamId: true,- },- });-- if (!teamAccess) {- return res.status(401).end("Unauthorized");- }-// Simple mode: return minimal data without filters, tags, or aggregationsif (isSimpleMode) {const datarooms = await prisma.dataroom.findMany({where: {teamId: teamId,+ ...(scoped ? { id: { in: allowedDataroomIds } } : {}),},select: {id: true,@@ -86,6 +78,8 @@ export default async function handle(// Build where clause based on filtersconst whereClause: Prisma.DataroomWhereInput = {teamId: teamId,+ // Dataroom-scoped members only ever see their assigned rooms.+ ...(scoped ? { id: { in: allowedDataroomIds } } : {}),};// Search filter - search both name and internalName@@ -122,17 +116,14 @@ export default async function handle(}}- // if (status === "active") {- // whereClause.links = { some: activeLinkFilter };- // } else if (status === "inactive") {- // whereClause.links = { none: activeLinkFilter };- // }+ const countWhere: Prisma.DataroomWhereInput = {+ teamId: teamId,+ ...(scoped ? { id: { in: allowedDataroomIds } } : {}),+ };const [totalCount, datarooms] = await Promise.all([prisma.dataroom.count({- where: {- teamId: teamId,- },+ where: countWhere,}),prisma.dataroom.findMany({where: whereClause,@@ -212,54 +203,21 @@ export default async function handle(console.error("Request error", error);return res.status(500).json({ error: "Error fetching datarooms" });}- } else if (req.method === "POST") {- // POST /api/teams/:teamId/datarooms- const session = await getServerSession(req, res, authOptions);- if (!session) {- res.status(401).end("Unauthorized");- return;- }-- const userId = (session.user as CustomUser).id;-- const { teamId } = req.query as { teamId: string };- const { name, internalName } = req.body as { name: string; internalName?: string };+ },+ { requiredPermissions: ["datarooms.read"] },+);++// POST /api/teams/:teamId/datarooms+const postHandler = withTeamApi(+ async ({ req, res, teamId, userId, team }) => {+ const { name, internalName } = req.body as {+ name: string;+ internalName?: string;+ };try {- // Check if the user is part of the team- const team = await prisma.team.findUnique({- where: {- id: teamId,- plan: {- in: [- "business",- "datarooms",- "datarooms-plus",- "datarooms-premium",- "datarooms-unlimited",- "business+old",- "datarooms+old",- "datarooms-plus+old",- "datarooms-premium+old",- "datarooms-unlimited+old",- "free+drtrial",- "datarooms+drtrial",- "business+drtrial",- "datarooms-plus+drtrial",- "datarooms-premium+drtrial",- "datarooms-unlimited+drtrial",- ],- },- users: {- some: {- userId: userId,- },- },- },- });-- if (!team) {- return res.status(401).end("Unauthorized");+ if (!DATAROOM_PLANS.includes(team.plan)) {+ return res.status(403).end("Forbidden");}// Check if team is paused@@ -280,7 +238,11 @@ export default async function handle(const limits = await getLimits({ teamId, userId });- if (limits && limits.datarooms !== null && dataroomCount >= limits.datarooms) {+ if (+ limits &&+ limits.datarooms !== null &&+ dataroomCount >= limits.datarooms+ ) {return res.status(403).json({ message: "You have reached the limit of datarooms" });@@ -307,8 +269,24 @@ export default async function handle(console.error("Request error", error);res.status(500).json({ error: "Error creating dataroom" });}+ },+ {+ // Creating a dataroom is a team-level structural action; scoped members are+ // excluded (they hold datarooms.write only for rooms they already manage).+ requiredPermissions: ["datarooms.write"],+ requiredRoles: ["ADMIN", "MANAGER", "MEMBER"],+ },+);++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "GET") {+ return getHandler(req, res);+ } else if (req.method === "POST") {+ return postHandler(req, res);} else {- // We only allow POST requestsres.setHeader("Allow", ["GET", "POST"]);return res.status(405).end(`Method ${req.method} Not Allowed`);}diff --git a/pages/api/teams/[teamId]/documents/[id]/add-to-dataroom.ts b/pages/api/teams/[teamId]/documents/[id]/add-to-dataroom.tsindex 492c9a81..62c60614 100644--- a/pages/api/teams/[teamId]/documents/[id]/add-to-dataroom.ts+++ b/pages/api/teams/[teamId]/documents/[id]/add-to-dataroom.ts@@ -5,63 +5,56 @@ import {processDocumentForAITask,SUPPORTED_AI_CONTENT_TYPES,} from "@/ee/features/ai/lib/trigger";-import { authOptions } from "@/pages/api/auth/[...nextauth]";import { waitUntil } from "@vercel/functions";-import { getServerSession } from "next-auth/next";+import { withTeamApi } from "@/lib/api/auth/with-session-team";+import { assertDocumentAccess } from "@/lib/api/rbac/entitlements";+import { isDataroomScopedRole } from "@/lib/api/rbac/permissions";import { getFeatureFlags } from "@/lib/featureFlags";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";-import { CustomUser } from "@/lib/types";export const config = {// in order to enable `waitUntil` functionsupportsResponseStreaming: true,};-export default async function handle(- req: NextApiRequest,- res: NextApiResponse,-) {- if (req.method === "POST") {- // POST /api/teams/:teamId/documents/:id/add-to-dataroom- const session = await getServerSession(req, res, authOptions);- if (!session) {- return res.status(401).end("Unauthorized");- }-- const { teamId, id: docId } = req.query as { teamId: string; id: string };+// POST /api/teams/:teamId/documents/:id/add-to-dataroom+const postHandler = withTeamApi(+ async ({ req, res, teamId, userId, role, team, allowedDataroomIds }) => {+ const { id: docId } = req.query as { id: string };const { dataroomId } = req.body as { dataroomId: string };- const userId = (session.user as CustomUser).id;-try {- const team = await prisma.team.findUnique({- where: {- id: teamId,- users: {- some: {- userId,- },- },- documents: {- some: {- id: {- equals: docId,- },- },- },- },- select: {- id: true,- plan: true,- },+ // The document must belong to the team.+ const ownedByTeam = await prisma.document.findFirst({+ where: { id: docId, teamId },+ select: { id: true, ownerId: true },});-- if (!team) {+ if (!ownedByTeam) {return res.status(401).end("Unauthorized");}+ // Scoped members may only attach a document they own or that already+ // lives in one of their assigned rooms.+ if (isDataroomScopedRole(role)) {+ const ownsDocument = ownedByTeam.ownerId === userId;+ const hasRoomAccess =+ ownsDocument ||+ (await assertDocumentAccess({+ role,+ userId,+ teamId,+ documentId: docId,+ allowedIds: allowedDataroomIds,+ }));+ if (!hasRoomAccess) {+ return res+ .status(403)+ .json({ message: "You cannot add this document to a data room." });+ }+ }+if ((team.plan === "free" || team.plan === "pro") &&!team.plan.includes("drtrial")@@ -202,8 +195,22 @@ export default async function handle(} catch (error) {errorhandler(error, res);}+ },+ {+ requiredPermissions: ["documents.write"],+ // dataroomId arrives in the request body for this route.+ resolveDataroomId: ({ req }) =>+ (req as NextApiRequest).body?.dataroomId as string | undefined,+ },+);++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method === "POST") {+ return postHandler(req, res);} else {- // We only allow POST requestsres.setHeader("Allow", ["POST"]);return res.status(405).end(`Method ${req.method} Not Allowed`);}diff --git a/pages/api/teams/[teamId]/documents/[id]/index.ts b/pages/api/teams/[teamId]/documents/[id]/index.tsindex ad104041..8a5cc9bb 100644--- a/pages/api/teams/[teamId]/documents/[id]/index.ts+++ b/pages/api/teams/[teamId]/documents/[id]/index.ts@@ -3,6 +3,8 @@ import { NextApiRequest, NextApiResponse } from "next";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { getServerSession } from "next-auth/next";+import { assertDocumentAccess } from "@/lib/api/rbac/entitlements";+import { isDataroomScopedRole } from "@/lib/api/rbac/permissions";import { TeamError, errorhandler } from "@/lib/errorHandler";import { getFeatureFlags } from "@/lib/featureFlags";import { deleteFile } from "@/lib/files/delete-file-server";@@ -49,13 +51,25 @@ export default async function handle(teamId: teamId,},},- select: { teamId: true },+ select: { teamId: true, role: true },});if (!teamAccess) {return res.status(401).json({ message: "Unauthorized" });}+ // Dataroom-scoped members may only read a document that lives in one of+ // their assigned rooms (closes cross-room/all-documents IDOR).+ const hasDocumentAccess = await assertDocumentAccess({+ role: teamAccess.role,+ userId,+ teamId,+ documentId: docId,+ });+ if (!hasDocumentAccess) {+ return res.status(403).json({ message: "Forbidden" });+ }+// Then fetch the specific document with its relationships (targeted query)const document = await prisma.document.findUnique({where: {@@ -279,6 +293,16 @@ export default async function handle(return res.status(401).json({ message: "Unauthorized" });}+ // Data room members can only remove documents from a data room (via the+ // dataroom-scoped endpoint); they must never delete the underlying+ // document for the whole team.+ if (isDataroomScopedRole(teamAccess.role)) {+ return res.status(403).json({+ message:+ "Data room members cannot delete documents. You can only remove documents from a data room.",+ });+ }+const documentVersions = await prisma.document.findUnique({where: {id: docId,diff --git a/pages/api/teams/[teamId]/documents/[id]/links.ts b/pages/api/teams/[teamId]/documents/[id]/links.tsindex 5aba8765..792605f9 100644--- a/pages/api/teams/[teamId]/documents/[id]/links.ts+++ b/pages/api/teams/[teamId]/documents/[id]/links.ts@@ -3,6 +3,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { getServerSession } from "next-auth/next";+import { enforceDocumentMemberScope } from "@/lib/api/rbac/guard";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";@@ -22,6 +23,12 @@ export default async function handle(const { teamId, id: docId } = req.query as { teamId: string; id: string };const userId = (session.user as CustomUser).id;+ if (+ await enforceDocumentMemberScope({ userId, teamId, documentId: docId, res })+ ) {+ return;+ }+try {// First, ensure the requester belongs to the teamconst teamHasUser = await prisma.team.findFirst({diff --git a/pages/api/teams/[teamId]/documents/[id]/overview.ts b/pages/api/teams/[teamId]/documents/[id]/overview.tsindex aebf5b7b..bddd46ae 100644--- a/pages/api/teams/[teamId]/documents/[id]/overview.ts+++ b/pages/api/teams/[teamId]/documents/[id]/overview.ts@@ -5,6 +5,7 @@ import { authOptions } from "@/pages/api/auth/[...nextauth]";import { Prisma } from "@prisma/client";import { getServerSession } from "next-auth/next";+import { enforceDocumentMemberScope } from "@/lib/api/rbac/guard";import { getFeatureFlags } from "@/lib/featureFlags";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";@@ -31,6 +32,13 @@ export default async function handle(const userId = (session.user as CustomUser).id;+ // Dataroom-scoped members may only access documents in their assigned rooms.+ if (+ await enforceDocumentMemberScope({ userId, teamId, documentId: docId, res })+ ) {+ return;+ }+try {// First verify user has access to the teamconst team = await prisma.team.findUnique({diff --git a/pages/api/teams/[teamId]/documents/[id]/preview-data.ts b/pages/api/teams/[teamId]/documents/[id]/preview-data.tsindex e3aa5a45..f40826d5 100644--- a/pages/api/teams/[teamId]/documents/[id]/preview-data.ts+++ b/pages/api/teams/[teamId]/documents/[id]/preview-data.ts@@ -4,6 +4,7 @@ import { getServerSession } from "next-auth/next";import { getTeamStorageConfigById } from "@/ee/features/storage/config";+import { enforceDocumentMemberScope } from "@/lib/api/rbac/guard";import { getFile } from "@/lib/files/get-file";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";@@ -31,6 +32,13 @@ export default async function handle(};const userId = (session.user as CustomUser).id;+ // Dataroom-scoped members may only access documents in their assigned rooms.+ if (+ await enforceDocumentMemberScope({ userId, teamId, documentId, res })+ ) {+ return;+ }+try {const team = await prisma.team.findUnique({where: {diff --git a/pages/api/teams/[teamId]/documents/[id]/preview-pages.ts b/pages/api/teams/[teamId]/documents/[id]/preview-pages.tsindex 6738141a..6b648343 100644--- a/pages/api/teams/[teamId]/documents/[id]/preview-pages.ts+++ b/pages/api/teams/[teamId]/documents/[id]/preview-pages.ts@@ -2,6 +2,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { getServerSession } from "next-auth/next";+import { enforceDocumentMemberScope } from "@/lib/api/rbac/guard";import { getFile } from "@/lib/files/get-file";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";@@ -31,6 +32,13 @@ export default async function handle(};const userId = (session.user as CustomUser).id;+ // Dataroom-scoped members may only access documents in their assigned rooms.+ if (+ await enforceDocumentMemberScope({ userId, teamId, documentId, res })+ ) {+ return;+ }+const { pageNumbers } = req.body as { pageNumbers: number[] };if (!pageNumbers || pageNumbers.length === 0) {diff --git a/pages/api/teams/[teamId]/documents/[id]/stats.ts b/pages/api/teams/[teamId]/documents/[id]/stats.tsindex f456fb60..0e0b7fcc 100644--- a/pages/api/teams/[teamId]/documents/[id]/stats.ts+++ b/pages/api/teams/[teamId]/documents/[id]/stats.ts@@ -4,6 +4,7 @@ import { authOptions } from "@/pages/api/auth/[...nextauth]";import { View } from "@prisma/client";import { getServerSession } from "next-auth/next";+import { assertDocumentAccess } from "@/lib/api/rbac/entitlements";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import {@@ -31,10 +32,14 @@ export default async function handle(teamId,id: docId,excludeTeamMembers,+ dataroomId,} = req.query as {teamId: string;id: string;excludeTeamMembers?: string;+ // When provided, stats are scoped to this data room's visits only,+ // treating the document's direct-link visits as out of scope.+ dataroomId?: string;};const userId = (session.user as CustomUser).id;@@ -48,6 +53,22 @@ export default async function handle(return res.status(401).end("Unauthorized");}+ // Dataroom-scoped members may only read stats for a document in one of+ // their assigned rooms.+ const membership = await prisma.userTeam.findUnique({+ where: { userId_teamId: { userId, teamId } },+ select: { role: true },+ });+ const hasDocumentAccess = await assertDocumentAccess({+ role: membership?.role ?? "",+ userId,+ teamId,+ documentId: docId,+ });+ if (!hasDocumentAccess) {+ return res.status(403).end("Forbidden");+ }+// First check if document exists and get basic infoconst document = await prisma.document.findUnique({where: {@@ -126,25 +147,40 @@ export default async function handle(});}- // combined archived and internal views- const allExcludedViews = [...internalViews, ...archivedViews];+ // When scoped to a data room, the document's direct-link visits (and any+ // visits belonging to other rooms) are out of scope and excluded.+ const outOfScopeViews: View[] = dataroomId+ ? activeViews.filter((view) => view.dataroomId !== dataroomId)+ : [];++ // combined archived, internal, and out-of-scope views (deduped by id)+ const excludedViewIdSet = new Set<string>();+ for (const view of [+ ...internalViews,+ ...archivedViews,+ ...outOfScopeViews,+ ]) {+ excludedViewIdSet.add(view.id);+ }+ const excludedViewIds = Array.from(excludedViewIdSet);+ const excludedViewIdsString = excludedViewIds.join(",");// filter out the excluded viewsconst filteredViews = views.filter(- (view) => !allExcludedViews.map((view) => view.id).includes(view.id),+ (view) => !excludedViewIdSet.has(view.id),);const [duration, totalDocumentDuration] = await Promise.all([getTotalAvgPageDuration({documentId: docId,excludedLinkIds: "",- excludedViewIds: allExcludedViews.map((view) => view.id).join(","),+ excludedViewIds: excludedViewIdsString,since: 0,}),getTotalDocumentDuration({documentId: docId,excludedLinkIds: "",- excludedViewIds: allExcludedViews.map((view) => view.id).join(","),+ excludedViewIds: excludedViewIdsString,since: 0,}),]);@@ -192,7 +228,7 @@ export default async function handle(// For document type, calculate based on pages viewedconst completionStats = await getViewCompletionStats({documentId: docId,- excludedViewIds: allExcludedViews.map((v) => v.id).join(","),+ excludedViewIds: excludedViewIdsString,since: 0,});@@ -228,8 +264,10 @@ export default async function handle(views: filteredViews,duration,total_duration:- (totalDocumentDuration.data[0].sum_duration * 1.0) /- filteredViews.length,+ filteredViews.length > 0+ ? ((totalDocumentDuration.data[0]?.sum_duration ?? 0) * 1.0) /+ filteredViews.length+ : 0,avgCompletionRate: Math.round(avgCompletionRate),totalViews: filteredViews.length,};diff --git a/pages/api/teams/[teamId]/documents/[id]/versions/index.ts b/pages/api/teams/[teamId]/documents/[id]/versions/index.tsindex db2c51c7..ff5d7c85 100644--- a/pages/api/teams/[teamId]/documents/[id]/versions/index.ts+++ b/pages/api/teams/[teamId]/documents/[id]/versions/index.ts@@ -5,6 +5,7 @@ import { authOptions } from "@/pages/api/auth/[...nextauth]";import { getServerSession } from "next-auth/next";import { hashToken } from "@/lib/api/auth/token";+import { enforceDocumentMemberScope } from "@/lib/api/rbac/guard";import { copyFileToBucketServer } from "@/lib/files/copy-file-to-bucket-server";import prisma from "@/lib/prisma";import { convertFilesToPdfTask } from "@/lib/trigger/convert-files";@@ -56,6 +57,13 @@ export default async function handle(userId = (session.user as CustomUser).id;}+ // Scoped members may only add versions to documents in their rooms.+ if (+ await enforceDocumentMemberScope({ userId, teamId, documentId, res })+ ) {+ return;+ }+// Validate request body using Zod schema for securityconst validationResult = await documentUploadSchema.safeParseAsync({...req.body,diff --git a/pages/api/teams/[teamId]/documents/[id]/video-analytics.ts b/pages/api/teams/[teamId]/documents/[id]/video-analytics.tsindex 930d71f4..45adc8dd 100644--- a/pages/api/teams/[teamId]/documents/[id]/video-analytics.ts+++ b/pages/api/teams/[teamId]/documents/[id]/video-analytics.ts@@ -3,6 +3,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { getServerSession } from "next-auth/next";+import { enforceDocumentMemberScope } from "@/lib/api/rbac/guard";import prisma from "@/lib/prisma";import { getVideoEventsByDocument } from "@/lib/tinybird/pipes";import { CustomUser } from "@/lib/types";@@ -184,6 +185,18 @@ export default async function handle(id: string;};+ // Scoped members may only read analytics for documents in their assigned rooms.+ if (+ await enforceDocumentMemberScope({+ userId: user.id,+ teamId,+ documentId,+ res,+ })+ ) {+ return;+ }+// Check if user has access to this document and teamconst document = await prisma.document.findFirst({where: {diff --git a/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/click-events.ts b/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/click-events.tsindex be43a9b8..023ec771 100644--- a/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/click-events.ts+++ b/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/click-events.ts@@ -3,6 +3,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { getServerSession } from "next-auth/next";+import { enforceDocumentMemberScope } from "@/lib/api/rbac/guard";import prisma from "@/lib/prisma";import { getClickEventsByView } from "@/lib/tinybird/pipes";import { CustomUser } from "@/lib/types";@@ -29,6 +30,13 @@ export default async function handler(const userId = (session.user as CustomUser).id;+ // Scoped members may only read views for documents in their assigned rooms.+ if (+ await enforceDocumentMemberScope({ userId, teamId, documentId: id, res })+ ) {+ return;+ }+try {const team = await prisma.team.findUnique({where: {diff --git a/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/custom-fields.ts b/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/custom-fields.tsindex 89c07af9..427dc30e 100644--- a/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/custom-fields.ts+++ b/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/custom-fields.ts@@ -3,6 +3,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { getServerSession } from "next-auth/next";+import { enforceDocumentMemberScope } from "@/lib/api/rbac/guard";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";@@ -30,6 +31,18 @@ export default async function handle(const userId = (session.user as CustomUser).id;+ // Scoped members may only read views for documents in their assigned rooms.+ if (+ await enforceDocumentMemberScope({+ userId,+ teamId,+ documentId: docId,+ res,+ })+ ) {+ return;+ }+try {const team = await prisma.team.findUnique({where: {diff --git a/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/stats.ts b/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/stats.tsindex 77f9cba1..b4c104ef 100644--- a/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/stats.ts+++ b/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/stats.ts@@ -3,6 +3,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { getServerSession } from "next-auth/next";+import { enforceDocumentMemberScope } from "@/lib/api/rbac/guard";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import { getViewPageDuration } from "@/lib/tinybird";@@ -31,6 +32,18 @@ export default async function handle(const userId = (session.user as CustomUser).id;+ // Scoped members may only read views for documents in their assigned rooms.+ if (+ await enforceDocumentMemberScope({+ userId,+ teamId,+ documentId: docId,+ res,+ })+ ) {+ return;+ }+try {const teamAccess = await prisma.userTeam.findUnique({where: {diff --git a/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/user-agent.ts b/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/user-agent.tsindex 197f0615..267bf5d7 100644--- a/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/user-agent.ts+++ b/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/user-agent.ts@@ -3,6 +3,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { getServerSession } from "next-auth/next";+import { enforceDocumentMemberScope } from "@/lib/api/rbac/guard";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import { getViewUserAgent, getViewUserAgent_v2 } from "@/lib/tinybird";@@ -31,6 +32,18 @@ export default async function handle(const userId = (session.user as CustomUser).id;+ // Scoped members may only read views for documents in their assigned rooms.+ if (+ await enforceDocumentMemberScope({+ userId,+ teamId,+ documentId: docId,+ res,+ })+ ) {+ return;+ }+try {const team = await prisma.team.findUnique({where: {diff --git a/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/video-stats.ts b/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/video-stats.tsindex efb19d65..469ea7e2 100644--- a/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/video-stats.ts+++ b/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/video-stats.ts@@ -3,6 +3,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { getServerSession } from "next-auth/next";+import { enforceDocumentMemberScope } from "@/lib/api/rbac/guard";import prisma from "@/lib/prisma";import { getVideoEventsByView } from "@/lib/tinybird/pipes";import { CustomUser } from "@/lib/types";@@ -32,6 +33,18 @@ export default async function handler(};const userId = (session.user as CustomUser).id;+ // Scoped members may only read views for documents in their assigned rooms.+ if (+ await enforceDocumentMemberScope({+ userId,+ teamId,+ documentId,+ res,+ })+ ) {+ return;+ }+// Check document accessconst doc = await prisma.document.findFirst({where: {diff --git a/pages/api/teams/[teamId]/documents/[id]/views/index.ts b/pages/api/teams/[teamId]/documents/[id]/views/index.tsindex 150f5ec8..96bdaa93 100644--- a/pages/api/teams/[teamId]/documents/[id]/views/index.ts+++ b/pages/api/teams/[teamId]/documents/[id]/views/index.ts@@ -2,10 +2,12 @@ import { NextApiRequest, NextApiResponse } from "next";import { isTeamPaused } from "@/ee/features/billing/cancellation/lib/is-team-paused";import { authOptions } from "@/pages/api/auth/[...nextauth]";-import { View } from "@prisma/client";+import { Prisma, View } from "@prisma/client";import { JsonValue } from "@prisma/client/runtime/library";import { getServerSession } from "next-auth/next";+import { enforceDocumentMemberScope } from "@/lib/api/rbac/guard";+import { isDataroomScopedRole } from "@/lib/api/rbac/permissions";import { LIMITS } from "@/lib/constants";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";@@ -187,6 +189,13 @@ export default async function handle(const { teamId, id: docId } = req.query as { teamId: string; id: string };+ // Optional dataroom scoping. When `dataroomId` is provided the views are+ // partitioned into the room's own visits ("dataroom") and the document's+ // direct-link visits ("other"). This powers the dataroom document page,+ // which shows room visits primarily and keeps direct-link visits separate.+ const dataroomId = (req.query.dataroomId as string) || undefined;+ const scope = (req.query.scope as string) || undefined;+// Parse and validate pagination parametersconst rawPage = Number.parseInt((req.query.page as string) || "1", 10);const rawLimit = Number.parseInt((req.query.limit as string) || "10", 10);@@ -201,6 +210,36 @@ export default async function handle(const userId = (session.user as CustomUser).id;+ if (+ await enforceDocumentMemberScope({ userId, teamId, documentId: docId, res })+ ) {+ return;+ }++ // Build the dataroom scope filter. "dataroom" → only this room's views;+ // "other" → only the document's direct-link visits (no dataroom).+ let scopeWhere: Prisma.ViewWhereInput = {};+ if (dataroomId) {+ if (scope === "other") {+ // Direct document-link visits must never be exposed to dataroom-scoped+ // members — they are only meaningful to full team members.+ const membership = await prisma.userTeam.findUnique({+ where: { userId_teamId: { userId, teamId } },+ select: { role: true },+ });+ if (membership && isDataroomScopedRole(membership.role)) {+ return res.status(200).json({+ viewsWithDuration: [],+ hiddenViewCount: 0,+ totalViews: 0,+ });+ }+ scopeWhere = { dataroomId: null };+ } else {+ scopeWhere = { dataroomId };+ }+ }+try {const team = await prisma.team.findUnique({where: {@@ -258,6 +297,7 @@ export default async function handle(const viewsWhereClause = {documentId: docId,isArchived: false,+ ...scopeWhere,...(pauseStartedAt && {viewedAt: {lt: pauseStartedAt,@@ -283,6 +323,7 @@ export default async function handle(take: limit,where: {documentId: docId,+ ...scopeWhere,...(pauseStartedAt && {viewedAt: {lt: pauseStartedAt,@@ -345,6 +386,7 @@ export default async function handle(where: {documentId: docId,isArchived: false,+ ...scopeWhere,},});@@ -354,6 +396,7 @@ export default async function handle(where: {documentId: docId,isArchived: false,+ ...scopeWhere,viewedAt: {gte: pauseStartedAt,},diff --git a/pages/api/teams/[teamId]/documents/index.ts b/pages/api/teams/[teamId]/documents/index.tsindex 0bd290e7..cc41f1e3 100644--- a/pages/api/teams/[teamId]/documents/index.ts+++ b/pages/api/teams/[teamId]/documents/index.ts@@ -6,6 +6,7 @@ import { Prisma } from "@prisma/client";import { getServerSession } from "next-auth/next";import { hashToken } from "@/lib/api/auth/token";+import { isDataroomScopedRole } from "@/lib/api/rbac/permissions";import { processDocument } from "@/lib/api/documents/process-document";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";@@ -52,6 +53,14 @@ export default async function handle(return res.status(401).end("Unauthorized");}+ // The team-wide "All Documents" list is not part of the dataroom-scoped+ // surface; scoped members must never enumerate every team document.+ if (isDataroomScopedRole(teamAccess.role)) {+ return res+ .status(403)+ .json({ error: "You do not have permission to perform this action." });+ }+let orderBy: Prisma.DocumentOrderByWithRelationInput;if (query || sort) {diff --git a/pages/api/teams/[teamId]/documents/search.ts b/pages/api/teams/[teamId]/documents/search.tsindex cb82e671..b21040d1 100644--- a/pages/api/teams/[teamId]/documents/search.ts+++ b/pages/api/teams/[teamId]/documents/search.ts@@ -3,6 +3,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { getServerSession } from "next-auth/next";+import { isDataroomScopedRole } from "@/lib/api/rbac/permissions";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";@@ -34,6 +35,13 @@ export default async function handle(return res.status(401).end("Unauthorized");}+ // Team-wide document search is not part of the dataroom-scoped surface.+ if (isDataroomScopedRole(teamAccess.role)) {+ return res+ .status(403)+ .json({ error: "You do not have permission to perform this action." });+ }+// First, get documents without expensive countsconst documents = await prisma.document.findMany({where: {diff --git a/pages/api/teams/[teamId]/index.ts b/pages/api/teams/[teamId]/index.tsindex 4eaeb0aa..c241f84a 100644--- a/pages/api/teams/[teamId]/index.ts+++ b/pages/api/teams/[teamId]/index.ts@@ -74,7 +74,14 @@ export default async function handle(return res.status(403).end("Unauthorized to access this team");}- return res.status(200).json(team);+ // Attach per-member dataroom assignments so the client can render the+ // scoped-member editor and derive the current user's allowed rooms.+ const userDatarooms = await prisma.userDataroom.findMany({+ where: { teamId },+ select: { userId: true, dataroomId: true },+ });++ return res.status(200).json({ ...team, userDatarooms });} catch (error) {errorhandler(error, res);}diff --git a/pages/api/teams/[teamId]/invitations/accept.ts b/pages/api/teams/[teamId]/invitations/accept.tsindex cfebbfec..89663857 100644--- a/pages/api/teams/[teamId]/invitations/accept.ts+++ b/pages/api/teams/[teamId]/invitations/accept.ts@@ -103,17 +103,39 @@ export default async function handle(return res.status(410).json("Invitation link has expired");}- await prisma.team.update({- where: {- id: teamId,- },- data: {- users: {- create: {- userId,- },+ // Apply the invited role (defaults to MEMBER for legacy invitations) and,+ // for dataroom-scoped members, create the per-room assignments. Only+ // datarooms that still belong to the team are assigned.+ const invitedRole = invitation.role;+ const assignableDataroomIds =+ invitedRole === "DATAROOM_MEMBER" && invitation.dataroomIds.length > 0+ ? (+ await prisma.dataroom.findMany({+ where: { id: { in: invitation.dataroomIds }, teamId },+ select: { id: true },+ })+ ).map((d) => d.id)+ : [];++ await prisma.$transaction(async (tx) => {+ await tx.userTeam.create({+ data: {+ userId,+ teamId,+ role: invitedRole,},- },+ });++ if (assignableDataroomIds.length > 0) {+ await tx.userDataroom.createMany({+ data: assignableDataroomIds.map((dataroomId) => ({+ userId,+ teamId,+ dataroomId,+ })),+ skipDuplicates: true,+ });+ }});await identifyUser(invitation.email);diff --git a/pages/api/teams/[teamId]/invite.ts b/pages/api/teams/[teamId]/invite.tsindex dbb85321..300d72eb 100644--- a/pages/api/teams/[teamId]/invite.ts+++ b/pages/api/teams/[teamId]/invite.ts@@ -28,12 +28,37 @@ export default async function handle(const { teamId } = req.query as { teamId: string };const userId = (session.user as CustomUser).id;- const { email } = req.body;+ const { email, role: rawRole, dataroomIds: rawDataroomIds } = req.body as {+ email?: string;+ role?: string;+ dataroomIds?: string[];+ };if (!email) {return res.status(400).json("Email is missing in request body");}+ const ALLOWED_INVITE_ROLES = [+ "ADMIN",+ "MANAGER",+ "MEMBER",+ "DATAROOM_MEMBER",+ ] as const;+ const role =+ rawRole && ALLOWED_INVITE_ROLES.includes(rawRole as any)+ ? (rawRole as (typeof ALLOWED_INVITE_ROLES)[number])+ : "MEMBER";+ const dataroomIds =+ role === "DATAROOM_MEMBER" && Array.isArray(rawDataroomIds)+ ? Array.from(new Set(rawDataroomIds.filter((id) => typeof id === "string")))+ : [];++ if (role === "DATAROOM_MEMBER" && dataroomIds.length === 0) {+ return res+ .status(400)+ .json("Select at least one data room for a data room member.");+ }+try {const userTeam = await prisma.userTeam.findUnique({where: {@@ -121,6 +146,19 @@ export default async function handle(return;}+ // Validate that any selected datarooms belong to this team.+ if (dataroomIds.length > 0) {+ const validDatarooms = await prisma.dataroom.findMany({+ where: { id: { in: dataroomIds }, teamId },+ select: { id: true },+ });+ if (validDatarooms.length !== dataroomIds.length) {+ return res+ .status(400)+ .json("One or more selected data rooms are invalid.");+ }+ }+const token = newId("inv");const expiresAt = new Date();expiresAt.setHours(expiresAt.getHours() + 168); // 7 days // invitation expires in 24 hour@@ -132,6 +170,8 @@ export default async function handle(token,expires: expiresAt,teamId,+ role,+ dataroomIds,},});diff --git a/pages/api/teams/[teamId]/remove-teammate.ts b/pages/api/teams/[teamId]/remove-teammate.tsindex da99d657..61ff6bc4 100644--- a/pages/api/teams/[teamId]/remove-teammate.ts+++ b/pages/api/teams/[teamId]/remove-teammate.ts@@ -80,6 +80,14 @@ export default async function handle(},}),revokeUserBoundTeamTokens(userToBeDeleted, teamId),+ // remove any dataroom-scoped assignments for this user in this team+ // (UserDataroom has no FK to UserTeam, so it isn't covered by cascade)+ prisma.userDataroom.deleteMany({+ where: {+ userId: userToBeDeleted,+ teamId,+ },+ }),// delete the user from the teamprisma.userTeam.delete({where: {diff --git a/pages/datarooms/[id]/document/[documentId].tsx b/pages/datarooms/[id]/document/[documentId].tsxnew file mode 100644index 00000000..4f12ad57--- /dev/null+++ b/pages/datarooms/[id]/document/[documentId].tsx@@ -0,0 +1,229 @@+// Lazy load heavy components for better performance+import dynamic from "next/dynamic";+import ErrorPage from "next/error";+import Link from "next/link";++import { Suspense } from "react";++import { useTeam } from "@/context/team-context";+import { ExternalLinkIcon } from "lucide-react";++import { useSelfMembership } from "@/lib/hooks/use-self-membership";+import { useDataroomDocumentOverview } from "@/lib/swr/use-dataroom-document";+import { useDocumentLinks } from "@/lib/swr/use-document";++import DocumentHeader from "@/components/documents/document-header";+import { DocumentPreviewButton } from "@/components/documents/document-preview-button";+import LinkDocumentIndicator from "@/components/documents/link-document-indicator";+import NotionAccessibilityIndicator from "@/components/documents/notion-accessibility-indicator";+import AppLayout from "@/components/layouts/app";+import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import LoadingSpinner from "@/components/ui/loading-spinner";++const StatsComponent = dynamic(+ () =>+ import("@/components/documents/stats").then((mod) => ({+ default: mod.StatsComponent,+ })),+ {+ loading: () => (+ <div className="flex h-48 animate-pulse items-center justify-center rounded-lg bg-gray-100">+ <LoadingSpinner className="h-6 w-6" />+ </div>+ ),+ ssr: false,+ },+);++const VideoAnalytics = dynamic(+ () => import("@/components/documents/video-analytics"),+ {+ loading: () => (+ <div className="flex h-48 animate-pulse items-center justify-center rounded-lg bg-gray-100">+ <LoadingSpinner className="h-6 w-6" />+ </div>+ ),+ ssr: false,+ },+);++const VisitorsTable = dynamic(+ () => import("@/components/visitors/visitors-table"),+ {+ loading: () => (+ <div className="flex h-64 animate-pulse items-center justify-center rounded-lg bg-gray-100">+ <LoadingSpinner className="h-6 w-6" />+ </div>+ ),+ ssr: false,+ },+);++export default function DataroomDocumentPage() {+ const {+ documentId,+ dataroomDocumentId,+ document: prismaDocument,+ primaryVersion,+ dataroom,+ counts,+ loading: overviewLoading,+ error,+ mutate: mutateOverview,+ } = useDataroomDocumentOverview();++ // Reuse the existing (scope-guarded) document endpoints by threading the+ // resolved underlying document id, since router.query.id is the dataroom id.+ const { mutate: mutateLinks } = useDocumentLinks(documentId);+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;+ const dataroomId = dataroom?.id;++ // Dataroom-scoped members only ever see the room's own visits. Full team+ // members additionally get a small count of the document's direct-link+ // visits, with a shortcut to the team-wide document page for the details.+ const { isDataroomMember } = useSelfMembership();+ const otherViewCount = counts?.otherViewCount ?? 0;++ const mutateDocument = () => {+ mutateOverview();+ mutateLinks();+ };++ if (error && error.status === 400) {+ return <ErrorPage statusCode={400} />;+ }++ if (overviewLoading || !prismaDocument || !primaryVersion || !teamId) {+ return (+ <AppLayout>+ <main className="relative mx-2 mb-10 mt-4 space-y-8 px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">+ <div className="flex h-screen items-center justify-center">+ <LoadingSpinner className="mr-1 h-20 w-20" />+ </div>+ </main>+ </AppLayout>+ );+ }++ return (+ <AppLayout>+ <main className="relative mx-2 mb-10 mt-4 space-y-8 px-1 sm:mx-3 md:mx-5 md:mt-5 lg:mx-7 lg:mt-8 xl:mx-10">+ {/* Action Header - Shows immediately */}+ <DocumentHeader+ primaryVersion={primaryVersion}+ prismaDocument={prismaDocument}+ teamId={teamId}+ dataroomId={dataroomId}+ dataroomDocumentId={dataroomDocumentId}+ actions={[+ // Jump to the team-wide document page. Hidden from data room+ // members (who have no access to the team-wide document surface).+ ...(!isDataroomMember+ ? [+ <Button+ key={"open-in-documents"}+ asChild+ variant="outline"+ size="default"+ className="h-8 whitespace-nowrap text-xs lg:h-9 lg:text-sm"+ >+ <Link+ href={`/documents/${prismaDocument.id}`}+ target="_blank"+ >+ <ExternalLinkIcon className="size-4" />+ Open in All Documents+ </Link>+ </Button>,+ ]+ : []),+ <NotionAccessibilityIndicator+ key={"notion-status"}+ documentId={prismaDocument.id}+ primaryVersion={primaryVersion}+ onUrlUpdate={mutateDocument}+ />,+ <LinkDocumentIndicator+ key={"link-status"}+ documentId={prismaDocument.id}+ primaryVersion={primaryVersion}+ onUrlUpdate={mutateDocument}+ />,+ <DocumentPreviewButton+ key={"preview"}+ documentId={prismaDocument.id}+ primaryVersion={primaryVersion}+ advancedExcelEnabled={prismaDocument.advancedExcelEnabled}+ variant="outline"+ size="default"+ showTooltip+ className="h-8 whitespace-nowrap text-xs lg:h-9 lg:text-sm"+ />,+ ]}+ />++ <Suspense+ fallback={+ <div className="h-48 animate-pulse rounded-lg bg-gray-100" />+ }+ >+ <>+ {/* Document Analytics — scoped to this data room's visits */}+ {primaryVersion.type !== "video" && (+ <StatsComponent+ documentId={prismaDocument.id}+ numPages={primaryVersion.numPages ?? 1}+ dataroomId={dataroomId}+ />+ )}++ {/* Video Analytics */}+ {primaryVersion.type === "video" && (+ <VideoAnalytics+ documentId={prismaDocument.id}+ primaryVersion={primaryVersion}+ teamId={teamId}+ />+ )}++ {/* Data room visitors — the primary list for this page */}+ <VisitorsTable+ primaryVersion={primaryVersion}+ isVideo={primaryVersion.type === "video"}+ documentId={prismaDocument.id}+ dataroomId={dataroomId}+ viewScope="dataroom"+ title="Data room visitors"+ emptyMessage="No data room visits yet. Try sharing this data room."+ />++ {/* A small count of direct document-link visits. Shown to full team+ members only; the "Open in documents" button above is the path+ to the full breakdown. Hidden from data room-scoped members. */}+ {!isDataroomMember && otherViewCount > 0 ? (+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-sm text-muted-foreground">+ <Badge variant="outline" className="text-muted-foreground">+ {otherViewCount}+ </Badge>+ <span>+ other {otherViewCount === 1 ? "visit" : "visits"} came from+ the document's direct link.{" "}+ <Link+ href={`/documents/${prismaDocument.id}`}+ className="font-medium text-foreground underline-offset-4 hover:underline"+ target="_blank"+ >+ Open in All Documents+ </Link>{" "}+ to view {otherViewCount === 1 ? "it" : "them"}.+ </span>+ </div>+ ) : null}+ </>+ </Suspense>+ </main>+ </AppLayout>+ );+}diff --git a/pages/datarooms/[id]/settings/index.tsx b/pages/datarooms/[id]/settings/index.tsxindex 52e2e949..6d1a2e91 100644--- a/pages/datarooms/[id]/settings/index.tsx+++ b/pages/datarooms/[id]/settings/index.tsx@@ -6,6 +6,7 @@ import { Check, CircleHelpIcon, Copy } from "lucide-react";import { toast } from "sonner";import { mutate } from "swr";+import { useSelfMembership } from "@/lib/hooks/use-self-membership";import { useDataroom } from "@/lib/swr/use-dataroom";import DataroomTagSection from "@/components/datarooms/settings/dataroom-tag-section";@@ -28,6 +29,7 @@ export default function Settings() {const { dataroom } = useDataroom();const teamInfo = useTeam();const teamId = teamInfo?.currentTeam?.id;+ const { isDataroomMember } = useSelfMembership();const [isCopied, setIsCopied] = useState(false);if (!dataroom) {@@ -168,7 +170,9 @@ export default function Settings() {vectorStoreId={dataroom.vectorStoreId}/>- <DuplicateDataroom dataroomId={dataroom.id} teamId={teamId} />+ {!isDataroomMember && (+ <DuplicateDataroom dataroomId={dataroom.id} teamId={teamId} />+ )}<Card className="bg-transparent"><CardHeader><CardTitle>Dataroom ID</CardTitle>diff --git a/pages/datarooms/index.tsx b/pages/datarooms/index.tsxindex 77b48c39..16563418 100644--- a/pages/datarooms/index.tsx+++ b/pages/datarooms/index.tsx@@ -8,6 +8,7 @@ import { PlanEnum } from "@/ee/stripe/constants";import { FilterIcon, PlusIcon } from "lucide-react";import { useQueryState } from "nuqs";+import { useSelfMembership } from "@/lib/hooks/use-self-membership";import { usePlan } from "@/lib/swr/use-billing";import useDatarooms from "@/lib/swr/use-datarooms";import useLimits from "@/lib/swr/use-limits";@@ -40,6 +41,9 @@ export default function DataroomsPage() {const { limits } = useLimits();const router = useRouter();+ // Dataroom-scoped members cannot create datarooms; hide the creation controls.+ const { isDataroomMember } = useSelfMembership();+const [tagsFilter, setTagsFilter] = useQueryState<string[]>("tags", {parse: (value: string) => value.split(",").filter(Boolean),serialize: (value: string[]) => value.join(","),@@ -68,25 +72,32 @@ export default function DataroomsPage() {return a.name.localeCompare(b.name);});- // Filter out only dataroom tags- const dataroomTags = useMemo(() => {- if (!availableTags) return [];- return availableTags;- }, [availableTags]);+ const selectedTagValues = useMemo(() => {+ return tagsFilter || [];+ }, [tagsFilter]);++ // Only surface tags that are actually applied to a dataroom the user can see.+ // Team tags that aren't attached to any visible dataroom would never match a+ // filter, so showing them is just noise (and leaks unrelated tags to+ // dataroom-scoped members). Selected tags are always kept so an active filter+ // doesn't vanish when it narrows the result set.+ const visibleTagNames = useMemo(() => {+ const names = new Set<string>(selectedTagValues);+ (datarooms ?? []).forEach((dataroom) => {+ dataroom.tags?.forEach((tagItem) => names.add(tagItem.tag.name));+ });+ return names;+ }, [datarooms, selectedTagValues]);const tagOptions = useMemo(() => {- return (- dataroomTags?.map((tag) => ({+ return (availableTags ?? [])+ .filter((tag) => visibleTagNames.has(tag.name))+ .map((tag) => ({value: tag.name,label: tag.name,meta: { color: tag.color, description: tag.description },- })) || []- );- }, [dataroomTags]);-- const selectedTagValues = useMemo(() => {- return tagsFilter || [];- }, [tagsFilter]);+ }));+ }, [availableTags, visibleTagNames]);const hasActiveFilters = searchQuery || tagsFilter?.length;@@ -107,7 +118,8 @@ export default function DataroomsPage() {</p></div><div className="flex items-center gap-x-1">- {isBusiness && !canCreateUnlimitedDatarooms ? (+ {isDataroomMember ? null : isBusiness &&+ !canCreateUnlimitedDatarooms ? (<UpgradePlanModalclickedPlan={PlanEnum.DataRooms}trigger="datarooms"@@ -116,7 +128,9 @@ export default function DataroomsPage() {className="group flex flex-1 items-center justify-start gap-x-1 whitespace-nowrap px-2 text-left sm:gap-x-3 sm:px-3"title="Upgrade to Add Data Room">- <span className="text-xs sm:text-sm">Upgrade to Add Data Room</span>+ <span className="text-xs sm:text-sm">+ Upgrade to Add Data Room+ </span></Button></UpgradePlanModal>) : isTrial &&@@ -153,7 +167,10 @@ export default function DataroomsPage() {className="group flex flex-1 items-center justify-start gap-x-1 whitespace-nowrap px-2 text-left sm:gap-x-3 sm:px-3"title="Create New Dataroom">- <PlusIcon className="h-5 w-5 shrink-0" aria-hidden="true" />+ <PlusIcon+ className="h-5 w-5 shrink-0"+ aria-hidden="true"+ /><span className="text-xs sm:text-sm">New Dataroom</span></Button></AddDataroomModal>diff --git a/pages/settings/people.tsx b/pages/settings/people.tsxindex 16ffb1ca..69faa264 100644--- a/pages/settings/people.tsx+++ b/pages/settings/people.tsx@@ -10,11 +10,13 @@ import { mutate } from "swr";import { useAnalytics } from "@/lib/analytics";import { usePlan } from "@/lib/swr/use-billing";+import useDataroomsSimple from "@/lib/swr/use-datarooms-simple";import { useInvitations } from "@/lib/swr/use-invitations";import useLimits from "@/lib/swr/use-limits";import { useGetTeam } from "@/lib/swr/use-team";import { useTeams } from "@/lib/swr/use-teams";-import { CustomUser } from "@/lib/types";+import { CustomUser, TeamRole } from "@/lib/types";+import { cn } from "@/lib/utils";import { AddSeatModal } from "@/components/billing/add-seat-modal";import { UnlimitedPlanModal } from "@/components/billing/unlimited-plan-modal";@@ -24,6 +26,14 @@ import Folder from "@/components/shared/icons/folder";import MoreVertical from "@/components/shared/icons/more-vertical";import { AddTeamMembers } from "@/components/teams/add-team-member-modal";import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";import {DropdownMenu,DropdownMenuContent,@@ -31,9 +41,36 @@ import {DropdownMenuLabel,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";+import { Label } from "@/components/ui/label";+import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";import { Skeleton } from "@/components/ui/skeleton";import { UpgradeButton } from "@/components/ui/upgrade-button";+const ROLE_LABELS: Record<TeamRole, string> = {+ ADMIN: "Admin",+ MANAGER: "Manager",+ MEMBER: "Member",+ DATAROOM_MEMBER: "Data Room Member",+};++const ROLE_DESCRIPTIONS: Record<TeamRole, string> = {+ ADMIN: "Full access to the team, billing, and all settings.",+ MANAGER: "Manage content and members, except admin-only settings.",+ MEMBER: "Create and manage documents, links, and data rooms.",+ DATAROOM_MEMBER: "Access limited to the specific data rooms you assign.",+};++const ASSIGNABLE_ROLES: TeamRole[] = [+ "ADMIN",+ "MANAGER",+ "MEMBER",+ "DATAROOM_MEMBER",+];++function formatRole(role: string): string {+ return ROLE_LABELS[role as TeamRole] ?? role;+}+export default function Billing() {const [isTeamMemberInviteModalOpen, setTeamMemberInviteModalOpen] =useState<boolean>(false);@@ -84,10 +121,19 @@ export default function Billing() {);};+ // Member currently being edited in the change-role dialog.+ const [roleMember, setRoleMember] = useState<{+ userId: string;+ teamId: string;+ name: string;+ role: TeamRole;+ } | null>(null);+const changeRole = async (teamId: string,userId: string,- role: "ADMIN" | "MANAGER" | "MEMBER",+ role: "ADMIN" | "MANAGER" | "MEMBER" | "DATAROOM_MEMBER",+ dataroomIds?: string[],) => {const response = await fetch(`/api/teams/${teamId}/change-role`, {method: "PUT",@@ -97,6 +143,9 @@ export default function Billing() {body: JSON.stringify({userToBeChanged: userId,role: role,+ ...(role === "DATAROOM_MEMBER"+ ? { dataroomIds: dataroomIds ?? [] }+ : {}),}),});@@ -254,11 +303,13 @@ export default function Billing() {<h2 className="text-xl font-medium">Team</h2><p className="text-sm text-secondary-foreground">Teammates that have access to this project.- {!isDataroomsUnlimited && limits?.users && limits.users !== Infinity && (- <span className="ml-1">- ({limits.usage?.users ?? 0}/{limits.users} seats used)- </span>- )}+ {!isDataroomsUnlimited &&+ limits?.users &&+ limits.users !== Infinity && (+ <span className="ml-1">+ ({limits.usage?.users ?? 0}/{limits.users} seats used)+ </span>+ )}</p></div>{showUpgradePlanModal ? (@@ -341,8 +392,8 @@ export default function Billing() {</div><div className="flex items-center gap-12"><div className="flex flex-col items-end gap-1">- <span className="text-sm capitalize text-foreground">- {member.role.toLowerCase()}+ <span className="text-sm text-foreground">+ {formatRole(member.role)}</span>{member.status === "BLOCKED_TRIAL_EXPIRED" && (<span className="text-xs font-medium text-red-500">@@ -375,48 +426,19 @@ export default function Billing() {{isCurrentUserAdmin() &&!isCurrentUser(member.userId) ? (<>- {member.role !== "ADMIN" && (- <DropdownMenuItem- onClick={() =>- changeRole(- member.teamId,- member.userId,- "ADMIN",- )- }- className="hover:cursor-pointer"- >- Change role to ADMIN- </DropdownMenuItem>- )}- {member.role !== "MANAGER" && (- <DropdownMenuItem- onClick={() =>- changeRole(- member.teamId,- member.userId,- "MANAGER",- )- }- className="hover:cursor-pointer"- >- Change role to MANAGER- </DropdownMenuItem>- )}- {member.role !== "MEMBER" && (- <DropdownMenuItem- onClick={() =>- changeRole(- member.teamId,- member.userId,- "MEMBER",- )- }- className="hover:cursor-pointer"- >- Change role to MEMBER- </DropdownMenuItem>- )}+ <DropdownMenuItem+ onClick={() =>+ setRoleMember({+ userId: member.userId,+ teamId: member.teamId,+ name: member.user.name || member.user.email,+ role: member.role,+ })+ }+ className="hover:cursor-pointer"+ >+ Change role+ </DropdownMenuItem><DropdownMenuItemonClick={() =>removeTeammate(member.teamId, member.userId)@@ -497,6 +519,151 @@ export default function Billing() {</ul></div></main>++ {roleMember ? (+ <ChangeRoleDialog+ member={roleMember}+ currentAssignments={(team?.userDatarooms ?? [])+ .filter((ud) => ud.userId === roleMember.userId)+ .map((ud) => ud.dataroomId)}+ onClose={() => setRoleMember(null)}+ onSave={async (role, dataroomIds) => {+ await changeRole(+ roleMember.teamId,+ roleMember.userId,+ role,+ dataroomIds,+ );+ setRoleMember(null);+ }}+ />+ ) : null}</AppLayout>);}++function ChangeRoleDialog({+ member,+ currentAssignments,+ onClose,+ onSave,+}: {+ member: { userId: string; teamId: string; name: string; role: TeamRole };+ currentAssignments: string[];+ onClose: () => void;+ onSave: (role: TeamRole, dataroomIds: string[]) => Promise<void>;+}) {+ const { datarooms } = useDataroomsSimple();+ const [role, setRole] = useState<TeamRole>(member.role);+ const [selected, setSelected] = useState<string[]>(currentAssignments);+ const [saving, setSaving] = useState(false);++ const toggle = (id: string) => {+ setSelected((prev) =>+ prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id],+ );+ };++ const assignmentsUnchanged =+ selected.length === currentAssignments.length &&+ selected.every((id) => currentAssignments.includes(id));++ const isUnchanged =+ role === member.role &&+ (role !== "DATAROOM_MEMBER" || assignmentsUnchanged);++ const canSave =+ !saving &&+ !isUnchanged &&+ (role !== "DATAROOM_MEMBER" || selected.length > 0);++ return (+ <Dialog open onOpenChange={(open) => !open && onClose()}>+ <DialogContent className="sm:max-w-[425px]">+ <DialogHeader className="text-start">+ <DialogTitle>Change role</DialogTitle>+ <DialogDescription>+ Update the role for {member.name}.+ </DialogDescription>+ </DialogHeader>++ <RadioGroup+ value={role}+ onValueChange={(value) => setRole(value as TeamRole)}+ className="gap-2"+ >+ {ASSIGNABLE_ROLES.map((r) => (+ <label+ key={r}+ htmlFor={`role-${r}`}+ className={cn(+ "flex cursor-pointer items-start gap-3 rounded-md border p-3 text-sm transition-colors",+ role === r+ ? "border-primary bg-muted"+ : "border-border hover:bg-muted/50",+ )}+ >+ <RadioGroupItem id={`role-${r}`} value={r} className="mt-0.5" />+ <div className="space-y-0.5">+ <p className="font-medium leading-none">{ROLE_LABELS[r]}</p>+ <p className="text-xs text-muted-foreground">+ {ROLE_DESCRIPTIONS[r]}+ </p>+ </div>+ </label>+ ))}+ </RadioGroup>++ {role === "DATAROOM_MEMBER" ? (+ <div className="space-y-1">+ <Label className="opacity-80">Data rooms</Label>+ <p className="text-xs text-muted-foreground">+ Select the data rooms {member.name} can manage.+ </p>+ <div className="mt-1 max-h-44 space-y-1 overflow-y-auto rounded-md border p-2">+ {datarooms && datarooms.length > 0 ? (+ datarooms.map((dataroom) => (+ <label+ key={dataroom.id}+ className="flex cursor-pointer items-center gap-2 rounded px-2 py-1 text-sm hover:bg-muted"+ >+ <input+ type="checkbox"+ checked={selected.includes(dataroom.id)}+ onChange={() => toggle(dataroom.id)}+ />+ <span className="truncate">+ {dataroom.internalName || dataroom.name}+ </span>+ </label>+ ))+ ) : (+ <p className="px-2 py-1 text-sm text-muted-foreground">+ No data rooms available.+ </p>+ )}+ </div>+ </div>+ ) : null}++ <DialogFooter>+ <Button+ type="button"+ disabled={!canSave}+ onClick={async () => {+ setSaving(true);+ try {+ await onSave(role, role === "DATAROOM_MEMBER" ? selected : []);+ } finally {+ setSaving(false);+ }+ }}+ className="h-9 w-full"+ >+ {saving ? "Saving..." : "Save changes"}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}diff --git a/prisma/migrations/20260610154707_add_dataroom_member_role_and_user_dataroom/migration.sql b/prisma/migrations/20260610154707_add_dataroom_member_role_and_user_dataroom/migration.sqlnew file mode 100644index 00000000..44a886f2--- /dev/null+++ b/prisma/migrations/20260610154707_add_dataroom_member_role_and_user_dataroom/migration.sql@@ -0,0 +1,34 @@+-- AlterEnum+ALTER TYPE "Role" ADD VALUE 'DATAROOM_MEMBER';++-- AlterTable+ALTER TABLE "Invitation" ADD COLUMN "dataroomIds" TEXT[] DEFAULT ARRAY[]::TEXT[],+ADD COLUMN "role" "Role" NOT NULL DEFAULT 'MEMBER';++-- CreateTable+CREATE TABLE "UserDataroom" (+ "userId" TEXT NOT NULL,+ "teamId" TEXT NOT NULL,+ "dataroomId" TEXT NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,++ CONSTRAINT "UserDataroom_pkey" PRIMARY KEY ("userId","dataroomId")+);++-- CreateIndex+CREATE INDEX "UserDataroom_userId_idx" ON "UserDataroom"("userId");++-- CreateIndex+CREATE INDEX "UserDataroom_teamId_idx" ON "UserDataroom"("teamId");++-- CreateIndex+CREATE INDEX "UserDataroom_dataroomId_idx" ON "UserDataroom"("dataroomId");++-- AddForeignKey+ALTER TABLE "UserDataroom" ADD CONSTRAINT "UserDataroom_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "UserDataroom" ADD CONSTRAINT "UserDataroom_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "UserDataroom" ADD CONSTRAINT "UserDataroom_dataroomId_fkey" FOREIGN KEY ("dataroomId") REFERENCES "Dataroom"("id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/prisma/migrations/migration_lock.toml b/prisma/migrations/migration_lock.tomlindex fbffa92c..648c57fd 100644--- a/prisma/migrations/migration_lock.toml+++ b/prisma/migrations/migration_lock.toml@@ -1,3 +1,3 @@# Please do not edit this file manually-# It should be added in your version-control system (i.e. Git)+# It should be added in your version-control system (e.g., Git)provider = "postgresql"\ No newline at end of filediff --git a/prisma/schema/dataroom.prisma b/prisma/schema/dataroom.prismaindex 4cda4891..34137086 100644--- a/prisma/schema/dataroom.prisma+++ b/prisma/schema/dataroom.prisma@@ -14,6 +14,9 @@ model Dataroom {viewerGroups ViewerGroup[]brand DataroomBrand?+ // Internal team members scoped to this dataroom (DATAROOM_MEMBER role).+ userDatarooms UserDataroom[]+permissionGroups PermissionGroup[]// conversationdiff --git a/prisma/schema/schema.prisma b/prisma/schema/schema.prismaindex f5e49771..b6e55ba3 100644--- a/prisma/schema/schema.prisma+++ b/prisma/schema/schema.prisma@@ -48,6 +48,7 @@ model User {sessions Session[]documents Document[]teams UserTeam[]+ userDatarooms UserDataroom[]domains Domain[]chats Chat[]contactId String?@@ -252,6 +253,13 @@ model Invitation {createdAt DateTime @default(now())token String @unique+ // Role the invitee will be assigned on acceptance. Defaults to MEMBER to+ // preserve historic behaviour for invitations created before this column.+ role Role @default(MEMBER)+ // Datarooms the invitee is scoped to, applied as UserDataroom rows on+ // acceptance. Only meaningful when role == DATAROOM_MEMBER.+ dataroomIds String[] @default([])+@@unique([email, teamId])}diff --git a/prisma/schema/team.prisma b/prisma/schema/team.prismaindex b036472f..2c88a7ae 100644--- a/prisma/schema/team.prisma+++ b/prisma/schema/team.prisma@@ -3,6 +3,7 @@ model Team {name Stringslug String? @unique // Optional human-readable identifier (e.g. "acme"), used for SSO loginusers UserTeam[]+ userDatarooms UserDataroom[]documents Document[]folders Folder[]domains Domain[]@@ -83,6 +84,26 @@ enum Role {ADMINMANAGERMEMBER+ // Least-privileged role. Scoped to one or more datarooms via UserDataroom and+ // acts as a room manager inside only those rooms. Denied everywhere else.+ DATAROOM_MEMBER+}++// Assigns a DATAROOM_MEMBER (or any user) to a specific dataroom within a team.+// This is the "which rooms" layer that the role alone cannot encode.+model UserDataroom {+ userId String+ teamId String+ dataroomId String+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)+ dataroom Dataroom @relation(fields: [dataroomId], references: [id], onDelete: Cascade)+ createdAt DateTime @default(now())++ @@id([userId, dataroomId])+ @@index([userId])+ @@index([teamId])+ @@index([dataroomId])}model UserTeam {