Skip to content

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

feat: improve name for files without extensions

Marc Seitzd65dda3adade
diff --git a/components/datarooms/edit-dataroom-document-modal.tsx b/components/datarooms/edit-dataroom-document-modal.tsx
index a78c0226..41a2db15 100644
--- a/components/datarooms/edit-dataroom-document-modal.tsx
+++ b/components/datarooms/edit-dataroom-document-modal.tsx
@@ -30,11 +30,14 @@ type DataroomIncludeDocumentsItem =
id: string;
folderId: string | null;
hierarchicalIndex: string | null;
- document: {
- id: string;
- name: string;
- type: string;
- };
+ document:
+ | {
+ id: string;
+ name: string;
+ type: string;
+ }
+ | null
+ | undefined;
};
function updateDocNameInDocuments(
@@ -92,13 +95,19 @@ function updateDocNameInIncludeDocumentsTree(
});
return items.map((item) => {
- if ("childFolders" in item) {
- return updateFolder(item);
+ if ("document" in item) {
+ const { document } = item;
+
+ if (!document) {
+ return item;
+ }
+
+ return document.id === docId
+ ? { ...item, document: { ...document, name: newName } }
+ : item;
}
- return item.document.id === docId
- ? { ...item, document: { ...item.document, name: newName } }
- : item;
+ return updateFolder(item);
});
}
diff --git a/components/documents/document-header.tsx b/components/documents/document-header.tsx
index f94de291..497ea360 100644
--- a/components/documents/document-header.tsx
+++ b/components/documents/document-header.tsx
@@ -36,7 +36,10 @@ import {
DocumentWithVersion,
} from "@/lib/types";
import { cn } from "@/lib/utils";
-import { supportsAdvancedExcelMode } from "@/lib/utils/get-content-type";
+import {
+ ensureFileExtension,
+ supportsAdvancedExcelMode,
+} from "@/lib/utils/get-content-type";
import { fileIcon } from "@/lib/utils/get-file-icon";
import FileUp from "@/components/shared/icons/file-up";
@@ -506,7 +509,11 @@ export default function DocumentHeader({
const url = window.URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
- a.download = prismaDocument.name;
+ a.download = ensureFileExtension({
+ name: prismaDocument.name,
+ contentType: documentVersion.contentType,
+ type: documentVersion.type,
+ });
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
diff --git a/components/view/dataroom/document-card.tsx b/components/view/dataroom/document-card.tsx
index 4c856fa3..8d5f548e 100644
--- a/components/view/dataroom/document-card.tsx
+++ b/components/view/dataroom/document-card.tsx
@@ -8,6 +8,8 @@ import { toast } from "sonner";
import { timeAgo } from "@/lib/utils";
import { cn } from "@/lib/utils";
+import { downloadFromLinkEndpoint } from "@/lib/utils/download-document";
+import { ensureFileExtension } from "@/lib/utils/get-content-type";
import { fileIcon } from "@/lib/utils/get-file-icon";
import {
HIERARCHICAL_DISPLAY_STYLE,
@@ -106,77 +108,18 @@ export default function DocumentCard({
return;
}
- const downloadPromise = (async () => {
- const response = await fetch(`/api/links/download/dataroom-document`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- linkId,
- viewId,
- documentId: document.id,
- }),
- });
-
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
- const errorMessage = errorData.error || "Failed to download file";
- throw new Error(errorMessage);
- }
-
- // Check if the response is JSON (for direct downloads) or binary (for buffered files)
- const contentType = response.headers.get("content-type");
-
- // If it's a watermarked PDF, handle it with the buffer method
- if (contentType?.includes("application/pdf")) {
- const blob = await response.blob();
- const url = window.URL.createObjectURL(blob);
-
- const link = window.document.createElement("a");
- link.href = url;
- const disposition = response.headers.get("content-disposition");
- const filenameMatch =
- disposition && disposition.match(/filename="(.+)"/);
- link.download = filenameMatch
- ? decodeURIComponent(filenameMatch[1])
- : document.name;
- link.rel = "noopener noreferrer";
- window.document.body.appendChild(link);
- link.click();
-
- setTimeout(() => {
- window.URL.revokeObjectURL(url);
- window.document.body.removeChild(link);
- }, 100);
-
- return "File downloaded successfully";
- }
-
- // For all other files, use a hidden iframe to trigger the download
- if (contentType?.includes("application/json")) {
- const data = await response.json();
-
- const iframe = window.document.createElement("iframe");
- iframe.style.display = "none";
- window.document.body.appendChild(iframe);
- iframe.src = data.downloadUrl;
-
- setTimeout(() => {
- if (iframe.parentNode) {
- window.document.body.removeChild(iframe);
- }
- }, 5000);
-
- return "File downloaded successfully";
- }
-
- throw new Error("Unexpected response format");
- })();
+ const downloadPromise = downloadFromLinkEndpoint({
+ endpoint: "/api/links/download/dataroom-document",
+ body: { linkId, viewId, documentId: document.id },
+ fallbackFileName: ensureFileExtension({
+ name: document.name,
+ type: document.versions[0]?.type,
+ }),
+ });
toast.promise(downloadPromise, {
loading: "Preparing download...",
- success: (message) => message,
+ success: "File downloaded successfully",
error: (err) => err.message || "Failed to download file",
});
};
diff --git a/components/view/nav.tsx b/components/view/nav.tsx
index 59456130..e2771b55 100644
--- a/components/view/nav.tsx
+++ b/components/view/nav.tsx
@@ -18,6 +18,7 @@ import {
import { toast } from "sonner";
import { createAdaptiveSurfacePalette } from "@/lib/utils/create-adaptive-surface-palette";
+import { downloadFromLinkEndpoint } from "@/lib/utils/download-document";
import {
DropdownMenu,
@@ -131,77 +132,26 @@ export default function Nav({
}
if (!allowDownload || type === "notion") return;
- const downloadPromise = (async () => {
- const response = await fetch(`/api/links/download`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ linkId, viewId }),
- });
+ // The server only produces a buffered binary response (which is when this
+ // fallback is consulted) for watermarked PDFs today, but other viewers
+ // ("sheet", future flows) share this Nav. Derive a safe fallback from the
+ // viewer `type` rather than hardcoding ".pdf" so non-PDF flows don't get
+ // a misleading extension if the contract ever broadens. We don't have the
+ // document name here, so we use a generic "document"-stem fallback.
+ const fallbackFileName =
+ !type || type === "pdf" ? "document.pdf" : "document";
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
- const errorMessage = errorData.error || "Failed to download file";
- throw new Error(errorMessage);
- }
-
- // Check if the response is a PDF file (for watermarked PDFs)
- const contentType = response.headers.get("content-type");
- if (contentType === "application/pdf") {
- // Handle direct PDF download (watermarked PDFs)
- const pdfBlob = await response.blob();
- const blobUrl = window.URL.createObjectURL(pdfBlob);
-
- // Extract filename from Content-Disposition header
- const contentDisposition = response.headers.get("content-disposition");
- let filename = "document.pdf";
- if (contentDisposition) {
- const filenameMatch = contentDisposition.match(
- /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/,
- );
- if (filenameMatch && filenameMatch[1]) {
- filename = decodeURIComponent(
- filenameMatch[1].replace(/['"]/g, ""),
- );
- }
- }
-
- const link = document.createElement("a");
- link.href = blobUrl;
- link.rel = "noopener noreferrer";
- link.download = filename;
- document.body.appendChild(link);
- link.click();
-
- setTimeout(() => {
- window.URL.revokeObjectURL(blobUrl);
- document.body.removeChild(link);
- }, 100);
- } else {
- // Handle JSON response with downloadUrl (non-watermarked files)
- const { downloadUrl } = await response.json();
-
- const iframe = document.createElement("iframe");
- iframe.style.display = "none";
- document.body.appendChild(iframe);
- iframe.src = downloadUrl;
-
- setTimeout(() => {
- if (iframe.parentNode) {
- document.body.removeChild(iframe);
- }
- }, 5000);
- }
-
- return "File downloaded successfully";
- })();
+ const downloadPromise = downloadFromLinkEndpoint({
+ endpoint: "/api/links/download",
+ body: { linkId, viewId },
+ fallbackFileName,
+ });
toast.promise(downloadPromise, {
loading: hasWatermark
? "Preparing download with watermark..."
: "Preparing download...",
- success: (message) => message,
+ success: "File downloaded successfully",
error: (err) => err.message || "Failed to download file",
});
};
diff --git a/components/view/viewer/download-only-viewer.tsx b/components/view/viewer/download-only-viewer.tsx
index 042ef674..f19eaeff 100644
--- a/components/view/viewer/download-only-viewer.tsx
+++ b/components/view/viewer/download-only-viewer.tsx
@@ -7,6 +7,8 @@ import { toast } from "sonner";
import { useSafePageViewTracker } from "@/lib/tracking/safe-page-view-tracker";
import { getTrackingOptions } from "@/lib/tracking/tracking-config";
+import { downloadFromLinkEndpoint } from "@/lib/utils/download-document";
+import { ensureFileExtension } from "@/lib/utils/get-content-type";
import { Button } from "@/components/ui/button";
@@ -197,62 +199,18 @@ export default function DownloadOnlyViewer({
}
if (!allowDownload) return;
- const downloadPromise = (async () => {
- const response = await fetch(`/api/links/download`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({ linkId, viewId }),
- });
-
- if (!response.ok) {
- const errorData = await response.json().catch(() => ({}));
- const errorMessage = errorData.error || "Failed to download file";
- throw new Error(errorMessage);
- }
-
- // Check if the response is a PDF file (for watermarked PDFs)
- const contentType = response.headers.get("content-type");
- if (contentType === "application/pdf") {
- // Handle direct PDF download (watermarked PDFs)
- const pdfBlob = await response.blob();
- const url = URL.createObjectURL(pdfBlob);
-
- const a = document.createElement("a");
- a.href = url;
- a.download = `${documentName || "document"}.pdf`;
- a.rel = "noopener noreferrer";
- document.body.appendChild(a);
- a.click();
-
- // Clean up
- setTimeout(() => {
- URL.revokeObjectURL(url);
- document.body.removeChild(a);
- }, 100);
- } else {
- // Handle JSON response with downloadUrl (non-watermarked files)
- const { downloadUrl } = await response.json();
-
- const iframe = document.createElement("iframe");
- iframe.style.display = "none";
- document.body.appendChild(iframe);
- iframe.src = downloadUrl;
-
- setTimeout(() => {
- if (iframe.parentNode) {
- document.body.removeChild(iframe);
- }
- }, 5000);
- }
-
- return "File downloaded successfully";
- })();
+ const downloadPromise = downloadFromLinkEndpoint({
+ endpoint: "/api/links/download",
+ body: { linkId, viewId },
+ fallbackFileName: ensureFileExtension({
+ name: documentName || "document",
+ contentType: "application/pdf",
+ }),
+ });
toast.promise(downloadPromise, {
loading: "Preparing download...",
- success: (message) => message,
+ success: "File downloaded successfully",
error: (err) => err.message || "Failed to download file",
});
};
diff --git a/components/view/viewer/pdf-default-viewer.tsx b/components/view/viewer/pdf-default-viewer.tsx
index 91bf3aa9..3d18060e 100644
--- a/components/view/viewer/pdf-default-viewer.tsx
+++ b/components/view/viewer/pdf-default-viewer.tsx
@@ -6,6 +6,7 @@ import { Document, Page, pdfjs } from "react-pdf";
import { useSafePageViewTracker } from "@/lib/tracking/safe-page-view-tracker";
import { getTrackingOptions } from "@/lib/tracking/tracking-config";
+import { ensureFileExtension } from "@/lib/utils/get-content-type";
import Nav from "@/components/view/nav";
@@ -231,7 +232,10 @@ export default function PDFViewer(props: any) {
//create <a/> to download the file
const a = document.createElement("a");
a.href = window.URL.createObjectURL(fileData);
- a.download = props.name;
+ a.download = ensureFileExtension({
+ name: props.name,
+ contentType: "application/pdf",
+ });
document.body.appendChild(a);
a.click();
diff --git a/lib/dataroom/build-bulk-download-structure.ts b/lib/dataroom/build-bulk-download-structure.ts
new file mode 100644
index 00000000..f92afa4a
--- /dev/null
+++ b/lib/dataroom/build-bulk-download-structure.ts
@@ -0,0 +1,317 @@
+import { DocumentStorageType } from "@prisma/client";
+
+import { ensureFileExtension } from "@/lib/utils/get-content-type";
+import { safeSlugify } from "@/lib/utils";
+
+import {
+ buildFolderNameMap,
+ buildFolderPathsFromHierarchy,
+ type FolderInput,
+} from "./build-folder-hierarchy";
+
+/**
+ * Shape of a single file inside the lambda payload.
+ *
+ * The bulk-download lambda accepts the full shape; the freeze archive
+ * lambda accepts the same shape and ignores the extra fields. Keeping a
+ * single shape lets us share the builder.
+ */
+export type BulkDownloadFile = {
+ name: string;
+ key: string;
+ type?: string;
+ numPages?: number;
+ needsWatermark?: boolean;
+ size?: number;
+};
+
+export type BulkDownloadFolderStructure = {
+ [path: string]: {
+ name: string;
+ path: string;
+ files: BulkDownloadFile[];
+ };
+};
+
+/**
+ * The minimum document/version shape the builder needs. Callers usually
+ * select a few extra fields for their own use; this type is intentionally
+ * loose so they don't have to match it exactly.
+ */
+export interface BulkDownloadDocumentInput {
+ id: string;
+ folderId: string | null;
+ document: {
+ id?: string;
+ name: string;
+ versions: Array<{
+ type: string | null;
+ file: string;
+ originalFile: string | null;
+ contentType: string | null;
+ storageType: DocumentStorageType;
+ numPages?: number | null;
+ fileSize?: bigint | number | null;
+ }>;
+ };
+}
+
+export interface BuildBulkDownloadStructureParams {
+ /**
+ * Full unfiltered folder list for this dataroom. Used for path
+ * computation so that parent folders removed by permission filtering
+ * still produce the correct child paths (e.g. "/legal/contracts" instead
+ * of just "/contracts" when the viewer can't download from "/legal").
+ */
+ fullFolders: FolderInput[];
+ /**
+ * Folders the viewer can actually download from. Pass the same list as
+ * `fullFolders` if no permission filtering is needed (e.g. team admin).
+ */
+ includedFolders: FolderInput[];
+ /**
+ * Documents the viewer can download. Notion documents and VERCEL_BLOB-
+ * stored documents are filtered out automatically (the lambda can't
+ * handle them).
+ */
+ includedDocuments: BulkDownloadDocumentInput[];
+ /**
+ * When true, PDFs are picked from `version.file` (the rendered, ready
+ * for watermarking copy). All other types and non-watermarked links use
+ * `version.originalFile ?? version.file`.
+ */
+ enableWatermark?: boolean;
+ /**
+ * If provided, the resulting structure is rooted at "/<safeSlugify(name)>"
+ * instead of "/" - used for folder-scoped downloads where the viewer
+ * downloaded a single folder rather than the whole dataroom.
+ */
+ rootFolder?: { id: string; name: string };
+}
+
+export interface BuildBulkDownloadStructureResult {
+ folderStructure: BulkDownloadFolderStructure;
+ fileKeys: string[];
+ /**
+ * The subset of `includedDocuments` that actually made it into the
+ * structure (i.e. excluding Notion / VERCEL_BLOB / missing-version
+ * docs). Useful for view-tracking / metadata where we want to record
+ * exactly what was downloaded.
+ */
+ downloadableDocuments: BulkDownloadDocumentInput[];
+}
+
+const isDownloadableVersion = (
+ version: BulkDownloadDocumentInput["document"]["versions"][number] | undefined,
+): boolean =>
+ !!version &&
+ version.type !== "notion" &&
+ version.storageType !== DocumentStorageType.VERCEL_BLOB;
+
+const pickFileKey = (
+ version: BulkDownloadDocumentInput["document"]["versions"][number],
+ enableWatermark: boolean,
+): string =>
+ enableWatermark && version.type === "pdf"
+ ? version.file
+ : (version.originalFile ?? version.file);
+
+const versionNeedsWatermark = (
+ version: BulkDownloadDocumentInput["document"]["versions"][number],
+ enableWatermark: boolean,
+): boolean | undefined => {
+ if (!enableWatermark) return undefined;
+ return version.type === "pdf" || version.type === "image" || undefined;
+};
+
+/**
+ * Strip the leading "/<rootFolderId>'s computed path" prefix from a
+ * descendant path. Used when scoping the download under a single folder.
+ */
+const stripRootPath = (descendantPath: string, rootPath: string): string => {
+ if (descendantPath === rootPath) return "";
+ if (rootPath && descendantPath.startsWith(rootPath + "/")) {
+ return descendantPath.slice(rootPath.length + 1);
+ }
+ // Descendant isn't actually under the root - shouldn't happen, but
+ // fall back to treating it as the descendant's own path.
+ return descendantPath.replace(/^\//, "");
+};
+
+/**
+ * Build the `folderStructure` + `fileKeys` payload that the bulk-download
+ * lambda (and the freeze-archive lambda) expects.
+ *
+ * This is the single source of truth for:
+ * - mapping folder hierarchy to slugified zip paths
+ * - choosing originalFile vs watermark-rendered file
+ * - applying the renamed-document-name + extension fix
+ * - filtering out unsupported storage types (Notion / VERCEL_BLOB)
+ *
+ * Callers are responsible for permission-filtering folders and documents
+ * before passing them in. The full unfiltered folder list is still needed
+ * (as `fullFolders`) so child paths render correctly when a parent has
+ * canView but not canDownload.
+ */
+export function buildBulkDownloadStructure({
+ fullFolders,
+ includedFolders,
+ includedDocuments,
+ enableWatermark = false,
+ rootFolder,
+}: BuildBulkDownloadStructureParams): BuildBulkDownloadStructureResult {
+ const folderStructure: BulkDownloadFolderStructure = {};
+ const fileKeys: string[] = [];
+ const downloadableDocuments: BulkDownloadDocumentInput[] = [];
+
+ const computedPathMap = buildFolderPathsFromHierarchy(fullFolders);
+ const folderNameMap = buildFolderNameMap(fullFolders, computedPathMap);
+
+ // For folder-scoped downloads, everything is rooted at the root folder's
+ // slug. We pre-seed the structure with the root entry so empty folders
+ // still produce something the lambda can recognise.
+ const scopedRoot = rootFolder
+ ? {
+ slug: safeSlugify(rootFolder.name),
+ computedPath: computedPathMap.get(rootFolder.id) ?? "",
+ }
+ : null;
+
+ if (scopedRoot) {
+ const rootPath = "/" + scopedRoot.slug;
+ folderStructure[rootPath] = {
+ name: scopedRoot.slug,
+ path: rootPath,
+ files: [],
+ };
+ }
+
+ /** Resolve the destination folder path inside the zip for a doc. */
+ const resolveZipPath = (folderId: string | null): string | null => {
+ if (!folderId) {
+ // Root-level doc.
+ if (scopedRoot) return "/" + scopedRoot.slug;
+ return "/";
+ }
+
+ const folderComputedPath = computedPathMap.get(folderId);
+ if (!folderComputedPath) return null;
+
+ if (!scopedRoot) return folderComputedPath;
+
+ // Folder-scoped: rebase under the root folder's slug.
+ const relative = stripRootPath(folderComputedPath, scopedRoot.computedPath);
+ if (!relative) return "/" + scopedRoot.slug;
+ return "/" + scopedRoot.slug + "/" + relative;
+ };
+
+ /** Ensure every parent folder up to `path` exists in the structure. */
+ const ensureFolderChain = (path: string) => {
+ if (path === "/") return;
+
+ const parts = path.split("/").filter(Boolean);
+ // When folder-scoped, the first segment is the root slug we already
+ // pre-seeded — start iterating after it but keep it in `currentPath`
+ // so child paths accumulate correctly.
+ const startIndex = scopedRoot ? 1 : 0;
+
+ let currentPath = "";
+ for (let i = 0; i < startIndex; i++) {
+ currentPath += "/" + parts[i];
+ }
+
+ for (let i = startIndex; i < parts.length; i++) {
+ const part = parts[i];
+ currentPath += "/" + part;
+ if (folderStructure[currentPath]) continue;
+
+ // For the inner folders, look up the folderNameMap to get a nicer
+ // display name (it may differ from the slug for non-ASCII names).
+ let displayName = part;
+ if (!scopedRoot) {
+ const info = folderNameMap.get(currentPath);
+ if (info) displayName = info.name;
+ }
+
+ folderStructure[currentPath] = {
+ name: displayName,
+ path: currentPath,
+ files: [],
+ };
+ }
+ };
+
+ const includedFolderIds = new Set(includedFolders.map((f) => f.id));
+
+ /** Add a single document to the structure. */
+ const addDocument = (doc: BulkDownloadDocumentInput) => {
+ const version = doc.document.versions[0];
+ if (!isDownloadableVersion(version)) return;
+
+ // Documents inside folders are only included if the folder itself is
+ // permission-allowed. Root-level docs (folderId == null) are always
+ // included if the caller passed them.
+ if (doc.folderId && !includedFolderIds.has(doc.folderId)) return;
+
+ const zipPath = resolveZipPath(doc.folderId);
+ if (zipPath == null) return;
+
+ ensureFolderChain(zipPath);
+
+ if (!folderStructure[zipPath]) {
+ // Root-level write into "/" when not scoped.
+ folderStructure[zipPath] = {
+ name: zipPath === "/" ? "Root" : zipPath.split("/").pop() || "Root",
+ path: zipPath,
+ files: [],
+ };
+ }
+
+ const safeName = ensureFileExtension({
+ name: doc.document.name,
+ contentType: version.contentType,
+ type: version.type,
+ });
+ // Watermarked PDFs always end in .pdf because the lambda renders
+ // them through mupdf and saves them as PDFs regardless of upload type.
+ const finalName =
+ enableWatermark && version.type === "pdf"
+ ? ensureFileExtension({
+ name: doc.document.name,
+ contentType: "application/pdf",
+ })
+ : safeName;
+
+ const fileKey = pickFileKey(version, enableWatermark);
+
+ folderStructure[zipPath].files.push({
+ name: finalName,
+ key: fileKey,
+ type: version.type ?? undefined,
+ numPages: version.numPages ?? undefined,
+ needsWatermark: versionNeedsWatermark(version, enableWatermark),
+ size:
+ version.fileSize != null
+ ? typeof version.fileSize === "bigint"
+ ? Number(version.fileSize)
+ : version.fileSize
+ : undefined,
+ });
+ fileKeys.push(fileKey);
+ downloadableDocuments.push(doc);
+ };
+
+ for (const doc of includedDocuments) {
+ addDocument(doc);
+ }
+
+ // Make sure every permitted folder has at least an entry in the
+ // structure (even if empty) so the lambda recreates it in the zip.
+ for (const folder of includedFolders) {
+ const zipPath = resolveZipPath(folder.id);
+ if (zipPath == null) continue;
+ ensureFolderChain(zipPath);
+ }
+
+ return { folderStructure, fileKeys, downloadableDocuments };
+}
diff --git a/lib/files/get-file.ts b/lib/files/get-file.ts
index c0290fae..97302024 100644
--- a/lib/files/get-file.ts
+++ b/lib/files/get-file.ts
@@ -8,6 +8,12 @@ export type GetFileOptions = {
isDownload?: boolean;
/** Signed URL lifetime in milliseconds (server-side S3 only, capped at 1 hour) */
expiresIn?: number;
+ /**
+ * Override the Content-Disposition returned for this single download.
+ * Only honored for S3-backed documents on origins that are not fronted by
+ * CloudFront (CloudFront strips/ignores the override).
+ */
+ responseContentDisposition?: string;
};
export const getFile = async ({
@@ -15,6 +21,7 @@ export const getFile = async ({
data,
isDownload = false,
expiresIn,
+ responseContentDisposition,
}: GetFileOptions): Promise<string> => {
const url = await match(type)
.with(DocumentStorageType.VERCEL_BLOB, () => {
@@ -25,7 +32,7 @@ export const getFile = async ({
}
})
.with(DocumentStorageType.S3_PATH, async () =>
- getFileFromS3(data, expiresIn),
+ getFileFromS3(data, expiresIn, responseContentDisposition),
)
.exhaustive();
@@ -37,11 +44,16 @@ const fetchPresignedUrl = async (
headers: Record<string, string>,
key: string,
expiresIn?: number,
+ responseContentDisposition?: string,
): Promise<string> => {
const response = await fetch(endpoint, {
method: "POST",
headers,
- body: JSON.stringify({ key, ...(expiresIn && { expiresIn }) }),
+ body: JSON.stringify({
+ key,
+ ...(expiresIn && { expiresIn }),
+ ...(responseContentDisposition && { responseContentDisposition }),
+ }),
});
if (!response.ok) {
@@ -71,7 +83,11 @@ const fetchPresignedUrl = async (
return url;
};
-const getFileFromS3 = async (key: string, expiresIn?: number) => {
+const getFileFromS3 = async (
+ key: string,
+ expiresIn?: number,
+ responseContentDisposition?: string,
+) => {
const isServer =
typeof window === "undefined" && !!process.env.INTERNAL_API_KEY;
@@ -84,6 +100,7 @@ const getFileFromS3 = async (key: string, expiresIn?: number) => {
},
key,
expiresIn,
+ responseContentDisposition,
);
} else {
return fetchPresignedUrl(
@@ -92,6 +109,8 @@ const getFileFromS3 = async (key: string, expiresIn?: number) => {
"Content-Type": "application/json",
},
key,
+ undefined,
+ responseContentDisposition,
);
}
};
diff --git a/lib/trigger/bulk-download.ts b/lib/trigger/bulk-download.ts
index 6baf1e3f..891fb4c4 100644
--- a/lib/trigger/bulk-download.ts
+++ b/lib/trigger/bulk-download.ts
@@ -11,18 +11,14 @@ import {
type LambdaClient,
} from "@aws-sdk/client-lambda";
-import {
- buildFolderNameMap,
- buildFolderPathsFromHierarchy,
- collectDescendantIds,
-} from "@/lib/dataroom/build-folder-hierarchy";
+import { buildBulkDownloadStructure } from "@/lib/dataroom/build-bulk-download-structure";
+import { collectDescendantIds } from "@/lib/dataroom/build-folder-hierarchy";
import { sendDownloadReadyEmail } from "@/lib/emails/send-download-ready-email";
import { getLambdaClientForTeam } from "@/lib/files/aws-client";
import { parseS3PresignedUrl } from "@/lib/files/bulk-download-presign";
import { notifyDocumentDownload } from "@/lib/integrations/slack/events";
import prisma from "@/lib/prisma";
import { downloadJobStore } from "@/lib/redis-download-job-store";
-import { safeSlugify } from "@/lib/utils";
import { constructLinkUrl } from "@/lib/utils/link-url";
// Maximum files per batch (Lambda payload limit)
@@ -924,63 +920,17 @@ async function buildDownloadContext({
);
}
- // Single pass: compute downloadable docs AND index docs by folderId so
- // both build*ModeStructure helpers can reuse the same map without
- // walking effectiveDocuments again.
- const downloadableDocuments: BuildDocumentRow[] = [];
- const docsByFolderId = new Map<string, BuildDocumentRow[]>();
- const rootDocs: BuildDocumentRow[] = [];
-
- for (const doc of effectiveDocuments) {
- const version = doc.document.versions[0];
- if (
- !version ||
- version.type === "notion" ||
- version.storageType === "VERCEL_BLOB"
- ) {
- continue;
- }
-
- downloadableDocuments.push(doc);
-
- if (doc.folderId) {
- const list = docsByFolderId.get(doc.folderId);
- if (list) {
- list.push(doc);
- } else {
- docsByFolderId.set(doc.folderId, [doc]);
- }
- } else {
- rootDocs.push(doc);
- }
- }
-
- let folderStructure: BulkDownloadFolderStructure;
- let fileKeys: string[];
-
- if (type === "folder") {
- const built = buildFolderModeStructure({
- rootFolder: rootFolder!,
- // Use the FULL folder list so parent folders that only have canView
- // permissions still resolve correct child paths.
- fullFolders: foldersInScope,
- effectiveFolders,
- docsByFolderId,
+ const { folderStructure, fileKeys, downloadableDocuments } =
+ buildBulkDownloadStructure({
+ fullFolders: type === "folder" ? foldersInScope : allDataroomFolders,
+ includedFolders: effectiveFolders,
+ includedDocuments: effectiveDocuments,
enableWatermark,
+ rootFolder:
+ type === "folder" && rootFolder
+ ? { id: rootFolder.id, name: rootFolder.name }
+ : undefined,
});
- folderStructure = built.folderStructure;
- fileKeys = built.fileKeys;
- } else {
- const built = buildBulkModeStructure({
- allFolders: allDataroomFolders,
- effectiveFolders,
- docsByFolderId,
- rootDocs,
- enableWatermark,
- });
- folderStructure = built.folderStructure;
- fileKeys = built.fileKeys;
- }
logger.info("Built folder download context", {
jobId,
@@ -1020,7 +970,7 @@ async function buildDownloadContext({
await prisma.view.createMany({
data: downloadableDocuments.map((doc) => ({
viewType: "DOCUMENT_VIEW",
- documentId: doc.document.id,
+ documentId: doc.document.id!,
linkId,
dataroomId,
groupId: groupId ?? null,
@@ -1073,268 +1023,6 @@ async function buildDownloadContext({
};
}
-type FolderRow = {
- id: string;
- name: string;
- path: string;
- parentId: string | null;
-};
-
-type BuildDocumentRow = {
- id: string;
- folderId: string | null;
- document: {
- id: string;
- name: string;
- versions: {
- type: string | null;
- file: string;
- storageType: string;
- originalFile: string | null;
- numPages: number | null;
- contentType: string | null;
- fileSize: bigint | null;
- }[];
- };
-};
-
-/**
- * Pick the S3 key to ship to Lambda for a given primary version. PDFs use
- * the watermarkable rendition (`file`) when watermarking is on; everything
- * else falls back to the original upload.
- */
-function pickFileKey(
- version: BuildDocumentRow["document"]["versions"][number],
- enableWatermark: boolean,
-): string {
- return enableWatermark && version.type === "pdf"
- ? version.file
- : (version.originalFile ?? version.file);
-}
-
-function buildFolderModeStructure({
- rootFolder,
- fullFolders,
- effectiveFolders,
- docsByFolderId,
- enableWatermark,
-}: {
- rootFolder: FolderRow;
- fullFolders: FolderRow[];
- effectiveFolders: FolderRow[];
- docsByFolderId: Map<string, BuildDocumentRow[]>;
- enableWatermark: boolean;
-}) {
- const folderStructure: BulkDownloadFolderStructure = {};
- const fileKeys: string[] = [];
-
- // Build paths from the FULL folder list (same as the previous API logic
- // so parent folders only granted canView still produce correct child paths).
- const computedPathMap = buildFolderPathsFromHierarchy(fullFolders);
- const computedRootPath =
- computedPathMap.get(rootFolder.id) ?? rootFolder.path;
- const rootFolderInfo = {
- name: rootFolder.name,
- computedPath: computedRootPath,
- };
-
- const addFileToStructure = (
- computedFolderPath: string,
- fileName: string,
- fileKey: string,
- fileType?: string,
- numPages?: number,
- fileSize?: number,
- ) => {
- let relativePath = "";
- if (computedFolderPath !== rootFolderInfo.computedPath) {
- const escapedRoot = rootFolderInfo.computedPath.replace(
- /[.*+?^${}()|[\]\\]/g,
- "\\$&",
- );
- const pathRegex = new RegExp(`^${escapedRoot}/(.*)$`);
- const match = computedFolderPath.match(pathRegex);
- relativePath = match ? match[1] : "";
- }
-
- const pathParts = [safeSlugify(rootFolderInfo.name)];
- if (relativePath) {
- pathParts.push(...relativePath.split("/").filter(Boolean));
- }
-
- let currentPath = "";
- for (const part of pathParts) {
- currentPath += "/" + part;
- if (!folderStructure[currentPath]) {
- folderStructure[currentPath] = {
- name: part,
- path: currentPath,
- files: [],
- };
- }
- }
-
- if (fileName && fileKey) {
- const needsWatermark =
- enableWatermark && (fileType === "pdf" || fileType === "image");
- folderStructure[currentPath].files.push({
- name: fileName,
- key: fileKey,
- type: fileType,
- numPages: numPages,
- needsWatermark: needsWatermark ?? undefined,
- size: fileSize,
- });
- fileKeys.push(fileKey);
- }
- };
-
- for (const folder of effectiveFolders) {
- const folderPath = computedPathMap.get(folder.id) ?? folder.path;
- const docs = docsByFolderId.get(folder.id);
-
- if (!docs || docs.length === 0) {
- addFileToStructure(folderPath, "", "");
- continue;
- }
-
- for (const doc of docs) {
- // docsByFolderId is already filtered to downloadable primary
- // versions (see buildDownloadContext), so versions[0] is guaranteed
- // present and not notion / VERCEL_BLOB.
- const version = doc.document.versions[0];
- const fileKey = pickFileKey(version, enableWatermark);
- addFileToStructure(
- folderPath,
- doc.document.name,
- fileKey,
- version.type ?? undefined,
- version.numPages ?? undefined,
- version.fileSize ? Number(version.fileSize) : undefined,
- );
- }
- }
-
- const rootPath = "/" + safeSlugify(rootFolder.name);
- if (!folderStructure[rootPath]) {
- folderStructure[rootPath] = {
- name: safeSlugify(rootFolder.name),
- path: rootPath,
- files: [],
- };
- }
-
- return { folderStructure, fileKeys };
-}
-
-function buildBulkModeStructure({
- allFolders,
- effectiveFolders,
- docsByFolderId,
- rootDocs,
- enableWatermark,
-}: {
- allFolders: FolderRow[];
- effectiveFolders: FolderRow[];
- docsByFolderId: Map<string, BuildDocumentRow[]>;
- rootDocs: BuildDocumentRow[];
- enableWatermark: boolean;
-}) {
- const folderStructure: BulkDownloadFolderStructure = {};
- const fileKeys: string[] = [];
-
- const computedPathMap = buildFolderPathsFromHierarchy(allFolders);
- const folderMap = buildFolderNameMap(allFolders, computedPathMap);
-
- const addFileToStructure = (
- path: string,
- fileName: string,
- fileKey: string,
- fileType?: string,
- numPages?: number,
- fileSize?: number,
- ) => {
- const pathParts = path.split("/").filter(Boolean);
- let currentPath = "";
-
- for (const part of pathParts) {
- currentPath += "/" + part;
- if (!folderStructure[currentPath]) {
- const folderInfo = folderMap.get(currentPath);
- folderStructure[currentPath] = {
- name: folderInfo ? folderInfo.name : part,
- path: currentPath,
- files: [],
- };
- }
- }
-
- if (!folderStructure[path]) {
- const folderInfo = folderMap.get(path) || { name: "Root", id: null };
- folderStructure[path] = {
- name: folderInfo.name,
- path: path,
- files: [],
- };
- }
-
- if (fileName && fileKey) {
- const needsWatermark =
- enableWatermark && (fileType === "pdf" || fileType === "image");
- folderStructure[path].files.push({
- name: fileName,
- key: fileKey,
- type: fileType,
- numPages: numPages,
- needsWatermark: needsWatermark ?? undefined,
- size: fileSize,
- });
- fileKeys.push(fileKey);
- }
- };
-
- // Root-level documents (already pre-filtered to downloadable primary
- // versions in buildDownloadContext).
- for (const doc of rootDocs) {
- const version = doc.document.versions[0];
- const fileKey = pickFileKey(version, enableWatermark);
- addFileToStructure(
- "/",
- doc.document.name,
- fileKey,
- version.type ?? undefined,
- version.numPages ?? undefined,
- version.fileSize ? Number(version.fileSize) : undefined,
- );
- }
-
- // Documents nested in folders.
- for (const folder of effectiveFolders) {
- const folderPath = computedPathMap.get(folder.id) ?? folder.path;
- const docs = docsByFolderId.get(folder.id);
-
- if (!docs || docs.length === 0) {
- addFileToStructure(folderPath, "", "");
- continue;
- }
-
- for (const doc of docs) {
- const version = doc.document.versions[0];
- const fileKey = pickFileKey(version, enableWatermark);
- addFileToStructure(
- folderPath,
- doc.document.name,
- fileKey,
- version.type ?? undefined,
- version.numPages ?? undefined,
- version.fileSize ? Number(version.fileSize) : undefined,
- );
- }
- }
-
- return { folderStructure, fileKeys };
-}
-
async function sendEmailNotification({
emailAddress,
dataroomName,
diff --git a/lib/utils.ts b/lib/utils.ts
index 1d436c32..845cb162 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -391,6 +391,24 @@ export function buildContentDisposition(
return `attachment; filename="${slugifiedName}"; filename*=UTF-8''${encodeRFC5987(originalFileName)}`;
}
+/**
+ * Build a Content-Disposition `attachment` header for a single download
+ * filename (already including its extension). This handles slugifying the
+ * ASCII fallback so the header is safe across browsers and proxies, while
+ * preserving the original Unicode name in `filename*` per RFC 5987.
+ *
+ * Use this for ad-hoc downloads (e.g. ResponseContentDisposition on S3
+ * presigned URLs) where the caller already produced a complete filename.
+ */
+export function buildAttachmentDispositionForName(filename: string): string {
+ const dotIdx = filename.lastIndexOf(".");
+ const base = dotIdx > 0 ? filename.slice(0, dotIdx) : filename;
+ const ext = dotIdx > 0 ? filename.slice(dotIdx) : "";
+ const sanitizedExt = /^\.[A-Za-z0-9]+$/.test(ext) ? ext : "";
+ const slug = safeSlugify(base) + sanitizedExt;
+ return buildContentDisposition(filename, slug);
+}
+
export const daysLeft = (
accountCreationDate: Date,
maxDays: number,
diff --git a/lib/utils/download-document.ts b/lib/utils/download-document.ts
new file mode 100644
index 00000000..0f1fa5ed
--- /dev/null
+++ b/lib/utils/download-document.ts
@@ -0,0 +1,105 @@
+/**
+ * Trigger a document download from one of the link-scoped download
+ * endpoints (`/api/links/download` or `/api/links/download/dataroom-document`).
+ *
+ * The server returns one of two response shapes:
+ *
+ * 1. A buffered binary response (currently only watermarked PDFs that need
+ * mupdf annotation) with `Content-Disposition` set to the desired
+ * filename. We turn it into a blob + `<a download>` to save it.
+ *
+ * 2. A JSON response of the form `{ downloadUrl, fileName }`. The URL is
+ * a CloudFront / S3 presigned URL with `response-content-disposition`
+ * baked in, so we just iframe-redirect to it. The browser streams the
+ * bytes straight from origin and saves the file with the right name -
+ * no proxying through the JS heap.
+ *
+ * `fallbackFileName` is used only when the buffered response is missing
+ * its `Content-Disposition` header (shouldn't happen in practice).
+ */
+export async function downloadFromLinkEndpoint({
+ endpoint,
+ body,
+ fallbackFileName,
+}: {
+ endpoint: string;
+ body: Record<string, unknown>;
+ fallbackFileName: string;
+}): Promise<void> {
+ const response = await fetch(endpoint, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ throw new Error(errorData.error || "Failed to download file");
+ }
+
+ const contentType = response.headers.get("content-type");
+
+ if (contentType?.includes("application/json")) {
+ const { downloadUrl } = (await response.json()) as { downloadUrl: string };
+
+ const iframe = window.document.createElement("iframe");
+ iframe.style.display = "none";
+ window.document.body.appendChild(iframe);
+ iframe.src = downloadUrl;
+
+ setTimeout(() => {
+ if (iframe.parentNode) {
+ window.document.body.removeChild(iframe);
+ }
+ }, 5000);
+
+ return;
+ }
+
+ // Buffered binary response (e.g. watermarked PDF).
+ const blob = await response.blob();
+ const objectUrl = window.URL.createObjectURL(blob);
+
+ const link = window.document.createElement("a");
+ link.href = objectUrl;
+ link.rel = "noopener noreferrer";
+ link.download =
+ extractFilenameFromContentDisposition(
+ response.headers.get("content-disposition"),
+ ) ?? fallbackFileName;
+
+ window.document.body.appendChild(link);
+ link.click();
+
+ setTimeout(() => {
+ window.URL.revokeObjectURL(objectUrl);
+ if (link.parentNode) {
+ window.document.body.removeChild(link);
+ }
+ }, 100);
+}
+
+/**
+ * Parse a `Content-Disposition` header. Prefers RFC 5987's
+ * `filename*=UTF-8''<encoded>` form so unicode filenames survive, and falls
+ * back to the legacy quoted-string `filename="..."` form.
+ */
+export function extractFilenameFromContentDisposition(
+ disposition: string | null,
+): string | null {
+ if (!disposition) return null;
+
+ const starMatch = disposition.match(/filename\*=UTF-8''([^;]+)/i);
+ if (starMatch && starMatch[1]) {
+ try {
+ return decodeURIComponent(starMatch[1]);
+ } catch {
+ return starMatch[1];
+ }
+ }
+
+ const quotedMatch = disposition.match(/filename="([^"]+)"/);
+ if (quotedMatch && quotedMatch[1]) return quotedMatch[1];
+
+ return null;
+}
diff --git a/lib/utils/get-content-type.ts b/lib/utils/get-content-type.ts
index 7be02513..b0253c34 100644
--- a/lib/utils/get-content-type.ts
+++ b/lib/utils/get-content-type.ts
@@ -140,6 +140,61 @@ export function getExtensionFromContentType(
}
}
+/**
+ * Ensure a download filename has a file extension.
+ *
+ * Document.name is mostly populated from the original `file.name` at upload
+ * time, so it usually already includes the extension. However, owners can
+ * rename documents via the UI without keeping the extension, and some legacy
+ * uploads may have stripped extensions. When such a name is used as a
+ * download filename, the OS can't infer the file type.
+ *
+ * Behavior:
+ * - If `name` already ends with a plausible extension (1-8 alphanumeric
+ * characters after a final dot), it is returned unchanged.
+ * - Otherwise we append the extension derived from `contentType` first
+ * (most accurate) and fall back to `type` (Papermark's internal type
+ * column, e.g. "pdf", "sheet", "image").
+ * - Returns the original name if no extension can be derived.
+ */
+export function ensureFileExtension({
+ name,
+ contentType,
+ type,
+}: {
+ name: string | null | undefined;
+ contentType?: string | null;
+ type?: string | null;
+}): string {
+ if (!name) return name ?? "";
+
+ if (/\.[A-Za-z0-9]{1,8}$/.test(name)) {
+ return name;
+ }
+
+ const derivedFromContentType = contentType
+ ? getExtensionFromContentType(contentType)
+ : null;
+
+ // `type` is the Papermark-internal short type. Most values are generic
+ // buckets ("sheet", "image", "docs", "slides", "video", "map", "email",
+ // "cad", "other") or non-file kinds ("notion", "link") that must NOT be
+ // appended as a fake extension. Only fall back to `type` when it is on a
+ // strict allow-list of values that correspond to a single real extension,
+ // and additionally validate it matches a filename-safe shape so a stray
+ // value can never produce an unsafe filename suffix.
+ const ALLOWED_TYPE_EXTENSIONS = new Set(["pdf", "zip"]);
+ const usableType =
+ type &&
+ ALLOWED_TYPE_EXTENSIONS.has(type) &&
+ /^[a-z0-9]{1,6}$/.test(type)
+ ? type
+ : null;
+
+ const ext = derivedFromContentType || usableType;
+ return ext ? `${name}.${ext}` : name;
+}
+
export function supportsAdvancedExcelMode(
contentType: string | null | undefined,
): boolean {
diff --git a/package.json b/package.json
index f227f947..060543be 100644
--- a/package.json
+++ b/package.json
@@ -218,4 +218,4 @@
"tar": "7.5.10",
"lodash": "4.18.1"
}
-}
+}
\ No newline at end of file
diff --git a/pages/api/file/s3/get-presigned-get-url-proxy.ts b/pages/api/file/s3/get-presigned-get-url-proxy.ts
index b32e6834..77189419 100644
--- a/pages/api/file/s3/get-presigned-get-url-proxy.ts
+++ b/pages/api/file/s3/get-presigned-get-url-proxy.ts
@@ -20,7 +20,10 @@ export default async function handler(
return res.status(401).json({ message: "Unauthorized" });
}
- const { key } = req.body as { key: string };
+ const { key, responseContentDisposition } = req.body as {
+ key: string;
+ responseContentDisposition?: string;
+ };
if (!key) {
return res.status(400).json({ message: "Key is required" });
@@ -63,7 +66,10 @@ export default async function handler(
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.INTERNAL_API_KEY}`,
},
- body: JSON.stringify({ key: key }),
+ body: JSON.stringify({
+ key,
+ ...(responseContentDisposition ? { responseContentDisposition } : {}),
+ }),
},
);
diff --git a/pages/api/file/s3/get-presigned-get-url.ts b/pages/api/file/s3/get-presigned-get-url.ts
index 274a87d6..a52953ef 100644
--- a/pages/api/file/s3/get-presigned-get-url.ts
+++ b/pages/api/file/s3/get-presigned-get-url.ts
@@ -39,9 +39,14 @@ export default async function handler(
return res.status(401).json({ message: "Unauthorized" });
}
- const { key, expiresIn: requestedExpiresIn } = req.body as {
+ const {
+ key,
+ expiresIn: requestedExpiresIn,
+ responseContentDisposition,
+ } = req.body as {
key: string;
expiresIn?: number;
+ responseContentDisposition?: string;
};
const expiration = Math.min(requestedExpiresIn || TWO_MINUTES, ONE_HOUR);
@@ -60,24 +65,51 @@ export default async function handler(
const { client, config } = await getTeamS3ClientAndConfig(teamId);
if (config.distributionHost) {
+ // CloudFront signed URLs DO honor `response-content-disposition` if S3
+ // is the origin and the distribution forwards that query param. The
+ // catch is that `@aws-sdk/cloudfront-signer` mangles the encoding when
+ // it parses the URL, so the resulting URL fails with AccessDenied.
+ // Workaround: set the param via URL.searchParams (so it's part of the
+ // signed policy) and then re-set it on the signed output to fix the
+ // encoding.
+ // See https://obviy.us/blog/cloudfront-signed-disposition/
const distributionUrl = new URL(
key,
`https://${config.distributionHost}`,
);
-
- const url = getCloudfrontSignedUrl({
+ if (responseContentDisposition) {
+ distributionUrl.searchParams.set(
+ "response-content-disposition",
+ responseContentDisposition,
+ );
+ }
+
+ const signed = getCloudfrontSignedUrl({
url: distributionUrl.toString(),
keyPairId: `${config.distributionKeyId}`,
privateKey: `${config.distributionKeyContents}`,
dateLessThan: new Date(Date.now() + expiration).toISOString(),
});
+ let url = signed;
+ if (responseContentDisposition) {
+ const fixed = new URL(signed);
+ fixed.searchParams.set(
+ "response-content-disposition",
+ responseContentDisposition,
+ );
+ url = fixed.href;
+ }
+
return res.status(200).json({ url });
}
const getObjectCommand = new GetObjectCommand({
Bucket: config.bucket,
Key: key,
+ ...(responseContentDisposition
+ ? { ResponseContentDisposition: responseContentDisposition }
+ : {}),
});
const url = await getS3SignedUrl(client, getObjectCommand, {
diff --git a/pages/api/links/download/dataroom-document.ts b/pages/api/links/download/dataroom-document.ts
index deda7809..e440e238 100644
--- a/pages/api/links/download/dataroom-document.ts
+++ b/pages/api/links/download/dataroom-document.ts
@@ -6,7 +6,11 @@ import { waitUntil } from "@vercel/functions";
import { getFile } from "@/lib/files/get-file";
import { notifyDocumentDownload } from "@/lib/integrations/slack/events";
import prisma from "@/lib/prisma";
-import { getFileNameWithPdfExtension } from "@/lib/utils";
+import {
+ buildAttachmentDispositionForName,
+ getFileNameWithPdfExtension,
+} from "@/lib/utils";
+import { ensureFileExtension } from "@/lib/utils/get-content-type";
import { getIpAddress } from "@/lib/utils/ip";
export const config = {
@@ -197,10 +201,25 @@ export default async function handle(
: (downloadDocuments[0].document!.versions[0].originalFile ??
downloadDocuments[0].document!.versions[0].file);
+ // Pre-compute the user-facing download filename (renamed name + correct
+ // extension). We pass it as ResponseContentDisposition on the S3
+ // presigned URL so the browser uses it instead of the original
+ // upload-time disposition stored on the S3 object. CloudFront-fronted
+ // origins ignore this and still return the stored disposition.
+ const versionForName = downloadDocuments[0].document!.versions[0];
+ const desiredFileName = ensureFileExtension({
+ name: downloadDocuments[0].document!.name,
+ contentType: versionForName.contentType,
+ type: versionForName.type,
+ });
+
const downloadUrl = await getFile({
- type: downloadDocuments[0].document!.versions[0].storageType,
+ type: versionForName.storageType,
data: file,
isDownload: true,
+ responseContentDisposition: desiredFileName
+ ? buildAttachmentDispositionForName(desiredFileName)
+ : undefined,
});
// For PDF files with watermark, always buffer and process
@@ -245,11 +264,12 @@ export default async function handle(
const pdfBuffer = await response.arrayBuffer();
- // Set appropriate headers for watermarked PDF
res.setHeader("Content-Type", "application/pdf");
res.setHeader(
"Content-Disposition",
- `attachment; filename="${encodeURIComponent(getFileNameWithPdfExtension(downloadDocuments[0].document!.name))}"`,
+ buildAttachmentDispositionForName(
+ getFileNameWithPdfExtension(downloadDocuments[0].document!.name),
+ ),
);
res.setHeader("Content-Length", Buffer.from(pdfBuffer).length);
@@ -257,52 +277,14 @@ export default async function handle(
return res.send(Buffer.from(pdfBuffer));
}
- // For non-watermarked PDFs, we need to buffer and set proper headers
- // - contentType is application/pdf
- // - contentType is null and type is pdf
- // - contentType starts with image/
- if (
- downloadDocuments[0].document!.versions[0].contentType ===
- "application/pdf" ||
- (downloadDocuments[0].document!.versions[0].contentType === null &&
- downloadDocuments[0].document!.versions[0].type === "pdf") ||
- downloadDocuments[0].document!.versions[0].contentType?.startsWith(
- "image/",
- )
- ) {
- const response = await fetch(downloadUrl);
- if (!response.ok) {
- return res.status(500).json({ error: "Error downloading file" });
- }
-
- const pdfBuffer = await response.arrayBuffer();
-
- // Set appropriate headers to force download
- res.setHeader("Content-Type", "application/pdf");
- res.setHeader(
- "Content-Disposition",
- `attachment; filename="${encodeURIComponent(downloadDocuments[0].document!.name)}"`,
- );
- res.setHeader("Content-Length", Buffer.from(pdfBuffer).length);
- res.setHeader("Cache-Control", "no-cache");
-
- // Send the PDF buffer directly
- return res.send(Buffer.from(pdfBuffer));
- }
-
- const headResponse = await fetch(downloadUrl, { method: "HEAD" });
- const contentType =
- downloadDocuments[0].document!.versions[0].contentType ||
- headResponse.headers.get("content-type") ||
- "application/octet-stream";
- const fileName = downloadDocuments[0].document!.name;
-
- // For all other files, return direct download URL
+ // For everything else (PDFs, images, sheets, slides, archives, ...)
+ // we hand back the presigned URL with the renamed Content-Disposition
+ // baked in via response-content-disposition. The client iframes it,
+ // CloudFront/S3 returns the bytes directly, and the OS saves the file
+ // with the right name + extension. No need to buffer through Vercel.
return res.status(200).json({
downloadUrl,
- fileName,
- contentType,
- isDirectDownload: true,
+ fileName: desiredFileName,
});
} catch (error) {
console.error("Error:", error);
diff --git a/pages/api/links/download/index.ts b/pages/api/links/download/index.ts
index 56a1dd00..e7cd3f35 100644
--- a/pages/api/links/download/index.ts
+++ b/pages/api/links/download/index.ts
@@ -5,7 +5,11 @@ import { LinkType } from "@prisma/client";
import { getFile } from "@/lib/files/get-file";
import { notifyDocumentDownload } from "@/lib/integrations/slack/events";
import prisma from "@/lib/prisma";
-import { getFileNameWithPdfExtension } from "@/lib/utils";
+import {
+ buildAttachmentDispositionForName,
+ getFileNameWithPdfExtension,
+} from "@/lib/utils";
+import { ensureFileExtension } from "@/lib/utils/get-content-type";
import { getIpAddress } from "@/lib/utils/ip";
// This function can run for a maximum of 300 seconds
@@ -138,10 +142,22 @@ export default async function handle(
: (view.document!.versions[0].originalFile ??
view.document!.versions[0].file);
+ // Pre-compute the user-facing filename (renamed doc name + correct
+ // extension). Pass it as ResponseContentDisposition so the browser
+ // uses our name even when downloading via direct presigned URL.
+ const desiredFileName = ensureFileExtension({
+ name: view.document!.name,
+ contentType: view.document!.versions[0].contentType,
+ type: view.document!.versions[0].type,
+ });
+
const downloadUrl = await getFile({
type: view.document!.versions[0].storageType,
data: file,
isDownload: true,
+ responseContentDisposition: desiredFileName
+ ? buildAttachmentDispositionForName(desiredFileName)
+ : undefined,
});
if (
@@ -197,11 +213,12 @@ export default async function handle(
const pdfBuffer = await response.arrayBuffer();
- // Set appropriate headers
res.setHeader("Content-Type", "application/pdf");
res.setHeader(
"Content-Disposition",
- `attachment; filename="${encodeURIComponent(getFileNameWithPdfExtension(view.document!.name))}"`,
+ buildAttachmentDispositionForName(
+ getFileNameWithPdfExtension(view.document!.name),
+ ),
);
res.setHeader("Content-Length", Buffer.from(pdfBuffer).length);
@@ -209,9 +226,10 @@ export default async function handle(
return res.send(Buffer.from(pdfBuffer));
}
- return res
- .status(200)
- .json({ downloadUrl, fileName: view.document!.name });
+ return res.status(200).json({
+ downloadUrl,
+ fileName: desiredFileName,
+ });
} catch (error) {
return res.status(500).json({
message: "Internal Server Error",
diff --git a/pages/api/teams/[teamId]/datarooms/[id]/download/bulk.ts b/pages/api/teams/[teamId]/datarooms/[id]/download/bulk.ts
index 7a64ec5d..a2241ff1 100644
--- a/pages/api/teams/[teamId]/datarooms/[id]/download/bulk.ts
+++ b/pages/api/teams/[teamId]/datarooms/[id]/download/bulk.ts
@@ -4,10 +4,7 @@ import { getTeamStorageConfigById } from "@/ee/features/storage/config";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import { getServerSession } from "next-auth";
-import {
- buildFolderNameMap,
- buildFolderPathsFromHierarchy,
-} from "@/lib/dataroom/build-folder-hierarchy";
+import { buildBulkDownloadStructure } from "@/lib/dataroom/build-bulk-download-structure";
import prisma from "@/lib/prisma";
import { downloadJobStore } from "@/lib/redis-download-job-store";
import { bulkDownloadTask } from "@/lib/trigger/bulk-download";
@@ -95,119 +92,12 @@ export default async function handler(
return res.status(404).end("Dataroom not found");
}
- let downloadFolders = dataroom.folders;
- let downloadDocuments = dataroom.documents;
-
- // Build folder paths from the parentId hierarchy (source of truth)
- // instead of using the materialized `path` field which can become stale
- // after folder renames/moves
- const computedPathMap = buildFolderPathsFromHierarchy(downloadFolders);
- const folderMap = buildFolderNameMap(downloadFolders, computedPathMap);
-
- // Construct folderStructure and fileKeys
- const folderStructure: {
- [key: string]: {
- name: string;
- path: string;
- files: { name: string; key: string; size?: number }[];
- };
- } = {};
- const fileKeys: string[] = [];
-
- const addFileToStructure = (
- path: string,
- fileName: string,
- fileKey: string,
- fileSize?: number,
- ) => {
- const pathParts = path.split("/").filter(Boolean);
- let currentPath = "";
-
- // Add folder information for each level of the path
- pathParts.forEach((part, index) => {
- currentPath += "/" + part;
- const folderInfo = folderMap.get(currentPath);
- if (!folderStructure[currentPath]) {
- folderStructure[currentPath] = {
- name: folderInfo ? folderInfo.name : part,
- path: currentPath,
- files: [],
- };
- }
- });
-
- // Add the file to the leaf folder
- if (!folderStructure[path]) {
- const folderInfo = folderMap.get(path) || {
- name: "Root",
- id: null,
- };
- folderStructure[path] = {
- name: folderInfo.name,
- path: path,
- files: [],
- };
- }
- folderStructure[path].files.push({
- name: fileName,
- key: fileKey,
- size: fileSize,
- });
- fileKeys.push(fileKey);
- };
-
- downloadDocuments
- .filter((doc) => !doc.folderId)
- .filter((doc) => doc.document.versions[0].type !== "notion")
- .filter((doc) => doc.document.versions[0].storageType !== "VERCEL_BLOB")
- .forEach((doc) =>
- addFileToStructure(
- "/",
- doc.document.name,
- doc.document.versions[0].originalFile ??
- doc.document.versions[0].file,
- doc.document.versions[0].fileSize
- ? Number(doc.document.versions[0].fileSize)
- : undefined,
- ),
- );
-
- // Pre-index documents by folderId for O(1) lookup per folder
- const docsByFolderId = new Map<string, typeof downloadDocuments>();
- for (const doc of downloadDocuments) {
- if (!doc.folderId) continue;
- const list = docsByFolderId.get(doc.folderId) ?? [];
- list.push(doc);
- docsByFolderId.set(doc.folderId, list);
- }
-
- downloadFolders.forEach((folder) => {
- // Use the computed path from parentId hierarchy instead of the stored path
- const folderPath = computedPathMap.get(folder.id) ?? folder.path;
-
- const folderDocs = (docsByFolderId.get(folder.id) ?? [])
- .filter((doc) => doc.document.versions[0].type !== "notion")
- .filter(
- (doc) => doc.document.versions[0].storageType !== "VERCEL_BLOB",
- );
-
- folderDocs &&
- folderDocs.forEach((doc) =>
- addFileToStructure(
- folderPath,
- doc.document.name,
- doc.document.versions[0].originalFile ??
- doc.document.versions[0].file,
- doc.document.versions[0].fileSize
- ? Number(doc.document.versions[0].fileSize)
- : undefined,
- ),
- );
-
- // If the folder is empty, ensure it's still added to the structure
- if (folderDocs && folderDocs.length === 0) {
- addFileToStructure(folderPath, "", "");
- }
+ // Admin bulk download: no permission filtering, no watermark.
+ const { folderStructure, fileKeys } = buildBulkDownloadStructure({
+ fullFolders: dataroom.folders,
+ includedFolders: dataroom.folders,
+ includedDocuments: dataroom.documents,
+ enableWatermark: false,
});
if (fileKeys.length === 0) {