Skip to content

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

feat: multi folder upload permission (#2164)

Marc Seitza48b2e92e1f9
diff --git a/app/(ee)/api/links/[id]/upload/route.ts b/app/(ee)/api/links/[id]/upload/route.ts
index 1a14b1c5..b702946e 100644
--- a/app/(ee)/api/links/[id]/upload/route.ts
+++ b/app/(ee)/api/links/[id]/upload/route.ts
@@ -153,6 +153,7 @@ export async function POST(
enableUpload: true,
enableNotification: true,
uploadFolderId: true,
+ uploadFolderIds: true,
dataroomId: true,
teamId: true,
team: {
@@ -239,22 +240,61 @@ export async function POST(
isExternalUpload: true,
});
- // 2. Create the dataroom document
- // If folderId is provided and link has no uploadFolderId, use folderId as the dataroomFolderId
- // Otherwise, use the link's uploadFolderId
- // or null if it doesn't exist
- let dataroomFolderId: string | null = folderId ?? null;
- if (link.uploadFolderId) {
- const dataroomFolder = await prisma.dataroomFolder.findUnique({
+ // 2. Resolve the target dataroom folder.
+ //
+ // Semantics:
+ // - Admin selected 0 folders → visitor can upload anywhere (use folderId
+ // from the request, validated against the dataroom).
+ // - Admin selected 1+ folders → the visitor-supplied folderId must be
+ // inside that allow-list. If it isn't (e.g. the visitor is currently
+ // browsing another folder), fall back to the first allowed folder so
+ // uploads never silently escape the allow-list.
+ //
+ // `uploadFolderIds` is the new source of truth, but until the legacy
+ // `uploadFolderId` column has been backfilled into it we fall back to
+ // `[uploadFolderId]` for rows where the array is still empty. The
+ // fallback becomes inert post-backfill.
+ const allowedUploadFolderIds: string[] =
+ Array.isArray(link.uploadFolderIds) && link.uploadFolderIds.length > 0
+ ? link.uploadFolderIds.filter(
+ (id): id is string => typeof id === "string" && !!id,
+ )
+ : link.uploadFolderId
+ ? [link.uploadFolderId]
+ : [];
+
+ let dataroomFolderId: string | null = null;
+
+ if (allowedUploadFolderIds.length === 0) {
+ // No restriction: validate the visitor-chosen folder belongs to this
+ // dataroom before using it.
+ if (folderId) {
+ const dataroomFolder = await prisma.dataroomFolder.findUnique({
+ where: { id: folderId, dataroomId },
+ select: { id: true },
+ });
+ dataroomFolderId = dataroomFolder?.id ?? null;
+ }
+ } else {
+ // Restricted: look up all allowed folders in one query and prefer the
+ // one the visitor is currently in if it's on the list.
+ const allowedFolders = await prisma.dataroomFolder.findMany({
where: {
- id: link.uploadFolderId,
+ id: { in: allowedUploadFolderIds },
dataroomId,
},
- select: {
- id: true,
- },
+ select: { id: true },
});
- dataroomFolderId = dataroomFolder?.id ?? null;
+ const allowedSet = new Set(allowedFolders.map((f) => f.id));
+
+ if (folderId && allowedSet.has(folderId)) {
+ dataroomFolderId = folderId;
+ } else {
+ // Preserve admin-selected ordering so the "primary" allowed folder
+ // (historically `uploadFolderId`) wins when multiple are allowed.
+ dataroomFolderId =
+ allowedUploadFolderIds.find((id) => allowedSet.has(id)) ?? null;
+ }
}
const newDataroomDocument = await prisma.dataroomDocument.create({
diff --git a/app/api/views-dataroom/route.ts b/app/api/views-dataroom/route.ts
index f344a23a..3d1723ed 100644
--- a/app/api/views-dataroom/route.ts
+++ b/app/api/views-dataroom/route.ts
@@ -145,6 +145,8 @@ export async function POST(request: NextRequest) {
},
},
enableUpload: true,
+ uploadFolderId: true,
+ uploadFolderIds: true,
dataroom: {
select: {
agentsEnabled: true,
@@ -745,6 +747,43 @@ export async function POST(request: NextRequest) {
const dataroomViewId =
newDataroomView?.id ?? dataroomSession?.viewId ?? undefined;
+ // Resolve the upload-destination allow-list so the visitor UI can
+ // surface exactly which folders they may target. Null/empty = no
+ // restriction (visitor may upload into any folder they're in).
+ let uploadFolderAllowList:
+ | { id: string; name: string; path: string }[]
+ | null = null;
+ if (link.enableUpload) {
+ // `uploadFolderIds` is the new source of truth, but until the
+ // legacy `uploadFolderId` column has been backfilled into it we
+ // fall back to `[uploadFolderId]` for rows where the array is
+ // still empty. The fallback becomes inert post-backfill.
+ const allowedIds: string[] =
+ Array.isArray(link.uploadFolderIds) &&
+ link.uploadFolderIds.length > 0
+ ? link.uploadFolderIds.filter(
+ (id): id is string => typeof id === "string" && !!id,
+ )
+ : link.uploadFolderId
+ ? [link.uploadFolderId]
+ : [];
+ if (allowedIds.length > 0) {
+ const folders = await prisma.dataroomFolder.findMany({
+ where: {
+ id: { in: allowedIds },
+ dataroomId: link.dataroomId!,
+ },
+ select: { id: true, name: true, path: true },
+ });
+ const byId = new Map(folders.map((f) => [f.id, f]));
+ uploadFolderAllowList = allowedIds
+ .map((id) => byId.get(id))
+ .filter(
+ (f): f is { id: string; name: string; path: string } => !!f,
+ );
+ }
+ }
+
const returnObject = {
message: "Dataroom View recorded",
viewId: dataroomViewId,
@@ -756,6 +795,7 @@ export async function POST(request: NextRequest) {
viewerId: viewer?.id,
conversationsEnabled: link.enableConversation,
enableVisitorUpload: link.enableUpload,
+ uploadFolderAllowList,
agentsEnabled: link.dataroom?.agentsEnabled ?? false,
dataroomName: link.dataroom?.name,
...(isTeamMember && { isTeamMember: true }),
diff --git a/components/links/link-sheet/index.tsx b/components/links/link-sheet/index.tsx
index aac4b218..7a4164f5 100644
--- a/components/links/link-sheet/index.tsx
+++ b/components/links/link-sheet/index.tsx
@@ -93,6 +93,8 @@ export const DEFAULT_LINK_PROPS = (
isFileRequestOnly: false,
uploadFolderId: null,
uploadFolderName: "Home",
+ uploadFolderIds: [],
+ uploadFolders: [],
enableIndexFile: false,
permissions: {},
permissionGroupId: null,
@@ -138,6 +140,8 @@ export type DEFAULT_LINK_TYPE = {
isFileRequestOnly: boolean;
uploadFolderId: string | null;
uploadFolderName: string;
+ uploadFolderIds: string[];
+ uploadFolders: { id: string; name: string; path?: string | null }[];
enableIndexFile: boolean;
permissions?: ItemPermission | null; // For dataroom links file permissions
permissionGroupId?: string | null;
@@ -477,6 +481,7 @@ export default function LinkSheet({
"enableUpload",
"isFileRequestOnly",
"uploadFolderId",
+ "uploadFolderIds",
"enableIndexFile",
"permissionGroupId",
"tags",
diff --git a/components/links/link-sheet/upload-section/index.tsx b/components/links/link-sheet/upload-section/index.tsx
index 982bbed8..8085a6a8 100644
--- a/components/links/link-sheet/upload-section/index.tsx
+++ b/components/links/link-sheet/upload-section/index.tsx
@@ -1,6 +1,6 @@
-import React, { useEffect, useState } from "react";
+import React, { useEffect, useMemo, useState } from "react";
-import { CircleHelpIcon, CircleXIcon, FolderIcon, XIcon } from "lucide-react";
+import { CircleHelpIcon, FolderIcon, XIcon } from "lucide-react";
import { motion } from "motion/react";
import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";
@@ -25,7 +25,18 @@ import { DEFAULT_LINK_TYPE } from "..";
import LinkItem from "../link-item";
import { LinkUpgradeOptions } from "../link-options";
-function FolderSelectionModal({
+type UploadFolderSummary = {
+ id: string;
+ name: string;
+ path?: string | null;
+};
+
+/**
+ * Single-folder selection modal used for document links / all-documents scope.
+ * Dataroom links use `MultiFolderSelectionModal` below because an admin may now
+ * grant upload access to more than one folder.
+ */
+function SingleFolderSelectionModal({
open,
setOpen,
dataroomId,
@@ -128,6 +139,138 @@ function FolderSelectionModal({
);
}
+/**
+ * Multi-folder picker for dataroom links. Reuses the single-select tree UI but
+ * accumulates folders into a local set each time the admin picks one in the
+ * dialog. Already-selected folders are surfaced as removable chips in the
+ * trigger so the admin can easily prune the allow-list.
+ */
+function MultiFolderSelectionModal({
+ dataroomId,
+ selectedFolders,
+ onChange,
+}: {
+ dataroomId: string;
+ selectedFolders: UploadFolderSummary[];
+ onChange: (folders: UploadFolderSummary[]) => void;
+}) {
+ const [open, setOpen] = useState(false);
+ const [draftFolder, setDraftFolder] = useState<TSelectedFolder | null>(null);
+
+ // Folders already in the allow-list shouldn't be picked again from the tree.
+ const disableIds = useMemo(
+ () => selectedFolders.map((f) => f.id),
+ [selectedFolders],
+ );
+
+ const addDraft = (event: React.MouseEvent) => {
+ event.preventDefault();
+ event.stopPropagation();
+ if (!draftFolder?.id) return;
+ const exists = selectedFolders.some((f) => f.id === draftFolder.id);
+ if (!exists) {
+ onChange([
+ ...selectedFolders,
+ {
+ id: draftFolder.id,
+ name: draftFolder.name,
+ path: draftFolder.path ?? null,
+ },
+ ]);
+ }
+ setDraftFolder(null);
+ setOpen(false);
+ };
+
+ const removeFolder = (id: string) => {
+ onChange(selectedFolders.filter((f) => f.id !== id));
+ };
+
+ return (
+ <div className="space-y-2">
+ {selectedFolders.length > 0 ? (
+ <div className="flex flex-wrap gap-2">
+ {selectedFolders.map((folder) => (
+ <span
+ key={folder.id}
+ className="inline-flex items-center gap-1 rounded-md border border-input bg-muted/40 px-2 py-1 text-sm"
+ title={folder.path ?? folder.name}
+ >
+ <FolderIcon className="h-3.5 w-3.5 text-muted-foreground" />
+ <span className="max-w-[220px] truncate">{folder.name}</span>
+ <button
+ type="button"
+ onClick={() => removeFolder(folder.id)}
+ className="rounded p-0.5 hover:bg-muted"
+ aria-label={`Remove ${folder.name}`}
+ >
+ <XIcon className="h-3.5 w-3.5 text-muted-foreground" />
+ </button>
+ </span>
+ ))}
+ </div>
+ ) : null}
+
+ <Dialog
+ open={open}
+ onOpenChange={(next) => {
+ setOpen(next);
+ if (!next) setDraftFolder(null);
+ }}
+ >
+ <DialogTrigger asChild>
+ <button
+ type="button"
+ className="flex w-full cursor-pointer items-center rounded-md border border-dashed border-input bg-white px-3 py-2 text-left text-sm text-muted-foreground hover:border-muted-foreground dark:border-gray-500 dark:bg-gray-800"
+ >
+ {selectedFolders.length === 0
+ ? "Optionally, select one or more folders"
+ : "Add another folder"}
+ </button>
+ </DialogTrigger>
+ <DialogContent className="sm:max-w-[425px]">
+ <DialogHeader className="text-start">
+ <DialogTitle>Select Folder</DialogTitle>
+ <DialogDescription>
+ Add a folder to the upload allow-list. You can add more than one.
+ </DialogDescription>
+ </DialogHeader>
+ <form onSubmit={(e) => e.preventDefault()}>
+ <div className="mb-2 max-h-[75vh] overflow-x-hidden overflow-y-scroll">
+ <DataroomFolderTree
+ dataroomId={dataroomId}
+ selectedFolder={draftFolder}
+ setSelectedFolder={setDraftFolder}
+ disableId={disableIds}
+ />
+ </div>
+
+ <DialogFooter>
+ <Button
+ type="button"
+ onClick={addDraft}
+ className="flex h-9 w-full gap-1"
+ disabled={!draftFolder}
+ >
+ {!draftFolder ? (
+ "Select a folder"
+ ) : (
+ <>
+ Add{" "}
+ <span className="max-w-[200px] truncate font-medium">
+ {draftFolder.name}
+ </span>
+ </>
+ )}
+ </Button>
+ </DialogFooter>
+ </form>
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+}
+
export default function UploadSection({
data,
setData,
@@ -145,27 +288,66 @@ export default function UploadSection({
}: LinkUpgradeOptions) => void;
targetId: string;
}) {
- const { enableUpload, isFileRequestOnly, uploadFolderId, uploadFolderName } =
- data;
+ const {
+ enableUpload,
+ uploadFolderId,
+ uploadFolderName,
+ uploadFolderIds,
+ uploadFolders,
+ } = data;
const [enabled, setEnabled] = useState<boolean>(false);
- const [selectedFolder, setSelectedFolder] = useState<TSelectedFolder | null>(
+ // Legacy single-folder selection kept for document links / all-documents.
+ const [legacyFolder, setLegacyFolder] = useState<TSelectedFolder | null>(
null,
);
const [open, setOpen] = useState<boolean>(false);
+ const isDataroomTarget = !!targetId && targetId !== "all_documents";
+
useEffect(() => {
setEnabled(enableUpload!);
}, [enableUpload]);
+ // Hydrate the legacy single-folder selection for the all-documents picker.
useEffect(() => {
if (uploadFolderId) {
- setSelectedFolder({ id: uploadFolderId, name: uploadFolderName });
+ setLegacyFolder({ id: uploadFolderId, name: uploadFolderName });
}
}, [uploadFolderId, uploadFolderName]);
+ // Normalise the allow-list of folders shown as chips for dataroom links.
+ const selectedFolders = useMemo<UploadFolderSummary[]>(() => {
+ if (Array.isArray(uploadFolders) && uploadFolders.length > 0) {
+ return uploadFolders.map((f) => ({
+ id: f.id,
+ name: f.name,
+ path: f.path ?? null,
+ }));
+ }
+ // Server didn't enrich folder metadata; synthesise names from the id list
+ // using the legacy fields so the chip still has a meaningful label.
+ if (Array.isArray(uploadFolderIds) && uploadFolderIds.length > 0) {
+ return uploadFolderIds.map((id) => ({
+ id,
+ name:
+ id === uploadFolderId && uploadFolderName
+ ? uploadFolderName
+ : "Folder",
+ }));
+ }
+ if (uploadFolderId) {
+ return [
+ {
+ id: uploadFolderId,
+ name: uploadFolderName || "Folder",
+ },
+ ];
+ }
+ return [];
+ }, [uploadFolders, uploadFolderIds, uploadFolderId, uploadFolderName]);
+
const handleUpload = async () => {
const updatedUpload = !enabled;
-
setData({
...data,
enableUpload: updatedUpload,
@@ -173,19 +355,29 @@ export default function UploadSection({
setEnabled(updatedUpload);
};
- const handleFileRequestToggle = (checked: boolean): void => {
+ const handleLegacySelectFolder = (
+ selectedFolder: TSelectedFolder | null,
+ ): void => {
+ setLegacyFolder(selectedFolder);
setData({
...data,
- isFileRequestOnly: checked,
+ uploadFolderId: selectedFolder?.id ?? null,
+ uploadFolderName: selectedFolder?.name || "Home",
+ uploadFolderIds: selectedFolder?.id ? [selectedFolder.id] : [],
+ uploadFolders: selectedFolder?.id
+ ? [{ id: selectedFolder.id, name: selectedFolder.name }]
+ : [],
});
};
- const handleSelectFolder = (selectedFolder: TSelectedFolder | null): void => {
- setSelectedFolder(selectedFolder);
+ const handleMultiChange = (folders: UploadFolderSummary[]): void => {
setData({
...data,
- uploadFolderId: selectedFolder?.id ?? null,
- uploadFolderName: selectedFolder?.name || "Home",
+ uploadFolderIds: folders.map((f) => f.id),
+ uploadFolders: folders,
+ // Keep the legacy columns in sync so existing consumers keep working.
+ uploadFolderId: folders[0]?.id ?? null,
+ uploadFolderName: folders[0]?.name ?? "Home",
});
};
@@ -215,25 +407,24 @@ export default function UploadSection({
>
<div className="flex w-full flex-col items-start gap-6 overflow-x-visible pb-4 pt-0">
<div className="w-full space-y-4">
- {/* <div className="flex items-center space-x-2">
- <Switch
- id="file-request-mode"
- checked={isFileRequestOnly}
- onCheckedChange={handleFileRequestToggle}
- />
- <Label htmlFor="file-request-mode">
- File request only mode
- </Label>
- </div> */}
-
<div className="space-y-4">
<Label
htmlFor="link-folder"
className="flex flex-col items-start gap-2"
>
<div className="flex items-center gap-2">
- <span>Upload to specific folder</span>
- <BadgeTooltip content="This is the folder that will be used to store uploaded files. If you don't select a folder, the files will be uploaded to the folder the visitor chooses.">
+ <span>
+ {isDataroomTarget
+ ? "Upload to specific folder(s)"
+ : "Upload to specific folder"}
+ </span>
+ <BadgeTooltip
+ content={
+ isDataroomTarget
+ ? "Add one or more folders where visitors may upload. When multiple are allowed, the visitor picks one at upload time (the folder they are currently browsing is pre-selected when it's on the list). Leave empty to let visitors choose any folder."
+ : "This is the folder that will be used to store uploaded files. If you don't select a folder, the files will be uploaded to the folder the visitor chooses."
+ }
+ >
<CircleHelpIcon className="h-4 w-4 shrink-0 text-muted-foreground hover:text-foreground" />
</BadgeTooltip>
</div>
@@ -241,13 +432,21 @@ export default function UploadSection({
Leave blank for visitor to choose folder
</span>
</Label>
- <FolderSelectionModal
- open={open}
- setOpen={setOpen}
- dataroomId={targetId}
- currentFolder={selectedFolder}
- handleSelectFolder={handleSelectFolder}
- />
+ {isDataroomTarget ? (
+ <MultiFolderSelectionModal
+ dataroomId={targetId}
+ selectedFolders={selectedFolders}
+ onChange={handleMultiChange}
+ />
+ ) : (
+ <SingleFolderSelectionModal
+ open={open}
+ setOpen={setOpen}
+ dataroomId={targetId}
+ currentFolder={legacyFolder}
+ handleSelectFolder={handleLegacySelectFolder}
+ />
+ )}
</div>
</div>
</div>
diff --git a/components/links/links-table.tsx b/components/links/links-table.tsx
index 0368af67..b2d7381f 100644
--- a/components/links/links-table.tsx
+++ b/components/links/links-table.tsx
@@ -429,6 +429,31 @@ export default function LinksTable({
isFileRequestOnly: link.isFileRequestOnly ?? false,
uploadFolderId: link.uploadFolderId ?? null,
uploadFolderName: link.uploadFolderName ?? "Home",
+ uploadFolderIds: (() => {
+ const ids = Array.isArray((link as any).uploadFolderIds)
+ ? ((link as any).uploadFolderIds as string[])
+ : [];
+ if (ids.length > 0) return ids;
+ return link.uploadFolderId ? [link.uploadFolderId] : [];
+ })(),
+ uploadFolders: (() => {
+ const folders = Array.isArray((link as any).uploadFolders)
+ ? ((link as any).uploadFolders as {
+ id: string;
+ name: string;
+ path?: string | null;
+ }[])
+ : [];
+ if (folders.length > 0) return folders;
+ return link.uploadFolderId
+ ? [
+ {
+ id: link.uploadFolderId,
+ name: link.uploadFolderName ?? "Folder",
+ },
+ ]
+ : [];
+ })(),
enableIndexFile: link.enableIndexFile ?? false,
permissionGroupId: link.permissionGroupId ?? null,
welcomeMessage: link.welcomeMessage ?? null,
diff --git a/components/view/dataroom/dataroom-view.tsx b/components/view/dataroom/dataroom-view.tsx
index 97f5547a..f81be107 100644
--- a/components/view/dataroom/dataroom-view.tsx
+++ b/components/view/dataroom/dataroom-view.tsx
@@ -43,6 +43,14 @@ export type DEFAULT_DATAROOM_VIEW_TYPE = {
viewerId?: string;
conversationsEnabled?: boolean;
enableVisitorUpload?: boolean;
+ /**
+ * When the link restricts uploads to specific folders this is the ordered
+ * allow-list. `null`/`undefined` means "no restriction — visitor may upload
+ * into whichever folder they're currently browsing".
+ */
+ uploadFolderAllowList?:
+ | { id: string; name: string; path: string }[]
+ | null;
isTeamMember?: boolean;
agentsEnabled?: boolean;
dataroomName?: string;
@@ -163,6 +171,7 @@ export default function DataroomView({
viewerId,
conversationsEnabled,
enableVisitorUpload,
+ uploadFolderAllowList,
isTeamMember,
agentsEnabled,
dataroomName,
@@ -200,6 +209,7 @@ export default function DataroomView({
viewerId,
conversationsEnabled,
enableVisitorUpload,
+ uploadFolderAllowList,
isTeamMember,
agentsEnabled,
dataroomName,
diff --git a/components/view/dataroom/document-upload-modal.tsx b/components/view/dataroom/document-upload-modal.tsx
index 488faf88..aceb2271 100644
--- a/components/view/dataroom/document-upload-modal.tsx
+++ b/components/view/dataroom/document-upload-modal.tsx
@@ -1,4 +1,4 @@
-import { useState } from "react";
+import { useEffect, useMemo, useState } from "react";
import {
CheckCircle2,
@@ -14,28 +14,92 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
import { ViewerUploadComponent } from "@/components/viewer-upload-component";
+type AllowedFolder = {
+ id: string;
+ name: string;
+ path?: string | null;
+};
+
+/**
+ * "Upload Document" entry-point for dataroom visitors.
+ *
+ * Destination selection rules:
+ * - If the admin restricted uploads to a single folder, that folder is shown
+ * read-only.
+ * - If the admin restricted uploads to multiple folders, the visitor picks
+ * one via a select. If the folder they're currently browsing is on the
+ * allow-list, it is pre-selected.
+ * - If the admin didn't restrict uploads, we fall back to the folder the
+ * visitor is currently in (original behaviour).
+ */
export function DocumentUploadModal({
linkId,
dataroomId,
viewerId,
folderId,
folderName,
+ allowedFolders,
}: {
linkId: string;
dataroomId: string;
viewerId: string;
+ /** Folder the viewer is currently browsing (undefined = root/home). */
folderId?: string;
- /** Display name of the current folder (undefined = root) */
+ /** Display name of the current folder (undefined = root). */
folderName?: string;
+ /**
+ * Restricted allow-list of folders this link may upload into. `null` or
+ * `undefined` means "no restriction".
+ */
+ allowedFolders?: AllowedFolder[] | null;
}) {
const [isOpen, setIsOpen] = useState(false);
const [uploadSuccess, setUploadSuccess] = useState(false);
+ const hasRestriction = !!allowedFolders && allowedFolders.length > 0;
+
+ // Decide the default destination.
+ // When restricted, prefer the current folder if it's allowed, otherwise the
+ // first folder in the admin-defined allow-list. Without a restriction, we
+ // default to the folder the viewer is currently in.
+ const defaultDestination = useMemo<string | undefined>(() => {
+ if (hasRestriction) {
+ if (folderId && allowedFolders!.some((f) => f.id === folderId)) {
+ return folderId;
+ }
+ return allowedFolders![0]?.id;
+ }
+ return folderId;
+ }, [hasRestriction, allowedFolders, folderId]);
+
+ const [destinationId, setDestinationId] = useState<string | undefined>(
+ defaultDestination,
+ );
+
+ // Keep the picker in sync when the viewer navigates between folders while
+ // the modal is closed.
+ useEffect(() => {
+ setDestinationId(defaultDestination);
+ }, [defaultDestination]);
+
+ const destinationName = useMemo(() => {
+ if (hasRestriction) {
+ return allowedFolders!.find((f) => f.id === destinationId)?.name;
+ }
+ return folderName;
+ }, [hasRestriction, allowedFolders, destinationId, folderName]);
+
const handleUploadSuccess = () => {
setUploadSuccess(true);
- // Auto-close the dialog after a short delay to show success message
setTimeout(() => {
setIsOpen(false);
setUploadSuccess(false);
@@ -49,6 +113,9 @@ export function DocumentUploadModal({
}
};
+ const showSelect = hasRestriction && allowedFolders!.length > 1;
+ const showReadOnlyRestriction = hasRestriction && allowedFolders!.length === 1;
+
return (
<>
<Button
@@ -73,17 +140,50 @@ export function DocumentUploadModal({
Your document will appear immediately in the dataroom and will be
processed in the background.
</p>
- {folderName && (
+
+ {showSelect ? (
+ <div className="mt-3 space-y-1.5">
+ <label className="flex items-center gap-1.5 text-xs font-medium text-muted-foreground">
+ <FolderIcon className="h-3.5 w-3.5" />
+ Destination folder
+ </label>
+ <Select
+ value={destinationId}
+ onValueChange={(value) => setDestinationId(value)}
+ >
+ <SelectTrigger className="h-9 w-full">
+ <SelectValue placeholder="Select destination folder" />
+ </SelectTrigger>
+ <SelectContent>
+ {allowedFolders!.map((folder) => (
+ <SelectItem key={folder.id} value={folder.id}>
+ <span className="flex items-center gap-2">
+ <FolderIcon className="h-3.5 w-3.5" />
+ <span className="max-w-[320px] truncate">
+ {folder.name}
+ </span>
+ </span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ ) : destinationName ? (
<div className="mt-2 flex items-center gap-1.5 text-xs text-muted-foreground">
<FolderIcon className="h-3.5 w-3.5" />
<span>
Uploading to:{" "}
<span className="font-medium text-foreground">
- {folderName}
+ {destinationName}
</span>
+ {showReadOnlyRestriction ? (
+ <span className="ml-1 text-muted-foreground">
+ (set by the dataroom owner)
+ </span>
+ ) : null}
</span>
</div>
- )}
+ ) : null}
</DialogHeader>
<div className="min-w-0 px-6 py-5">
@@ -105,7 +205,7 @@ export function DocumentUploadModal({
dataroomId,
}}
teamId="visitor-upload"
- folderId={folderId}
+ folderId={destinationId}
onUploadSuccess={handleUploadSuccess}
/>
)}
diff --git a/components/view/viewer/dataroom-viewer.tsx b/components/view/viewer/dataroom-viewer.tsx
index 917a706e..9612c75f 100644
--- a/components/view/viewer/dataroom-viewer.tsx
+++ b/components/view/viewer/dataroom-viewer.tsx
@@ -655,6 +655,7 @@ export default function DataroomViewer({
? folders.find((f) => f.id === folderId)?.name
: undefined
}
+ allowedFolders={viewData?.uploadFolderAllowList}
/>
)}
</div>
diff --git a/ee/features/permissions/components/dataroom-link-sheet.tsx b/ee/features/permissions/components/dataroom-link-sheet.tsx
index 3de80e57..b2259676 100644
--- a/ee/features/permissions/components/dataroom-link-sheet.tsx
+++ b/ee/features/permissions/components/dataroom-link-sheet.tsx
@@ -637,6 +637,7 @@ export function DataroomLinkSheet({
"enableUpload",
"isFileRequestOnly",
"uploadFolderId",
+ "uploadFolderIds",
"enableIndexFile",
"permissionGroupId",
"tags",
diff --git a/lib/types.ts b/lib/types.ts
index f7bd20ba..99788e83 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -67,6 +67,7 @@ export interface LinkWithViews extends Link {
customFields: CustomField[];
tags: TagProps[];
uploadFolderName: string | undefined;
+ uploadFolders?: { id: string; name: string; path: string | null }[];
visitorGroups?: { visitorGroupId: string }[];
}
diff --git a/pages/api/links/[id]/index.ts b/pages/api/links/[id]/index.ts
index 3d0043f7..671f1d01 100644
--- a/pages/api/links/[id]/index.ts
+++ b/pages/api/links/[id]/index.ts
@@ -19,6 +19,37 @@ import { checkGlobalBlockList } from "@/lib/utils/global-block-list";
import { DomainObject } from "..";
import { authOptions } from "../../auth/[...nextauth]";
+/** See pages/api/links/index.ts — same semantics. */
+function normalizeUploadFolderIds(linkData: {
+ uploadFolderIds?: unknown;
+ uploadFolderId?: unknown;
+}): string[] {
+ if (Array.isArray(linkData.uploadFolderIds)) {
+ const ids: string[] = [];
+ for (const id of linkData.uploadFolderIds) {
+ if (typeof id === "string" && id.length > 0) ids.push(id);
+ }
+ if (ids.length > 0) {
+ return Array.from(new Set(ids));
+ }
+ }
+ if (
+ typeof linkData.uploadFolderId === "string" &&
+ linkData.uploadFolderId.length > 0
+ ) {
+ return Array.from(new Set([linkData.uploadFolderId]));
+ }
+ return [];
+}
+
+function primaryUploadFolderId(linkData: {
+ uploadFolderIds?: unknown;
+ uploadFolderId?: unknown;
+}): string | null {
+ const ids = normalizeUploadFolderIds(linkData);
+ return ids[0] ?? null;
+}
+
export default async function handle(
req: NextApiRequest,
res: NextApiResponse,
@@ -377,6 +408,46 @@ export default async function handle(
}
}
+ // Validate upload folder IDs belong to the target dataroom. Without this
+ // check, a tampered payload could persist arbitrary folder cuids (including
+ // ones from other datarooms/teams) into the link.
+ let validatedUploadFolderIds: string[] = [];
+ let validatedPrimaryUploadFolderId: string | null = null;
+ if (linkData.enableUpload) {
+ const normalizedIds = normalizeUploadFolderIds(linkData);
+ const primaryId = primaryUploadFolderId(linkData);
+
+ if (normalizedIds.length > 0) {
+ if (!dataroomLink || !targetId) {
+ return res.status(400).json({
+ error: "Upload folders can only be assigned to dataroom links.",
+ });
+ }
+
+ const validFolders = await prisma.dataroomFolder.findMany({
+ where: {
+ id: { in: normalizedIds },
+ dataroomId: targetId,
+ },
+ select: { id: true },
+ });
+ const validIdSet = new Set(validFolders.map((f) => f.id));
+
+ if (validIdSet.size !== normalizedIds.length) {
+ return res.status(400).json({
+ error:
+ "One or more upload folders do not belong to this data room.",
+ });
+ }
+
+ validatedUploadFolderIds = normalizedIds.filter((id) =>
+ validIdSet.has(id),
+ );
+ validatedPrimaryUploadFolderId =
+ primaryId && validIdSet.has(primaryId) ? primaryId : null;
+ }
+ }
+
const updatedLink = await prisma.$transaction(async (tx) => {
const link = await tx.link.update({
where: { id, teamId },
@@ -457,7 +528,12 @@ export default async function handle(
enableAIAgents: linkData.enableAIAgents || false,
enableUpload: linkData.enableUpload || false,
isFileRequestOnly: linkData.isFileRequestOnly || false,
- uploadFolderId: linkData.uploadFolderId || null,
+ uploadFolderIds: linkData.enableUpload
+ ? validatedUploadFolderIds
+ : [],
+ uploadFolderId: linkData.enableUpload
+ ? validatedPrimaryUploadFolderId
+ : null,
},
include: {
customFields: true,
diff --git a/pages/api/links/index.ts b/pages/api/links/index.ts
index 92fa6c9d..9bea0ec6 100644
--- a/pages/api/links/index.ts
+++ b/pages/api/links/index.ts
@@ -26,6 +26,43 @@ export interface DomainObject {
slug: string;
}
+/**
+ * Normalize the list of allowed upload folder ids from the incoming payload.
+ * Accepts the new `uploadFolderIds` array as well as the legacy single
+ * `uploadFolderId` field, and deduplicates the result while dropping falsy
+ * entries. An empty array represents "visitor may upload anywhere".
+ */
+function normalizeUploadFolderIds(linkData: {
+ uploadFolderIds?: unknown;
+ uploadFolderId?: unknown;
+}): string[] {
+ const ids: string[] = [];
+ if (Array.isArray(linkData.uploadFolderIds)) {
+ for (const id of linkData.uploadFolderIds) {
+ if (typeof id === "string" && id.length > 0) ids.push(id);
+ }
+ }
+ if (
+ typeof linkData.uploadFolderId === "string" &&
+ linkData.uploadFolderId.length > 0
+ ) {
+ ids.push(linkData.uploadFolderId);
+ }
+ return Array.from(new Set(ids));
+}
+
+/**
+ * Legacy single-folder column mirrors the first entry of the allow-list so
+ * callers still reading the old column keep working.
+ */
+function primaryUploadFolderId(linkData: {
+ uploadFolderIds?: unknown;
+ uploadFolderId?: unknown;
+}): string | null {
+ const ids = normalizeUploadFolderIds(linkData);
+ return ids[0] ?? null;
+}
+
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
@@ -192,6 +229,46 @@ export default async function handler(
}
}
+ // Validate upload folder IDs belong to the target dataroom. Without this
+ // check, a tampered payload could persist arbitrary folder cuids
+ // (including ones from other datarooms/teams) into the link.
+ let validatedUploadFolderIds: string[] = [];
+ let validatedPrimaryUploadFolderId: string | null = null;
+ if (linkData.enableUpload) {
+ const normalizedIds = normalizeUploadFolderIds(linkData);
+ const primaryId = primaryUploadFolderId(linkData);
+
+ if (normalizedIds.length > 0) {
+ if (!dataroomLink || !targetId) {
+ return res.status(400).json({
+ error: "Upload folders can only be assigned to dataroom links.",
+ });
+ }
+
+ const validFolders = await prisma.dataroomFolder.findMany({
+ where: {
+ id: { in: normalizedIds },
+ dataroomId: targetId,
+ },
+ select: { id: true },
+ });
+ const validIdSet = new Set(validFolders.map((f) => f.id));
+
+ if (validIdSet.size !== normalizedIds.length) {
+ return res.status(400).json({
+ error:
+ "One or more upload folders do not belong to this data room.",
+ });
+ }
+
+ validatedUploadFolderIds = normalizedIds.filter((id) =>
+ validIdSet.has(id),
+ );
+ validatedPrimaryUploadFolderId =
+ primaryId && validIdSet.has(primaryId) ? primaryId : null;
+ }
+ }
+
// Fetch the link and its related document from the database
const updatedLink = await prisma.$transaction(async (tx) => {
const link = await tx.link.create({
@@ -252,7 +329,8 @@ export default async function handler(
...(linkData.enableUpload && {
enableUpload: linkData.enableUpload,
isFileRequestOnly: linkData.isFileRequestOnly,
- uploadFolderId: linkData.uploadFolderId,
+ uploadFolderIds: validatedUploadFolderIds,
+ uploadFolderId: validatedPrimaryUploadFolderId,
}),
enableAIAgents: linkData.enableAIAgents || false,
enableConversation: linkData.enableConversation || false,
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/links.ts b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/links.ts
index cd37f3ab..5aedc2ed 100644
--- a/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/links.ts
+++ b/pages/api/teams/[teamId]/datarooms/[id]/groups/[groupId]/links.ts
@@ -87,17 +87,37 @@ export default async function handle(
if (link.password !== null) {
link.password = decryptEncrpytedPassword(link.password);
}
- // Get the upload folder name if it exists
- if (link.enableUpload && link.uploadFolderId !== null) {
- const folder = await prisma.dataroomFolder.findUnique({
- where: {
- id: link.uploadFolderId,
- },
- select: {
- name: true,
- },
- });
- link.uploadFolderName = folder?.name;
+ // Get the upload folder name(s) if any folder is restricted.
+ // `uploadFolderIds` is the new source of truth, but until the
+ // legacy `uploadFolderId` column has been backfilled into it we
+ // fall back to `[uploadFolderId]` for rows where the array is
+ // still empty. The fallback becomes inert post-backfill.
+ if (link.enableUpload) {
+ const allowedIds: string[] =
+ Array.isArray(link.uploadFolderIds) &&
+ link.uploadFolderIds.length > 0
+ ? link.uploadFolderIds.filter(
+ (id): id is string => typeof id === "string" && !!id,
+ )
+ : link.uploadFolderId
+ ? [link.uploadFolderId]
+ : [];
+
+ if (allowedIds.length > 0) {
+ const folders = await prisma.dataroomFolder.findMany({
+ where: {
+ id: { in: allowedIds },
+ dataroomId,
+ },
+ select: { id: true, name: true, path: true },
+ });
+ const byId = new Map(folders.map((f) => [f.id, f]));
+ const ordered = allowedIds
+ .map((id) => byId.get(id))
+ .filter((f): f is (typeof folders)[number] => !!f);
+ link.uploadFolders = ordered;
+ link.uploadFolderName = ordered[0]?.name;
+ }
}
// Get the tags for the link
const tags = await prisma.tag.findMany({
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/links.ts b/pages/api/teams/[teamId]/datarooms/[id]/links.ts
index f38c8c4a..24788bb2 100644
--- a/pages/api/teams/[teamId]/datarooms/[id]/links.ts
+++ b/pages/api/teams/[teamId]/datarooms/[id]/links.ts
@@ -83,16 +83,37 @@ export default async function handle(
if (link.password !== null) {
link.password = decryptEncrpytedPassword(link.password);
}
- if (link.enableUpload && link.uploadFolderId !== null) {
- const folder = await prisma.dataroomFolder.findUnique({
- where: {
- id: link.uploadFolderId,
- },
- select: {
- name: true,
- },
- });
- link.uploadFolderName = folder?.name;
+ if (link.enableUpload) {
+ // `uploadFolderIds` is the new source of truth, but until the
+ // legacy `uploadFolderId` column has been backfilled into it we
+ // fall back to `[uploadFolderId]` for rows where the array is
+ // still empty. The fallback becomes inert post-backfill.
+ const allowedIds: string[] =
+ Array.isArray(link.uploadFolderIds) &&
+ link.uploadFolderIds.length > 0
+ ? link.uploadFolderIds.filter(
+ (id): id is string => typeof id === "string" && !!id,
+ )
+ : link.uploadFolderId
+ ? [link.uploadFolderId]
+ : [];
+
+ if (allowedIds.length > 0) {
+ const folders = await prisma.dataroomFolder.findMany({
+ where: {
+ id: { in: allowedIds },
+ dataroomId,
+ },
+ select: { id: true, name: true, path: true },
+ });
+ // Preserve the admin-selected order when possible.
+ const byId = new Map(folders.map((f) => [f.id, f]));
+ const ordered = allowedIds
+ .map((id) => byId.get(id))
+ .filter((f): f is (typeof folders)[number] => !!f);
+ link.uploadFolders = ordered;
+ link.uploadFolderName = ordered[0]?.name;
+ }
}
const tags = await prisma.tag.findMany({
where: {
diff --git a/prisma/migrations/20260422000000_add_link_upload_folder_ids/migration.sql b/prisma/migrations/20260422000000_add_link_upload_folder_ids/migration.sql
new file mode 100644
index 00000000..ca9324d9
--- /dev/null
+++ b/prisma/migrations/20260422000000_add_link_upload_folder_ids/migration.sql
@@ -0,0 +1,2 @@
+-- AlterTable
+ALTER TABLE "Link" ADD COLUMN "uploadFolderIds" TEXT[] DEFAULT ARRAY[]::TEXT[];
diff --git a/prisma/schema/link.prisma b/prisma/schema/link.prisma
index 2fb7bae1..77c0f0c8 100644
--- a/prisma/schema/link.prisma
+++ b/prisma/schema/link.prisma
@@ -80,7 +80,8 @@ model Link {
// upload
enableUpload Boolean? @default(false) // Optional give user a option to enable the upload document function
isFileRequestOnly Boolean? @default(false) // Optional give user a option to enable the file request only
- uploadFolderId String? // This can be nullable, indicating upload to root folder, either document folder or dataroom folder
+ uploadFolderId String? // Deprecated: first entry of `uploadFolderIds`; kept for backward compatibility. Nullable = no restriction.
+ uploadFolderIds String[] @default([]) // Allow-list of dataroom folder ids where visitors may upload. Empty = no restriction (visitor chooses).
enableIndexFile Boolean? @default(false)
uploadedDocuments DocumentUpload[]