Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat: improve file permissions

Marc Seitzea69481d81cc
diff --git a/components/datarooms/settings/permission-settings.tsx b/components/datarooms/settings/permission-settings.tsx
index d6292bf3..85582878 100644
--- a/components/datarooms/settings/permission-settings.tsx
+++ b/components/datarooms/settings/permission-settings.tsx
@@ -22,9 +22,13 @@ type DefaultPermissionStrategy =
| "ASK_EVERY_TIME"
| "HIDDEN_BY_DEFAULT";
+type RootItemAccess = "VIEW_ONLY" | "VIEW_AND_DOWNLOAD" | "HIDDEN";
+
type PermissionField =
| "defaultPermissionStrategy"
- | "defaultGroupPermissionStrategy";
+ | "defaultGroupPermissionStrategy"
+ | "defaultRootItemAccess"
+ | "defaultGroupRootItemAccess";
interface DataroomPermissionData {
id: string;
@@ -32,22 +36,26 @@ interface DataroomPermissionData {
pId: string;
defaultPermissionStrategy: DefaultPermissionStrategy;
defaultGroupPermissionStrategy: DefaultPermissionStrategy;
+ defaultRootItemAccess: RootItemAccess;
+ defaultGroupRootItemAccess: RootItemAccess;
}
interface PermissionSettingsProps {
dataroomId: string;
}
-const STRATEGY_OPTIONS: {
- value: DefaultPermissionStrategy;
+type SettingOption = {
+ value: string;
label: string;
description: string;
-}[] = [
+};
+
+const STRATEGY_OPTIONS: SettingOption[] = [
{
value: "INHERIT_FROM_PARENT",
label: "Inherit from parent folder",
description:
- "New documents and folders inherit permissions from their parent folder. Root-level items get view-only by default.",
+ "New documents and folders inherit permissions from the folder they are placed in. Root-level items use the root-level access setting below.",
},
{
value: "ASK_EVERY_TIME",
@@ -63,11 +71,34 @@ const STRATEGY_OPTIONS: {
},
];
-const SCOPES: {
+const ROOT_ACCESS_OPTIONS: SettingOption[] = [
+ {
+ value: "VIEW_ONLY",
+ label: "View only",
+ description:
+ "Root-level documents and folders become viewable (not downloadable) for every group.",
+ },
+ {
+ value: "VIEW_AND_DOWNLOAD",
+ label: "View and download",
+ description:
+ "Root-level documents and folders become viewable and downloadable for every group.",
+ },
+ {
+ value: "HIDDEN",
+ label: "Hidden",
+ description:
+ "Root-level documents and folders stay hidden until access is granted manually.",
+ },
+];
+
+type Scope = {
key: PermissionField;
label: string;
icon: React.ComponentType<{ className?: string }>;
-}[] = [
+};
+
+const STRATEGY_SCOPES: Scope[] = [
{
key: "defaultGroupPermissionStrategy",
label: "Groups",
@@ -80,6 +111,19 @@ const SCOPES: {
},
];
+const ROOT_ACCESS_SCOPES: Scope[] = [
+ {
+ key: "defaultGroupRootItemAccess",
+ label: "Groups",
+ icon: UsersIcon,
+ },
+ {
+ key: "defaultRootItemAccess",
+ label: "Links",
+ icon: LinkIcon,
+ },
+];
+
export default function PermissionSettings({
dataroomId,
}: PermissionSettingsProps) {
@@ -100,7 +144,7 @@ export default function PermissionSettings({
const handlePermissionChange = async (
field: PermissionField,
- value: DefaultPermissionStrategy,
+ value: string,
) => {
if (!dataroomId || !teamId || updatingField || !dataroomData) return;
setUpdatingField(field);
@@ -145,79 +189,124 @@ export default function PermissionSettings({
}
};
- const values: Record<PermissionField, DefaultPermissionStrategy> = {
+ const values: Record<PermissionField, string> = {
defaultGroupPermissionStrategy:
dataroomData?.defaultGroupPermissionStrategy ?? "INHERIT_FROM_PARENT",
defaultPermissionStrategy:
dataroomData?.defaultPermissionStrategy ?? "INHERIT_FROM_PARENT",
+ defaultGroupRootItemAccess:
+ dataroomData?.defaultGroupRootItemAccess ?? "VIEW_ONLY",
+ defaultRootItemAccess: dataroomData?.defaultRootItemAccess ?? "VIEW_ONLY",
};
const disabled = updatingField !== null || !dataroomData;
return (
- <Card>
- <CardHeader>
- <CardTitle>Default File Permissions</CardTitle>
- <CardDescription>
- Configure how new documents and folders are exposed to groups and
- links. Each scope is set independently.
- </CardDescription>
- </CardHeader>
- <CardContent>
- <div className="grid grid-cols-[1fr_auto] gap-x-8 gap-y-1">
- <div />
- <div className="flex items-center gap-1">
- {SCOPES.map((scope) => (
- <div
- key={scope.key}
- className="flex w-20 items-center justify-center gap-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground"
- >
- <scope.icon className="h-3 w-3" />
- {scope.label}
- </div>
- ))}
+ <div className="space-y-6">
+ <Card>
+ <CardHeader>
+ <CardTitle>Default File Permissions</CardTitle>
+ <CardDescription>
+ Configure how new documents and folders are exposed to groups and
+ links. Each scope is set independently.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <SettingsMatrix
+ options={STRATEGY_OPTIONS}
+ scopes={STRATEGY_SCOPES}
+ values={values}
+ disabled={disabled}
+ onChange={handlePermissionChange}
+ />
+ </CardContent>
+ </Card>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>Root-Level Item Access</CardTitle>
+ <CardDescription>
+ Items created at the top level of the dataroom have no parent folder
+ to inherit from. Choose what access groups and links get on new
+ root-level documents and folders when the strategy is &quot;Inherit
+ from parent folder&quot;.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <SettingsMatrix
+ options={ROOT_ACCESS_OPTIONS}
+ scopes={ROOT_ACCESS_SCOPES}
+ values={values}
+ disabled={disabled}
+ onChange={handlePermissionChange}
+ />
+ </CardContent>
+ </Card>
+ </div>
+ );
+}
+
+function SettingsMatrix({
+ options,
+ scopes,
+ values,
+ disabled,
+ onChange,
+}: {
+ options: SettingOption[];
+ scopes: Scope[];
+ values: Record<PermissionField, string>;
+ disabled: boolean;
+ onChange: (field: PermissionField, value: string) => void;
+}) {
+ return (
+ <div className="grid grid-cols-[1fr_auto] gap-x-8 gap-y-1">
+ <div />
+ <div className="flex items-center gap-1">
+ {scopes.map((scope) => (
+ <div
+ key={scope.key}
+ className="flex w-20 items-center justify-center gap-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground"
+ >
+ <scope.icon className="h-3 w-3" />
+ {scope.label}
</div>
+ ))}
+ </div>
- {STRATEGY_OPTIONS.map((option, index) => (
- <StrategyRow
- key={option.value}
- option={option}
- values={values}
- disabled={disabled}
- isFirst={index === 0}
- onChange={handlePermissionChange}
- />
- ))}
- </div>
- </CardContent>
- </Card>
+ {options.map((option, index) => (
+ <SettingRow
+ key={option.value}
+ option={option}
+ scopes={scopes}
+ values={values}
+ disabled={disabled}
+ isFirst={index === 0}
+ onChange={onChange}
+ />
+ ))}
+ </div>
);
}
-function StrategyRow({
+function SettingRow({
option,
+ scopes,
values,
disabled,
isFirst,
onChange,
}: {
- option: (typeof STRATEGY_OPTIONS)[number];
- values: Record<PermissionField, DefaultPermissionStrategy>;
+ option: SettingOption;
+ scopes: Scope[];
+ values: Record<PermissionField, string>;
disabled: boolean;
isFirst: boolean;
- onChange: (
- field: PermissionField,
- value: DefaultPermissionStrategy,
- ) => void;
+ onChange: (field: PermissionField, value: string) => void;
}) {
return (
<>
- <div
- className={cn(
- "py-3",
- !isFirst && "border-t border-border/60",
- )}
- >
+ <div className={cn("py-3", !isFirst && "border-t border-border/60")}>
<Label
htmlFor={`group-${option.value}`}
className="text-sm font-medium"
@@ -234,16 +323,14 @@ function StrategyRow({
!isFirst && "border-t border-border/60",
)}
>
- {SCOPES.map((scope) => (
+ {scopes.map((scope) => (
<div
key={scope.key}
className="flex w-20 items-center justify-center"
>
<RadioGroup
value={values[scope.key]}
- onValueChange={(value) =>
- onChange(scope.key, value as DefaultPermissionStrategy)
- }
+ onValueChange={(value) => onChange(scope.key, value)}
disabled={disabled}
aria-label={`${scope.label} default`}
>
diff --git a/lib/dataroom/root-item-access.ts b/lib/dataroom/root-item-access.ts
new file mode 100644
index 00000000..3da3bbeb
--- /dev/null
+++ b/lib/dataroom/root-item-access.ts
@@ -0,0 +1,24 @@
+import { RootItemAccess } from "@prisma/client";
+
+/**
+ * Maps a dataroom's root-item access setting to the ACL flags written for a
+ * newly created root-level item under INHERIT_FROM_PARENT. Returns `null` for
+ * HIDDEN, meaning no access-control row should be created at all (absence of
+ * a row is how "not visible" is represented for group-restricted links).
+ */
+export function resolveRootItemAccessFlags(
+ access: RootItemAccess,
+): { canView: boolean; canDownload: boolean } | null {
+ switch (access) {
+ case RootItemAccess.VIEW_ONLY:
+ return { canView: true, canDownload: false };
+ case RootItemAccess.VIEW_AND_DOWNLOAD:
+ return { canView: true, canDownload: true };
+ case RootItemAccess.HIDDEN:
+ return null;
+ default: {
+ const _exhaustive: never = access;
+ throw new Error(`Unhandled root item access: ${_exhaustive}`);
+ }
+ }
+}
diff --git a/lib/folders/bulk-create.ts b/lib/folders/bulk-create.ts
index 3a6a77b8..39e2377b 100644
--- a/lib/folders/bulk-create.ts
+++ b/lib/folders/bulk-create.ts
@@ -1,5 +1,6 @@
import { DefaultPermissionStrategy, ItemType, Prisma } from "@prisma/client";
+import { resolveRootItemAccessFlags } from "@/lib/dataroom/root-item-access";
import { safeSlugify } from "@/lib/utils";
/**
@@ -54,9 +55,7 @@ async function withUniqueConstraintRetry<T>(args: {
await tx.$executeRawUnsafe(`RELEASE SAVEPOINT "${savepointName}"`);
return result;
} catch (error) {
- await tx.$executeRawUnsafe(
- `ROLLBACK TO SAVEPOINT "${savepointName}"`,
- );
+ await tx.$executeRawUnsafe(`ROLLBACK TO SAVEPOINT "${savepointName}"`);
await tx.$executeRawUnsafe(`RELEASE SAVEPOINT "${savepointName}"`);
if (
@@ -103,7 +102,10 @@ export interface BulkFolderResult {
}
class BulkValidationError extends Error {
- constructor(public readonly code: string, message: string) {
+ constructor(
+ public readonly code: string,
+ message: string,
+ ) {
super(message);
this.name = "BulkValidationError";
}
@@ -148,13 +150,22 @@ function buildLevels(folders: BulkFolderInput[]): BulkFolderInput[][] {
const byId = new Map<string, BulkFolderInput>();
for (const f of folders) {
if (!f.tempId) {
- throw new BulkValidationError("MISSING_TEMP_ID", "Each folder needs a tempId");
+ throw new BulkValidationError(
+ "MISSING_TEMP_ID",
+ "Each folder needs a tempId",
+ );
}
if (!f.name || f.name.trim() === "") {
- throw new BulkValidationError("EMPTY_NAME", `Folder ${f.tempId} has an empty name`);
+ throw new BulkValidationError(
+ "EMPTY_NAME",
+ `Folder ${f.tempId} has an empty name`,
+ );
}
if (byId.has(f.tempId)) {
- throw new BulkValidationError("DUPLICATE_TEMP_ID", `Duplicate tempId: ${f.tempId}`);
+ throw new BulkValidationError(
+ "DUPLICATE_TEMP_ID",
+ `Duplicate tempId: ${f.tempId}`,
+ );
}
byId.set(f.tempId, f);
}
@@ -240,9 +251,7 @@ function resolveParentId(
*/
async function resolveExternalParentPaths(
folders: BulkFolderInput[],
- findRows: (
- paths: string[],
- ) => Promise<{ id: string; path: string }[]>,
+ findRows: (paths: string[]) => Promise<{ id: string; path: string }[]>,
): Promise<Map<string, string>> {
const paths = new Set<string>();
for (const f of folders) {
@@ -279,7 +288,12 @@ async function resolveLevelPaths(args: {
const { level, parentPathOf, findExisting } = args;
if (level.length === 0) return new Map();
- const candidatesPerFolder: { tempId: string; name: string; basePath: string; candidates: string[] }[] = [];
+ const candidatesPerFolder: {
+ tempId: string;
+ name: string;
+ basePath: string;
+ candidates: string[];
+ }[] = [];
const allCandidates = new Set<string>();
for (const f of level) {
@@ -290,7 +304,12 @@ async function resolveLevelPaths(args: {
for (let i = 1; i <= MAX_SLUG_SUFFIX; i++) {
candidates.push(basePath + safeSlugify(`${f.name} (${i})`));
}
- candidatesPerFolder.push({ tempId: f.tempId, name: f.name, basePath, candidates });
+ candidatesPerFolder.push({
+ tempId: f.tempId,
+ name: f.name,
+ basePath,
+ candidates,
+ });
for (const c of candidates) allCandidates.add(c);
}
@@ -570,6 +589,8 @@ async function applyDefaultPermissionsBulk(args: {
select: {
defaultPermissionStrategy: true,
defaultGroupPermissionStrategy: true,
+ defaultRootItemAccess: true,
+ defaultGroupRootItemAccess: true,
},
}),
tx.viewerGroup.findMany({
@@ -625,15 +646,24 @@ async function applyDefaultPermissionsBulk(args: {
),
]);
+ const groupRootFlags = resolveRootItemAccessFlags(
+ dataroom.defaultGroupRootItemAccess,
+ );
+ const linkRootFlags = resolveRootItemAccessFlags(
+ dataroom.defaultRootItemAccess,
+ );
+
// Viewer-group ACLs.
if (groupInherits && viewerGroups.length > 0) {
const sourcePerms = rootParentId
? parentViewerPerms
- : viewerGroups.map((g) => ({
- groupId: g.id,
- canView: true,
- canDownload: false,
- }));
+ : groupRootFlags
+ ? viewerGroups.map((g) => ({
+ groupId: g.id,
+ canView: groupRootFlags.canView,
+ canDownload: groupRootFlags.canDownload,
+ }))
+ : [];
if (sourcePerms.length > 0) {
const data = newFolderIds.flatMap((folderId) =>
@@ -658,12 +688,14 @@ async function applyDefaultPermissionsBulk(args: {
if (linkInherits && permissionGroups.length > 0) {
const sourcePerms = rootParentId
? parentLinkPerms
- : permissionGroups.map((g) => ({
- groupId: g.id,
- canView: true,
- canDownload: false,
- canDownloadOriginal: false,
- }));
+ : linkRootFlags
+ ? permissionGroups.map((g) => ({
+ groupId: g.id,
+ canView: linkRootFlags.canView,
+ canDownload: linkRootFlags.canDownload,
+ canDownloadOriginal: false,
+ }))
+ : [];
if (sourcePerms.length > 0) {
const data = newFolderIds.flatMap((folderId) =>
diff --git a/lib/trigger/dataroom-change-notification.ts b/lib/trigger/dataroom-change-notification.ts
index 4dd87b9c..cbd63ca9 100644
--- a/lib/trigger/dataroom-change-notification.ts
+++ b/lib/trigger/dataroom-change-notification.ts
@@ -85,53 +85,109 @@ export const sendDataroomChangeNotificationTask = schemaTask({
return;
}
- const folderAccessCache = new Map<string, boolean>();
+ // Folder → parent map for walking a document's ancestor chain. Viewer-side
+ // visibility (getFilteredDataroomDocumentIds) treats a document as visible
+ // when any ancestor folder grants access, so checking the immediate folder
+ // alone would miss documents nested below the granted folder.
+ const folders = await prisma.dataroomFolder.findMany({
+ where: { dataroomId: payload.dataroomId },
+ select: { id: true, parentId: true },
+ });
+ const folderParentById = new Map<string, string | null>(
+ folders.map((folder) => [folder.id, folder.parentId]),
+ );
- const canViewFolder = async (
+ const accessCache = new Map<string, boolean | null>();
+
+ // Reads one ACL row's canView. Returns null when no row exists so the
+ // caller can distinguish "explicitly denied" from "no explicit grant".
+ const lookupCanView = async (
groupId: string | null | undefined,
permissionGroupId: string | null | undefined,
- folderId: string | null,
- ): Promise<boolean> => {
- if (!groupId && !permissionGroupId) {
- return true;
- }
-
- if (!folderId) {
- return true;
- }
-
+ itemId: string,
+ ): Promise<boolean | null> => {
if (groupId) {
- const cacheKey = `viewer-group:${groupId}:${folderId}`;
- if (folderAccessCache.has(cacheKey)) {
- return folderAccessCache.get(cacheKey)!;
+ const cacheKey = `viewer-group:${groupId}:${itemId}`;
+ if (accessCache.has(cacheKey)) {
+ return accessCache.get(cacheKey)!;
}
const ac = await prisma.viewerGroupAccessControls.findUnique({
where: {
- groupId_itemId: { groupId, itemId: folderId },
+ groupId_itemId: { groupId, itemId },
},
select: { canView: true },
});
- const result = ac?.canView === true;
- folderAccessCache.set(cacheKey, result);
+ const result = ac ? ac.canView : null;
+ accessCache.set(cacheKey, result);
return result;
}
if (permissionGroupId) {
- const cacheKey = `permission-group:${permissionGroupId}:${folderId}`;
- if (folderAccessCache.has(cacheKey)) {
- return folderAccessCache.get(cacheKey)!;
+ const cacheKey = `permission-group:${permissionGroupId}:${itemId}`;
+ if (accessCache.has(cacheKey)) {
+ return accessCache.get(cacheKey)!;
}
const ac = await prisma.permissionGroupAccessControls.findUnique({
where: {
- groupId_itemId: { groupId: permissionGroupId, itemId: folderId },
+ groupId_itemId: { groupId: permissionGroupId, itemId },
},
select: { canView: true },
});
- const result = ac?.canView === true;
- folderAccessCache.set(cacheKey, result);
+ const result = ac ? ac.canView : null;
+ accessCache.set(cacheKey, result);
return result;
}
+ return null;
+ };
+
+ // Mirrors the viewer-side visibility rules: the document's own ACL row
+ // wins (an explicit deny blocks inherited folder access); without a row
+ // the document is visible through a viewable ancestor folder anywhere up
+ // the tree. Previously this gated on the immediate folder alone, which
+ // skipped documents nested below a granted folder.
+ const canViewDocument = async (
+ groupId: string | null | undefined,
+ permissionGroupId: string | null | undefined,
+ doc: { id: string; folderId: string | null },
+ ): Promise<boolean> => {
+ if (!groupId && !permissionGroupId) {
+ return true;
+ }
+
+ const docCanView = await lookupCanView(
+ groupId,
+ permissionGroupId,
+ doc.id,
+ );
+ if (docCanView !== null) {
+ return docCanView;
+ }
+
+ if (!doc.folderId) {
+ // Root-level document without an explicit grant is not visible.
+ return false;
+ }
+
+ // Walk up the ancestor chain: the nearest folder with an explicit ACL
+ // row decides visibility (an explicit deny blocks inherited access from
+ // folders higher up). The visited guard protects against malformed
+ // parent cycles.
+ const visited = new Set<string>();
+ let currentFolderId: string | null = doc.folderId;
+ while (currentFolderId && !visited.has(currentFolderId)) {
+ visited.add(currentFolderId);
+ const folderCanView = await lookupCanView(
+ groupId,
+ permissionGroupId,
+ currentFolderId,
+ );
+ if (folderCanView !== null) {
+ return folderCanView;
+ }
+ currentFolderId = folderParentById.get(currentFolderId) ?? null;
+ }
+
return false;
};
@@ -140,10 +196,10 @@ export const sendDataroomChangeNotificationTask = schemaTask({
// TODO: KNOWN LIMITATION: Only the most recent view (views[0]) is checked for
// folder access. A viewer with multiple verified links may be
// incorrectly skipped if views[0]'s link lacks access but another
- // link in viewer.views does grant it via canViewFolder(). The fix is
- // to iterate over all viewer.views and pick any link where
- // canViewFolder(link.groupId, link.permissionGroupId) returns true
- // for dataroomDocument.folderId before deciding to skip.
+ // link in viewer.views does grant it via canViewDocument(). The fix
+ // is to iterate over all viewer.views and pick any link where
+ // canViewDocument(link.groupId, link.permissionGroupId, doc) returns
+ // true before deciding to skip.
const view = viewer.views[0];
const link = view?.link;
@@ -157,16 +213,16 @@ export const sendDataroomChangeNotificationTask = schemaTask({
const accessibleDocIds: string[] = [];
for (const doc of dataroomDocuments) {
- const hasAccess = await canViewFolder(
+ const hasAccess = await canViewDocument(
link.groupId,
link.permissionGroupId,
- doc.folderId,
+ doc,
);
if (hasAccess) {
accessibleDocIds.push(doc.id);
} else {
logger.info(
- "Skipping document for viewer: link group lacks folder access",
+ "Skipping document for viewer: link group lacks document access",
{
viewerId: viewer.id,
linkId: link.id,
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/apply-permissions.ts b/pages/api/teams/[teamId]/datarooms/[id]/apply-permissions.ts
index a1f7db5e..cf568947 100644
--- a/pages/api/teams/[teamId]/datarooms/[id]/apply-permissions.ts
+++ b/pages/api/teams/[teamId]/datarooms/[id]/apply-permissions.ts
@@ -1,15 +1,26 @@
import { NextApiRequest, NextApiResponse } from "next";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
-import { DefaultPermissionStrategy, ItemType } from "@prisma/client";
+import {
+ DefaultPermissionStrategy,
+ ItemType,
+ RootItemAccess,
+} from "@prisma/client";
import { getServerSession } from "next-auth";
+import { resolveRootItemAccessFlags } from "@/lib/dataroom/root-item-access";
import { errorhandler } from "@/lib/errorHandler";
import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
type GroupTarget = "VIEWER_GROUP" | "PERMISSION_GROUP";
+type DataroomDocumentRef = {
+ id: string;
+ documentId: string;
+ folderId: string | null;
+};
+
const VALID_STRATEGIES = new Set<string>([
"INHERIT_FROM_PARENT",
"ASK_EVERY_TIME",
@@ -22,10 +33,7 @@ async function revalidateLinksForDataroom(dataroomId: string): Promise<void> {
where: {
dataroomId,
deletedAt: null,
- OR: [
- { permissionGroupId: { not: null } },
- { groupId: { not: null } },
- ],
+ OR: [{ permissionGroupId: { not: null } }, { groupId: { not: null } }],
},
select: { id: true, domainId: true },
});
@@ -75,13 +83,9 @@ export default async function handler(
const userId = (session.user as CustomUser).id;
try {
- const {
- documentIds,
- strategy,
- groupStrategy,
- linkStrategy,
- folderPath,
- } = req.body as {
+ // `folderPath` is still sent by older clients but no longer trusted; the
+ // containing folder is resolved from each document's own `folderId`.
+ const { documentIds, strategy, groupStrategy, linkStrategy } = req.body as {
documentIds: string[];
strategy?: string;
groupStrategy?: string;
@@ -125,6 +129,8 @@ export default async function handler(
teamId: true,
defaultPermissionStrategy: true,
defaultGroupPermissionStrategy: true,
+ defaultRootItemAccess: true,
+ defaultGroupRootItemAccess: true,
},
});
@@ -167,14 +173,14 @@ export default async function handler(
dataroomId,
dataroomDocuments,
strategy: effectiveGroupStrategy,
- folderPath,
+ rootItemAccess: dataroom.defaultGroupRootItemAccess,
target: "VIEWER_GROUP",
}),
applyPermissionStrategy({
dataroomId,
dataroomDocuments,
strategy: effectiveLinkStrategy,
- folderPath,
+ rootItemAccess: dataroom.defaultRootItemAccess,
target: "PERMISSION_GROUP",
}),
]);
@@ -195,16 +201,13 @@ export default async function handler(
async function applyPermissionStrategy(opts: {
dataroomId: string;
- dataroomDocuments: {
- id: string;
- documentId: string;
- folderId: string | null;
- }[];
+ dataroomDocuments: DataroomDocumentRef[];
strategy: DefaultPermissionStrategy;
- folderPath?: string;
+ rootItemAccess: RootItemAccess;
target: GroupTarget;
}) {
- const { dataroomId, dataroomDocuments, strategy, folderPath, target } = opts;
+ const { dataroomId, dataroomDocuments, strategy, rootItemAccess, target } =
+ opts;
// ASK_EVERY_TIME and HIDDEN_BY_DEFAULT both intentionally leave the document
// hidden until something else writes the access control rows (the unified
@@ -212,29 +215,103 @@ async function applyPermissionStrategy(opts: {
// HIDDEN_BY_DEFAULT).
if (strategy !== DefaultPermissionStrategy.INHERIT_FROM_PARENT) return;
- const isRootLevel = !folderPath || folderPath.length === 0;
-
- if (isRootLevel) {
- await applyRootLevelPermissions(dataroomId, dataroomDocuments, target);
- } else {
- await inheritFromParentFolder(
- dataroomId,
- dataroomDocuments,
- folderPath!,
- target,
- );
+ // Group documents by the folder they actually live in (server-side truth,
+ // not the client-provided path). Root-level documents have no parent to
+ // inherit from and get the dataroom's root-item default instead.
+ const rootDocuments: DataroomDocumentRef[] = [];
+ const documentsByFolderId = new Map<string, DataroomDocumentRef[]>();
+ for (const doc of dataroomDocuments) {
+ if (doc.folderId === null) {
+ rootDocuments.push(doc);
+ } else {
+ const list = documentsByFolderId.get(doc.folderId) ?? [];
+ list.push(doc);
+ documentsByFolderId.set(doc.folderId, list);
+ }
}
+
+ await Promise.all([
+ rootDocuments.length > 0
+ ? applyRootLevelPermissions(
+ dataroomId,
+ rootDocuments,
+ rootItemAccess,
+ target,
+ )
+ : Promise.resolve(),
+ ...Array.from(documentsByFolderId, ([folderId, docs]) =>
+ inheritFromContainingFolder(folderId, docs, target),
+ ),
+ ]);
+}
+
+/**
+ * Upsert-equivalent for default-permission rows: remove any existing rows for
+ * the exact (group, document) pairs we're about to write, then insert the new
+ * values. Unlike `createMany({ skipDuplicates: true })`, a stale row (e.g.
+ * `canView=false` left behind by an earlier write) is corrected instead of
+ * silently kept.
+ */
+async function upsertViewerGroupDocumentRows(
+ data: {
+ groupId: string;
+ itemId: string;
+ itemType: ItemType;
+ canView: boolean;
+ canDownload: boolean;
+ }[],
+) {
+ if (data.length === 0) return;
+ const groupIds = Array.from(new Set(data.map((d) => d.groupId)));
+ const itemIds = Array.from(new Set(data.map((d) => d.itemId)));
+ await prisma.$transaction([
+ prisma.viewerGroupAccessControls.deleteMany({
+ where: {
+ groupId: { in: groupIds },
+ itemId: { in: itemIds },
+ itemType: ItemType.DATAROOM_DOCUMENT,
+ },
+ }),
+ prisma.viewerGroupAccessControls.createMany({ data }),
+ ]);
+}
+
+async function upsertPermissionGroupDocumentRows(
+ data: {
+ groupId: string;
+ itemId: string;
+ itemType: ItemType;
+ canView: boolean;
+ canDownload: boolean;
+ canDownloadOriginal: boolean;
+ }[],
+) {
+ if (data.length === 0) return;
+ const groupIds = Array.from(new Set(data.map((d) => d.groupId)));
+ const itemIds = Array.from(new Set(data.map((d) => d.itemId)));
+ await prisma.$transaction([
+ prisma.permissionGroupAccessControls.deleteMany({
+ where: {
+ groupId: { in: groupIds },
+ itemId: { in: itemIds },
+ itemType: ItemType.DATAROOM_DOCUMENT,
+ },
+ }),
+ prisma.permissionGroupAccessControls.createMany({ data }),
+ ]);
}
async function applyRootLevelPermissions(
dataroomId: string,
- dataroomDocuments: {
- id: string;
- documentId: string;
- folderId: string | null;
- }[],
+ dataroomDocuments: DataroomDocumentRef[],
+ rootItemAccess: RootItemAccess,
target: GroupTarget,
) {
+ const flags = resolveRootItemAccessFlags(rootItemAccess);
+ // HIDDEN: no rows are written, so the documents stay invisible until an
+ // admin grants access explicitly.
+ if (!flags) return;
+
if (target === "VIEWER_GROUP") {
const viewerGroups = await prisma.viewerGroup.findMany({
where: { dataroomId },
@@ -242,22 +319,17 @@ async function applyRootLevelPermissions(
});
if (viewerGroups.length === 0) return;
- const data = viewerGroups.flatMap((group) =>
- dataroomDocuments.map((doc) => ({
- groupId: group.id,
- itemId: doc.id,
- itemType: ItemType.DATAROOM_DOCUMENT,
- canView: true,
- canDownload: false,
- })),
+ await upsertViewerGroupDocumentRows(
+ viewerGroups.flatMap((group) =>
+ dataroomDocuments.map((doc) => ({
+ groupId: group.id,
+ itemId: doc.id,
+ itemType: ItemType.DATAROOM_DOCUMENT,
+ canView: flags.canView,
+ canDownload: flags.canDownload,
+ })),
+ ),
);
-
- if (data.length > 0) {
- await prisma.viewerGroupAccessControls.createMany({
- data,
- skipDuplicates: true,
- });
- }
return;
}
@@ -267,85 +339,64 @@ async function applyRootLevelPermissions(
});
if (permissionGroups.length === 0) return;
- const data = permissionGroups.flatMap((group) =>
- dataroomDocuments.map((doc) => ({
- groupId: group.id,
- itemId: doc.id,
- itemType: ItemType.DATAROOM_DOCUMENT,
- canView: true,
- canDownload: false,
- canDownloadOriginal: false,
- })),
+ await upsertPermissionGroupDocumentRows(
+ permissionGroups.flatMap((group) =>
+ dataroomDocuments.map((doc) => ({
+ groupId: group.id,
+ itemId: doc.id,
+ itemType: ItemType.DATAROOM_DOCUMENT,
+ canView: flags.canView,
+ canDownload: flags.canDownload,
+ canDownloadOriginal: false,
+ })),
+ ),
);
-
- if (data.length > 0) {
- await prisma.permissionGroupAccessControls.createMany({
- data,
- skipDuplicates: true,
- });
- }
}
-async function inheritFromParentFolder(
- dataroomId: string,
- dataroomDocuments: {
- id: string;
- documentId: string;
- folderId: string | null;
- }[],
- folderPath: string,
+/**
+ * Copies the ACLs of the folder the documents actually live in onto the
+ * documents. Groups without a row on the folder get no row on the document
+ * (not visible), mirroring the folder exactly.
+ *
+ * Note this intentionally reads the *containing* folder's permissions — a
+ * previous version derived the parent from the client-supplied folder path
+ * with an off-by-one (`slice(0, -1)`), inheriting from the grandparent and
+ * leaving freshly uploaded documents without any viewable row.
+ */
+async function inheritFromContainingFolder(
+ folderId: string,
+ dataroomDocuments: DataroomDocumentRef[],
target: GroupTarget,
) {
- const pathSegments = folderPath.split("/").filter(Boolean);
- const parentPath = "/" + pathSegments.slice(0, -1).join("/");
-
- const parentFolder = await prisma.dataroomFolder.findUnique({
- where: {
- dataroomId_path: { dataroomId, path: parentPath },
- },
- select: { id: true },
- });
-
- if (!parentFolder) {
- await applyRootLevelPermissions(dataroomId, dataroomDocuments, target);
- return;
- }
-
if (target === "VIEWER_GROUP") {
- const parentViewerPermissions =
- await prisma.viewerGroupAccessControls.findMany({
- where: {
- itemId: parentFolder.id,
- itemType: ItemType.DATAROOM_FOLDER,
- },
- select: { groupId: true, canView: true, canDownload: true },
- });
-
- if (parentViewerPermissions.length === 0) return;
-
- const data = parentViewerPermissions.flatMap((parentPerm) =>
- dataroomDocuments.map((doc) => ({
- groupId: parentPerm.groupId,
- itemId: doc.id,
- itemType: ItemType.DATAROOM_DOCUMENT,
- canView: parentPerm.canView,
- canDownload: parentPerm.canDownload,
- })),
- );
+ const folderPermissions = await prisma.viewerGroupAccessControls.findMany({
+ where: {
+ itemId: folderId,
+ itemType: ItemType.DATAROOM_FOLDER,
+ },
+ select: { groupId: true, canView: true, canDownload: true },
+ });
- if (data.length > 0) {
- await prisma.viewerGroupAccessControls.createMany({
- data,
- skipDuplicates: true,
- });
- }
+ if (folderPermissions.length === 0) return;
+
+ await upsertViewerGroupDocumentRows(
+ folderPermissions.flatMap((folderPerm) =>
+ dataroomDocuments.map((doc) => ({
+ groupId: folderPerm.groupId,
+ itemId: doc.id,
+ itemType: ItemType.DATAROOM_DOCUMENT,
+ canView: folderPerm.canView,
+ canDownload: folderPerm.canDownload,
+ })),
+ ),
+ );
return;
}
- const parentPermissionGroupPermissions =
- await prisma.permissionGroupAccessControls.findMany({
+ const folderPermissions = await prisma.permissionGroupAccessControls.findMany(
+ {
where: {
- itemId: parentFolder.id,
+ itemId: folderId,
itemType: ItemType.DATAROOM_FOLDER,
},
select: {
@@ -354,25 +405,21 @@ async function inheritFromParentFolder(
canDownload: true,
canDownloadOriginal: true,
},
- });
-
- if (parentPermissionGroupPermissions.length === 0) return;
-
- const data = parentPermissionGroupPermissions.flatMap((parentPerm) =>
- dataroomDocuments.map((doc) => ({
- groupId: parentPerm.groupId,
- itemId: doc.id,
- itemType: ItemType.DATAROOM_DOCUMENT,
- canView: parentPerm.canView,
- canDownload: parentPerm.canDownload,
- canDownloadOriginal: parentPerm.canDownloadOriginal,
- })),
+ },
);
- if (data.length > 0) {
- await prisma.permissionGroupAccessControls.createMany({
- data,
- skipDuplicates: true,
- });
- }
+ if (folderPermissions.length === 0) return;
+
+ await upsertPermissionGroupDocumentRows(
+ folderPermissions.flatMap((folderPerm) =>
+ dataroomDocuments.map((doc) => ({
+ groupId: folderPerm.groupId,
+ itemId: doc.id,
+ itemType: ItemType.DATAROOM_DOCUMENT,
+ canView: folderPerm.canView,
+ canDownload: folderPerm.canDownload,
+ canDownloadOriginal: folderPerm.canDownloadOriginal,
+ })),
+ ),
+ );
}
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/folders/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/folders/index.ts
index 74b2971a..5e585557 100644
--- a/pages/api/teams/[teamId]/datarooms/[id]/folders/index.ts
+++ b/pages/api/teams/[teamId]/datarooms/[id]/folders/index.ts
@@ -1,10 +1,15 @@
import { NextApiRequest, NextApiResponse } from "next";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
-import { DefaultPermissionStrategy, ItemType } from "@prisma/client";
+import {
+ DefaultPermissionStrategy,
+ ItemType,
+ RootItemAccess,
+} from "@prisma/client";
import { getServerSession } from "next-auth/next";
import { enforceDataroomMemberScope } from "@/lib/api/rbac/guard";
+import { resolveRootItemAccessFlags } from "@/lib/dataroom/root-item-access";
import { resolveFreeFolderPath } from "@/lib/folders/bulk-create";
import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
@@ -33,6 +38,8 @@ async function applyDefaultFolderPermissions(
select: {
defaultPermissionStrategy: true,
defaultGroupPermissionStrategy: true,
+ defaultRootItemAccess: true,
+ defaultGroupRootItemAccess: true,
teamId: true,
},
}),
@@ -82,6 +89,7 @@ async function applyDefaultFolderPermissions(
folderId,
viewerGroups,
strategy: dataroom.defaultGroupPermissionStrategy,
+ rootItemAccess: dataroom.defaultGroupRootItemAccess,
parentFolderId,
}),
applyForPermissionGroups({
@@ -89,6 +97,7 @@ async function applyDefaultFolderPermissions(
folderId,
permissionGroups,
strategy: dataroom.defaultPermissionStrategy,
+ rootItemAccess: dataroom.defaultRootItemAccess,
parentFolderId,
}),
]);
@@ -99,9 +108,11 @@ async function applyForViewerGroups(opts: {
folderId: string;
viewerGroups: { id: string }[];
strategy: DefaultPermissionStrategy;
+ rootItemAccess: RootItemAccess;
parentFolderId: string | null;
}) {
- const { folderId, viewerGroups, strategy, parentFolderId } = opts;
+ const { folderId, viewerGroups, strategy, rootItemAccess, parentFolderId } =
+ opts;
if (strategy !== DefaultPermissionStrategy.INHERIT_FROM_PARENT) return;
if (viewerGroups.length === 0) return;
@@ -130,13 +141,16 @@ async function applyForViewerGroups(opts: {
return;
}
+ const flags = resolveRootItemAccessFlags(rootItemAccess);
+ if (!flags) return;
+
await prisma.viewerGroupAccessControls.createMany({
data: viewerGroups.map((group) => ({
groupId: group.id,
itemId: folderId,
itemType: ItemType.DATAROOM_FOLDER,
- canView: true,
- canDownload: false,
+ canView: flags.canView,
+ canDownload: flags.canDownload,
})),
skipDuplicates: true,
});
@@ -147,9 +161,16 @@ async function applyForPermissionGroups(opts: {
folderId: string;
permissionGroups: { id: string }[];
strategy: DefaultPermissionStrategy;
+ rootItemAccess: RootItemAccess;
parentFolderId: string | null;
}) {
- const { folderId, permissionGroups, strategy, parentFolderId } = opts;
+ const {
+ folderId,
+ permissionGroups,
+ strategy,
+ rootItemAccess,
+ parentFolderId,
+ } = opts;
if (strategy !== DefaultPermissionStrategy.INHERIT_FROM_PARENT) return;
if (permissionGroups.length === 0) return;
@@ -184,13 +205,16 @@ async function applyForPermissionGroups(opts: {
return;
}
+ const flags = resolveRootItemAccessFlags(rootItemAccess);
+ if (!flags) return;
+
await prisma.permissionGroupAccessControls.createMany({
data: permissionGroups.map((group) => ({
groupId: group.id,
itemId: folderId,
itemType: ItemType.DATAROOM_FOLDER,
- canView: true,
- canDownload: false,
+ canView: flags.canView,
+ canDownload: flags.canDownload,
canDownloadOriginal: false,
})),
skipDuplicates: true,
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/index.ts
index dd15723c..77e7f428 100644
--- a/pages/api/teams/[teamId]/datarooms/[id]/index.ts
+++ b/pages/api/teams/[teamId]/datarooms/[id]/index.ts
@@ -1,6 +1,6 @@
import { NextApiRequest, NextApiResponse } from "next";
-import { DefaultPermissionStrategy } from "@prisma/client";
+import { DefaultPermissionStrategy, RootItemAccess } from "@prisma/client";
import { withTeamApi } from "@/lib/api/auth/with-session-team";
import { errorhandler } from "@/lib/errorHandler";
@@ -69,6 +69,8 @@ const patchHandler = withTeamApi(
enableVisitorUploadChangeNotifications,
defaultPermissionStrategy,
defaultGroupPermissionStrategy,
+ defaultRootItemAccess,
+ defaultGroupRootItemAccess,
allowBulkDownload,
showLastUpdated,
tags,
@@ -83,6 +85,8 @@ const patchHandler = withTeamApi(
enableVisitorUploadChangeNotifications?: boolean;
defaultPermissionStrategy?: DefaultPermissionStrategy;
defaultGroupPermissionStrategy?: DefaultPermissionStrategy;
+ defaultRootItemAccess?: RootItemAccess;
+ defaultGroupRootItemAccess?: RootItemAccess;
allowBulkDownload?: boolean;
showLastUpdated?: boolean;
tags?: string[];
@@ -126,6 +130,17 @@ const patchHandler = withTeamApi(
});
}
+ for (const value of [defaultRootItemAccess, defaultGroupRootItemAccess]) {
+ if (
+ value !== undefined &&
+ !Object.values(RootItemAccess).includes(value)
+ ) {
+ return res.status(400).json({
+ message: "Invalid root item access value",
+ });
+ }
+ }
+
const updatedDataroom = await prisma.$transaction(async (tx) => {
const dataroom = await tx.dataroom.update({
where: {
@@ -150,6 +165,10 @@ const patchHandler = withTeamApi(
...(defaultGroupPermissionStrategy && {
defaultGroupPermissionStrategy,
}),
+ ...(defaultRootItemAccess && { defaultRootItemAccess }),
+ ...(defaultGroupRootItemAccess && {
+ defaultGroupRootItemAccess,
+ }),
...(typeof allowBulkDownload === "boolean" && {
allowBulkDownload,
}),
diff --git a/prisma/migrations/20260707000000_add_root_item_access_defaults/migration.sql b/prisma/migrations/20260707000000_add_root_item_access_defaults/migration.sql
new file mode 100644
index 00000000..4d5e6f48
--- /dev/null
+++ b/prisma/migrations/20260707000000_add_root_item_access_defaults/migration.sql
@@ -0,0 +1,6 @@
+-- CreateEnum
+CREATE TYPE "RootItemAccess" AS ENUM ('VIEW_ONLY', 'VIEW_AND_DOWNLOAD', 'HIDDEN');
+
+-- AlterTable
+ALTER TABLE "Dataroom" ADD COLUMN "defaultRootItemAccess" "RootItemAccess" NOT NULL DEFAULT 'VIEW_ONLY',
+ADD COLUMN "defaultGroupRootItemAccess" "RootItemAccess" NOT NULL DEFAULT 'VIEW_ONLY';
diff --git a/prisma/schema/dataroom.prisma b/prisma/schema/dataroom.prisma
index 5a6a291e..eb80e531 100644
--- a/prisma/schema/dataroom.prisma
+++ b/prisma/schema/dataroom.prisma
@@ -61,6 +61,12 @@ model Dataroom {
// defaultPermissionStrategy so links and groups can have different defaults.
defaultGroupPermissionStrategy DefaultPermissionStrategy @default(INHERIT_FROM_PARENT)
+ // How root-level items (which have no parent folder to inherit from) are
+ // exposed when the INHERIT_FROM_PARENT strategy applies. One per scope,
+ // matching the link/group strategy split above.
+ defaultRootItemAccess RootItemAccess @default(VIEW_ONLY) // links (permission groups)
+ defaultGroupRootItemAccess RootItemAccess @default(VIEW_ONLY) // viewer groups
+
// bulk download setting
allowBulkDownload Boolean @default(true) // Allow bulk download of entire dataroom
@@ -371,6 +377,14 @@ enum DefaultPermissionStrategy {
HIDDEN_BY_DEFAULT
}
+// Default access granted to root-level items under INHERIT_FROM_PARENT,
+// where there is no parent folder whose permissions could be copied.
+enum RootItemAccess {
+ VIEW_ONLY
+ VIEW_AND_DOWNLOAD
+ HIDDEN
+}
+
model PermissionGroup {
id String @id @default(cuid())
name String