Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add dataroom uploader
Marc Seitz8e980cdf8dab
diff --git a/app/api/links/[id]/upload/route.ts b/app/api/links/[id]/upload/route.tsnew file mode 100644index 00000000..a7b171f8--- /dev/null+++ b/app/api/links/[id]/upload/route.ts@@ -0,0 +1,145 @@+import { NextRequest, NextResponse } from "next/server";++import { processDocument } from "@/lib/api/documents/process-document";+import { verifyDataroomSession } from "@/lib/auth/dataroom-auth";+import { DocumentData } from "@/lib/documents/create-document";+import prisma from "@/lib/prisma";++export async function POST(+ request: NextRequest,+ { params }: { params: { id: string } },+) {+ try {+ const linkId = params.id;+ const body = await request.json();+ const { documentData, dataroomId } = body as {+ documentData: DocumentData;+ dataroomId: string;+ };++ if (!linkId || !documentData || !dataroomId) {+ return NextResponse.json(+ { message: "Missing required parameters" },+ { status: 400 },+ );+ }++ // 0. Verify the dataroom session+ const dataroomSession = await verifyDataroomSession(+ request,+ linkId,+ dataroomId,+ );++ if (!dataroomSession || !dataroomSession.viewerId) {+ return NextResponse.json(+ { message: "You need to be logged in to upload a document." },+ { status: 401 },+ );+ }++ // Check if the link exists and has visitor upload enabled+ const link = await prisma.link.findUnique({+ where: { id: linkId, dataroomId },+ select: {+ id: true,+ enableUpload: true,+ uploadFolderId: true,+ dataroomId: true,+ teamId: true,+ team: {+ select: {+ plan: true,+ },+ },+ },+ });++ if (+ !link ||+ !link.enableUpload ||+ link.dataroomId !== dataroomId ||+ !link.teamId+ ) {+ return NextResponse.json(+ { message: "Uploads not allowed for this link" },+ { status: 403 },+ );+ }++ const { viewerId, viewId } = dataroomSession;++ // Check if the viewer exists+ const viewer = await prisma.viewer.findUnique({+ where: {+ id: viewerId,+ teamId: link.teamId,+ views: { some: { id: viewId } },+ },+ select: { id: true },+ });++ if (!viewer) {+ return NextResponse.json(+ { message: "Viewer not found" },+ { status: 404 },+ );+ }++ // 1. Create the document+ const document = await processDocument({+ documentData,+ teamId: link.teamId,+ teamPlan: link.team?.plan ?? "free",+ isExternalUpload: true,+ });++ // 2. Create the dataroom document+ let dataroomFolderId: string | null = null;+ if (link.uploadFolderId) {+ const dataroomFolder = await prisma.dataroomFolder.findUnique({+ where: {+ id: link.uploadFolderId,+ dataroomId,+ },+ select: {+ id: true,+ },+ });+ dataroomFolderId = dataroomFolder?.id ?? null;+ }++ const newDataroomDocument = await prisma.dataroomDocument.create({+ data: {+ dataroomId: dataroomId,+ documentId: document.id,+ folderId: dataroomFolderId,+ },+ });++ // 3. Create the DocumentUpload record to track the upload details+ await prisma.documentUpload.create({+ data: {+ documentId: document.id,+ viewerId: viewerId,+ viewId: viewId,+ linkId: linkId,+ originalFilename: document.name,+ fileSize: document.versions[0].fileSize,+ numPages: document.numPages,+ mimeType: document.contentType,+ dataroomId: dataroomId,+ dataroomDocumentId: newDataroomDocument.id,+ teamId: link.teamId,+ },+ });++ return NextResponse.json({ success: true });+ } catch (error) {+ console.error("Error uploading document:", error);+ return NextResponse.json(+ { message: "Error uploading document" },+ { status: 500 },+ );+ }+}diff --git a/components/view/dataroom/document-upload-modal.tsx b/components/view/dataroom/document-upload-modal.tsxnew file mode 100644index 00000000..5171ef70--- /dev/null+++ b/components/view/dataroom/document-upload-modal.tsx@@ -0,0 +1,62 @@+// components/view/dataroom/document-upload-button.tsx+import { useState } from "react";++import { PlusIcon } from "lucide-react";++import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { ViewerUploadComponent } from "@/components/viewer-upload-component";++export function DocumentUploadModal({+ linkId,+ dataroomId,+ viewerId,+}: {+ linkId: string;+ dataroomId: string;+ viewerId: string;+}) {+ const [isOpen, setIsOpen] = useState(false);++ return (+ <>+ <Button+ onClick={() => setIsOpen(true)}+ size="sm"+ variant="outline"+ className="group flex items-center justify-start gap-x-3 px-3 text-left"+ title="Add Document"+ >+ <PlusIcon className="h-5 w-5 shrink-0" aria-hidden="true" />+ <span>Add Document</span>+ </Button>++ <Dialog open={isOpen} onOpenChange={setIsOpen}>+ <DialogContent>+ <DialogHeader>+ <DialogTitle>Upload Document to Dataroom</DialogTitle>+ <DialogDescription>+ The data room manager will receive a notification when the+ document is uploaded and approve the document. Only then, it will+ be visible to all visitors.+ </DialogDescription>+ </DialogHeader>+ <ViewerUploadComponent+ viewerData={{+ id: viewerId,+ linkId,+ dataroomId,+ }}+ teamId="visitor-upload"+ />+ </DialogContent>+ </Dialog>+ </>+ );+}diff --git a/components/view/viewer/dataroom-viewer.tsx b/components/view/viewer/dataroom-viewer.tsxindex d984c6ba..6ee98ee5 100644--- a/components/view/viewer/dataroom-viewer.tsx+++ b/components/view/viewer/dataroom-viewer.tsx@@ -30,6 +30,7 @@ import {import { DEFAULT_DATAROOM_VIEW_TYPE } from "../dataroom/dataroom-view";import DocumentCard from "../dataroom/document-card";+import { DocumentUploadModal } from "../dataroom/document-upload-modal";import FolderCard from "../dataroom/folder-card";import DataroomNav from "../dataroom/nav-dataroom";@@ -84,6 +85,7 @@ export default function DataroomViewer({accessControls,viewerId,viewData,+ enableVisitorUpload = true,}: {brand: Partial<DataroomBrand>;viewId?: string;@@ -96,6 +98,7 @@ export default function DataroomViewer({accessControls: ViewerGroupAccessControls[];viewerId?: string;viewData: DEFAULT_DATAROOM_VIEW_TYPE;+ enableVisitorUpload?: boolean;}) {const { documents, folders } = dataroom as {documents: DataroomDocument[];@@ -226,38 +229,48 @@ export default function DataroomViewer({</Sheet></div>- <Breadcrumb>- <BreadcrumbList>- <BreadcrumbItem key={"root"}>- <BreadcrumbLink- onClick={() => setFolderId(null)}- className="cursor-pointer"- >- Home- </BreadcrumbLink>- </BreadcrumbItem>+ <div className="flex flex-1 items-center justify-between gap-x-2">+ <Breadcrumb>+ <BreadcrumbList>+ <BreadcrumbItem key={"root"}>+ <BreadcrumbLink+ onClick={() => setFolderId(null)}+ className="cursor-pointer"+ >+ Home+ </BreadcrumbLink>+ </BreadcrumbItem>++ {breadcrumbFolders.map((folder, index) => (+ <React.Fragment key={folder.id}>+ <BreadcrumbSeparator />+ <BreadcrumbItem>+ {index === breadcrumbFolders.length - 1 ? (+ <BreadcrumbPage className="capitalize">+ {folder.name}+ </BreadcrumbPage>+ ) : (+ <BreadcrumbLink+ onClick={() => setFolderId(folder.id)}+ className="cursor-pointer capitalize"+ >+ {folder.name}+ </BreadcrumbLink>+ )}+ </BreadcrumbItem>+ </React.Fragment>+ ))}+ </BreadcrumbList>+ </Breadcrumb>- {breadcrumbFolders.map((folder, index) => (- <React.Fragment key={folder.id}>- <BreadcrumbSeparator />- <BreadcrumbItem>- {index === breadcrumbFolders.length - 1 ? (- <BreadcrumbPage className="capitalize">- {folder.name}- </BreadcrumbPage>- ) : (- <BreadcrumbLink- onClick={() => setFolderId(folder.id)}- className="cursor-pointer capitalize"- >- {folder.name}- </BreadcrumbLink>- )}- </BreadcrumbItem>- </React.Fragment>- ))}- </BreadcrumbList>- </Breadcrumb>+ {enableVisitorUpload && viewerId && (+ <DocumentUploadModal+ linkId={linkId}+ dataroomId={dataroom?.id}+ viewerId={viewerId}+ />+ )}+ </div></div><ul role="list" className="-mx-4 space-y-4 overflow-auto p-4">{mixedItems.map(renderItem)}diff --git a/components/viewer-upload-component.tsx b/components/viewer-upload-component.tsxnew file mode 100644index 00000000..36a5bdf5--- /dev/null+++ b/components/viewer-upload-component.tsx@@ -0,0 +1,118 @@+import { useState } from "react";++import { toast } from "sonner";++import { DocumentData } from "@/lib/documents/create-document";++import ViewerUploadZone from "@/components/viewer-upload-zone";++export function ViewerUploadComponent({+ viewerData,+ teamId,+}: {+ viewerData: { id: string; linkId: string; dataroomId?: string };+ teamId: string;+}) {+ const [uploads, setUploads] = useState<+ { fileName: string; progress: number }[]+ >([]);+ const [rejectedFiles, setRejectedFiles] = useState<+ { fileName: string; message: string }[]+ >([]);++ const handleUploadStart = (+ uploads: { fileName: string; progress: number }[],+ ) => {+ setUploads(uploads);+ };++ const handleUploadProgress = (index: number, progress: number) => {+ setUploads((prev) => {+ const updated = [...prev];+ updated[index] = { ...updated[index], progress };+ return updated;+ });+ };++ const handleUploadComplete = async (documentData: DocumentData) => {+ // Call your API to add the document to the dataroom or store it for viewer uploads+ try {+ const response = await fetch(`/api/links/${viewerData.linkId}/upload`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ documentData,+ dataroomId: viewerData.dataroomId,+ }),+ });++ if (!response.ok) {+ const errorData = await response.json();+ throw new Error(errorData.message || "Failed to process upload");+ }++ // Optional: You might want to update UI or fetch updated document list+ } catch (error) {+ console.error("Error processing upload:", error);+ toast.error((error as Error).message || "Failed to upload document");+ }+ };++ return (+ <div className="p-4">+ <h1 className="mb-4 text-xl font-bold">Upload Documents</h1>++ <ViewerUploadZone+ onUploadStart={handleUploadStart}+ onUploadProgress={handleUploadProgress}+ onUploadComplete={handleUploadComplete}+ onUploadRejected={(rejected) => setRejectedFiles(rejected)}+ viewerData={viewerData}+ teamId={teamId}+ >+ <div className="rounded-lg border-2 border-dashed border-gray-300 p-8 text-center">+ <p>Drag & drop files here, or click to select files</p>+ <p className="mt-2 text-sm text-gray-500">+ Supported file types: PDF, Excel, CSV+ </p>++ {/* Display current uploads */}+ {uploads.length > 0 && (+ <div className="mt-4">+ <h3 className="font-medium">Uploads</h3>+ <ul className="mt-2 space-y-2">+ {uploads.map((upload, index) => (+ <li key={index} className="text-sm">+ {upload.fileName} - {upload.progress}%+ <div className="mt-1 h-1 rounded-full bg-gray-200">+ <div+ className="h-1 rounded-full bg-blue-500"+ style={{ width: `${upload.progress}%` }}+ />+ </div>+ </li>+ ))}+ </ul>+ </div>+ )}++ {/* Display rejected files */}+ {rejectedFiles.length > 0 && (+ <div className="mt-4">+ <h3 className="font-medium text-red-500">Rejected Files</h3>+ <ul className="mt-2 space-y-1">+ {rejectedFiles.map((file, index) => (+ <li key={index} className="text-sm text-red-500">+ {file.fileName}: {file.message}+ </li>+ ))}+ </ul>+ </div>+ )}+ </div>+ </ViewerUploadZone>+ </div>+ );+}diff --git a/components/viewer-upload-zone.tsx b/components/viewer-upload-zone.tsxnew file mode 100644index 00000000..7409b933--- /dev/null+++ b/components/viewer-upload-zone.tsx@@ -0,0 +1,208 @@+import { useCallback, useRef, useState } from "react";++import { DocumentStorageType } from "@prisma/client";+import { FileRejection, useDropzone } from "react-dropzone";+import { toast } from "sonner";++import { DocumentData } from "@/lib/documents/create-document";+import { viewerUpload } from "@/lib/files/viewer-tus-upload";+import { cn } from "@/lib/utils";+import { getSupportedContentType } from "@/lib/utils/get-content-type";+import { getPagesCount } from "@/lib/utils/get-page-number-count";++// File types allowed for viewer uploads+const acceptableViewerFileTypes = {+ "application/pdf": [], // ".pdf"+ "application/vnd.ms-excel": [], // ".xls"+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": [], // ".xlsx"+ "text/csv": [], // ".csv"+ "application/vnd.oasis.opendocument.spreadsheet": [], // ".ods"+ "image/jpeg": [], // ".jpg"+ "image/png": [], // ".png"+ "image/jpg": [], // ".jpg"+};++export default function ViewerUploadZone({+ children,+ onUploadStart,+ onUploadProgress,+ onUploadComplete,+ onUploadRejected,+ viewerData,+ teamId,+ maxFileSize = 30, // 30 MB default+}: {+ children: React.ReactNode;+ onUploadStart: (uploads: { fileName: string; progress: number }[]) => void;+ onUploadProgress: (index: number, progress: number) => void;+ onUploadComplete: (documentData: DocumentData) => void;+ onUploadRejected: (rejected: { fileName: string; message: string }[]) => void;+ viewerData: {+ id: string;+ linkId: string;+ dataroomId?: string;+ };+ teamId: string;+ maxFileSize?: number;+}) {+ const [progress, setProgress] = useState<number>(0);+ const uploadProgress = useRef<number[]>([]);++ const onDropRejected = useCallback(+ (rejectedFiles: FileRejection[]) => {+ const rejected = rejectedFiles.map(({ file, errors }) => {+ let message = "";+ if (errors.find(({ code }) => code === "file-too-large")) {+ message = `File size too big (max. ${maxFileSize} MB).`;+ } else if (errors.find(({ code }) => code === "file-invalid-type")) {+ message = `File type not supported. Please upload PDF or Excel files.`;+ }+ return { fileName: file.name, message };+ });+ onUploadRejected(rejected);+ },+ [onUploadRejected, maxFileSize],+ );++ const onDrop = useCallback(+ async (acceptedFiles: File[]) => {+ const newUploads = acceptedFiles.map((file) => ({+ fileName: file.name,+ progress: 0,+ }));++ onUploadStart(newUploads);++ const uploadPromises = acceptedFiles.map(async (file, index) => {+ // count the number of pages in the file+ let numPages = 1;+ if (file.type === "application/pdf") {+ const buffer = await file.arrayBuffer();+ numPages = await getPagesCount(buffer);+ }++ const { complete } = await viewerUpload({+ file,+ onProgress: (bytesUploaded, bytesTotal) => {+ uploadProgress.current[index] = (bytesUploaded / bytesTotal) * 100;+ onUploadProgress(+ index,+ Math.min(Math.round(uploadProgress.current[index]), 99),+ );++ const _progress = uploadProgress.current.reduce(+ (acc, progress) => acc + progress,+ 0,+ );++ setProgress(Math.round(_progress / acceptedFiles.length));+ },+ onError: (error) => {+ console.error("Upload error:", error);+ toast.error(`Failed to upload ${file.name}`);+ },+ viewerData,+ teamId,+ numPages,+ });++ const uploadResult = await complete;++ let contentType = uploadResult.fileType;+ let supportedFileType = getSupportedContentType(contentType) ?? "";++ if (+ uploadResult.fileName.endsWith(".dwg") ||+ uploadResult.fileName.endsWith(".dxf")+ ) {+ supportedFileType = "cad";+ contentType = `image/vnd.${uploadResult.fileName.split(".").pop()}`;+ }++ if (uploadResult.fileName.endsWith(".xlsm")) {+ supportedFileType = "sheet";+ contentType = "application/vnd.ms-excel.sheet.macroEnabled.12";+ }++ if (+ uploadResult.fileName.endsWith(".kml") ||+ uploadResult.fileName.endsWith(".kmz")+ ) {+ supportedFileType = "map";+ contentType = `application/vnd.google-earth.${uploadResult.fileName.endsWith(".kml") ? "kml+xml" : "kmz"}`;+ }++ const documentData: DocumentData = {+ key: uploadResult.id,+ supportedFileType: supportedFileType,+ name: file.name,+ storageType: DocumentStorageType.S3_PATH,+ contentType: contentType,+ fileSize: file.size,+ numPages: numPages,+ };++ // Complete the upload by calling the provided callback+ onUploadComplete(documentData);++ onUploadProgress(index, 100); // Mark upload as complete++ return uploadResult;+ });++ try {+ await Promise.all(uploadPromises);+ toast.success("File upload complete!");+ } catch (error) {+ console.error("Upload error:", error);+ toast.error("An error occurred during upload");+ }+ },+ [onUploadStart, onUploadProgress, onUploadComplete, viewerData, teamId],+ );++ const { getRootProps, getInputProps, isDragActive } = useDropzone({+ accept: acceptableViewerFileTypes,+ multiple: true,+ maxSize: maxFileSize * 1024 * 1024,+ onDrop,+ onDropRejected,+ });++ return (+ <div {...getRootProps()} className="relative min-h-[200px]">+ <div+ className={cn(+ "absolute inset-0 z-40 -m-1 rounded-lg border-2 border-dashed",+ isDragActive+ ? "pointer-events-auto border-primary/50 bg-gray-100/75 backdrop-blur-sm dark:bg-gray-800/75"+ : "pointer-events-none border-none",+ )}+ >+ <input+ {...getInputProps()}+ name="file"+ id="viewer-upload-files-zone"+ className="sr-only"+ />++ {isDragActive && (+ <div className="sticky top-1/2 z-50 -translate-y-1/2 px-2">+ <div className="flex justify-center">+ <div className="inline-flex flex-col rounded-lg bg-background/95 px-6 py-4 text-center ring-1 ring-gray-900/5 dark:bg-gray-900/95 dark:ring-white/10">+ <span className="font-medium text-foreground">+ Drop your file(s) here+ </span>+ <p className="mt-1 text-xs leading-5 text-muted-foreground">+ Only *.pdf, *.xls, *.xlsx, *.csv, *.ods files+ </p>+ </div>+ </div>+ </div>+ )}+ </div>++ {children}+ </div>+ );+}diff --git a/lib/auth/dataroom-auth.ts b/lib/auth/dataroom-auth.tsindex 9a0473ee..dbfb05c4 100644--- a/lib/auth/dataroom-auth.ts+++ b/lib/auth/dataroom-auth.ts@@ -1,7 +1,9 @@+import { NextApiRequest } from "next";import { cookies } from "next/headers";import { NextRequest } from "next/server";import { ipAddress } from "@vercel/functions";+import { parse } from "cookie";import crypto from "crypto";import { z } from "zod";@@ -107,4 +109,54 @@ async function verifyDataroomSession(}}+export async function verifyDataroomSessionInPagesRouter(+ req: NextApiRequest,+ linkId: string,+ dataroomId: string,+): Promise<DataroomSession | null> {+ if (!dataroomId) return null;++ // Get cookies from request headers+ const cookies = parse(req.headers.cookie || "");+ const sessionToken = cookies[`pm_drs_${linkId}`];+ if (!sessionToken) return null;++ const session = await redis.get(`dataroom_session:${sessionToken}`);+ if (!session) return null;++ try {+ const sessionData = DataroomSessionSchema.parse(session);++ // Check if session is expired+ if (sessionData.expiresAt < Date.now()) {+ await redis.del(`dataroom_session:${sessionToken}`);+ return null;+ }++ // Get IP address from request+ const ipAddressValue = getIpAddress(req.headers) ?? LOCALHOST_IP;++ if (ipAddressValue !== sessionData.ipAddress) {+ await redis.del(`dataroom_session:${sessionToken}`);+ return null;+ }++ // Check if the session is for the correct link and dataroom+ if (+ sessionData.linkId !== linkId ||+ sessionData.dataroomId !== dataroomId+ ) {+ await redis.del(`dataroom_session:${sessionToken}`);+ return null;+ }++ return sessionData;+ } catch (error) {+ console.log("error", error);+ // If validation fails, delete invalid session and return null+ await redis.del(`dataroom_session:${sessionToken}`);+ return null;+ }+}+export { createDataroomSession, verifyDataroomSession };diff --git a/lib/files/viewer-tus-upload.ts b/lib/files/viewer-tus-upload.tsnew file mode 100644index 00000000..aa43de5e--- /dev/null+++ b/lib/files/viewer-tus-upload.ts@@ -0,0 +1,118 @@+import * as tus from "tus-js-client";++import { decodeBase64Url } from "../utils/decode-base64url";++type ViewerUploadParams = {+ file: File;+ onProgress?: (bytesUploaded: number, bytesTotal: number) => void;+ onError?: (error: Error | tus.DetailedError) => void;+ viewerData: {+ id: string;+ linkId: string;+ dataroomId?: string;+ };+ teamId: string;+ numPages: number;+};++type UploadResult = {+ id: string;+ url: string;+ fileName: string;+ fileType: string;+ numPages: number;+ viewerId: string;+ linkId: string;+ dataroomId?: string;+ teamId: string;+};++export function viewerUpload({+ file,+ onProgress,+ onError,+ viewerData,+ teamId,+ numPages,+}: ViewerUploadParams) {+ return new Promise<{ upload: tus.Upload; complete: Promise<UploadResult> }>(+ (resolve, reject) => {+ let completeResolve: (+ value: UploadResult | PromiseLike<UploadResult>,+ ) => void;+ const complete = new Promise<UploadResult>((res) => {+ completeResolve = res;+ });++ const upload = new tus.Upload(file, {+ endpoint: `${process.env.NEXT_PUBLIC_BASE_URL}/api/file/tus-viewer`,+ retryDelays: [0, 3000, 5000, 10000],+ uploadDataDuringCreation: true,+ removeFingerprintOnSuccess: true,+ metadata: {+ fileName: file.name,+ contentType: file.type,+ numPages: String(numPages),+ teamId: teamId,+ viewerId: viewerData.id,+ linkId: viewerData.linkId,+ dataroomId: viewerData.dataroomId || "",+ },+ chunkSize: 4 * 1024 * 1024,+ onError: (error) => {+ onError && onError(error);+ console.error("Failed because: " + error);+ reject(error);+ },+ onShouldRetry(error, retryAttempt, options) {+ console.error(`Should retry upload. Attempt ${retryAttempt}`);+ var status = error.originalResponse+ ? error.originalResponse.getStatus()+ : 0;+ // Do not retry if the status is a 500 or 403.+ if (status === 500 || status === 403) {+ return false;+ }+ // For any other status code, we retry.+ return true;+ },+ onProgress,+ onSuccess: () => {+ console.log("Uploaded successfully");+ const id = upload.url!.split("/api/file/tus-viewer/")[1];+ // if id contains a slash, then we use it as it otherwise we need to convert from buffer base64URL to utf-8+ const newId = id.includes("/") ? id : decodeBase64Url(id);+ completeResolve({+ id: newId,+ url: upload.url!,+ fileName: file.name,+ fileType: file.type,+ numPages,+ viewerId: viewerData.id,+ linkId: viewerData.linkId,+ dataroomId: viewerData.dataroomId,+ teamId,+ });+ },+ });++ // Check if there are any previous uploads to continue.+ upload+ .findPreviousUploads()+ .then((previousUploads) => {+ // Found previous uploads so we select the first one.+ if (previousUploads.length) {+ upload.resumeFromPreviousUpload(previousUploads[0]);+ }++ upload.start();+ resolve({ upload, complete });+ })+ .catch((error) => {+ console.error("Error finding previous uploads:", error);+ upload.start();+ resolve({ upload, complete });+ });+ },+ );+}diff --git a/package-lock.json b/package-lock.jsonindex 583aed6f..9105db92 100644--- a/package-lock.json+++ b/package-lock.json@@ -134,6 +134,7 @@"@trigger.dev/build": "^3.3.17","@trivago/prettier-plugin-sort-imports": "^5.2.2","@types/bcryptjs": "^2.4.6",+ "@types/cookie": "^0.6.0","@types/fluent-ffmpeg": "^2.1.27","@types/js-cookie": "^3.0.6","@types/jsonwebtoken": "^9.0.7",@@ -5966,6 +5967,13 @@"integrity": "sha512-9xlo6R2qDs5uixm0bcIqCeMCE6HiQsIyel9KQySStiyqNl2tnj2mP3DX1Nf56MD6KMenNNlBBsy3LJ7gUEQPXQ==","dev": true},+ "node_modules/@types/cookie": {+ "version": "0.6.0",+ "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz",+ "integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==",+ "dev": true,+ "license": "MIT"+ },"node_modules/@types/cors": {"version": "2.8.17","resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.17.tgz",@@ -16957,21 +16965,6 @@"peerDependencies": {"zod": "^3.18.0"}- },- "node_modules/react-email/node_modules/@next/swc-win32-ia32-msvc": {- "version": "14.2.25",- "resolved": "https://registry.npmjs.org/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-14.2.25.tgz",- "integrity": "sha512-DZ/gc0o9neuCDyD5IumyTGHVun2dCox5TfPQI/BJTYwpSNYM3CZDI4i6TOdjeq1JMo+Ug4kPSMuZdwsycwFbAw==",- "cpu": [- "ia32"- ],- "optional": true,- "os": [- "win32"- ],- "engines": {- "node": ">= 10"- }}}}diff --git a/package.json b/package.jsonindex 4493a75c..20ccca38 100644--- a/package.json+++ b/package.json@@ -145,6 +145,7 @@"@trigger.dev/build": "^3.3.17","@trivago/prettier-plugin-sort-imports": "^5.2.2","@types/bcryptjs": "^2.4.6",+ "@types/cookie": "^0.6.0","@types/fluent-ffmpeg": "^2.1.27","@types/js-cookie": "^3.0.6","@types/jsonwebtoken": "^9.0.7",diff --git a/pages/api/file/tus-viewer/[[...file]].ts b/pages/api/file/tus-viewer/[[...file]].tsnew file mode 100644index 00000000..9e92c236--- /dev/null+++ b/pages/api/file/tus-viewer/[[...file]].ts@@ -0,0 +1,263 @@+import type { NextApiRequest, NextApiResponse } from "next";++import { CopyObjectCommand } from "@aws-sdk/client-s3";+import slugify from "@sindresorhus/slugify";+import { S3Store } from "@tus/s3-store";+import { Server } from "@tus/server";+import path from "node:path";++import { verifyDataroomSessionInPagesRouter } from "@/lib/auth/dataroom-auth";+import { getS3Client } from "@/lib/files/aws-client";+import { RedisLocker } from "@/lib/files/tus-redis-locker";+import { newId } from "@/lib/id-helper";+import prisma from "@/lib/prisma";+import { lockerRedisClient } from "@/lib/redis";+import { log } from "@/lib/utils";++export const config = {+ api: {+ bodyParser: false,+ },+};++const locker = new RedisLocker({+ redisClient: lockerRedisClient,+});++const client = getS3Client();++const tusServer = new Server({+ // `path` needs to match the route declared by the next file router+ path: "/api/file/tus-viewer",+ maxSize: 1024 * 1024 * 1024 * 2, // 2 GiB+ respectForwardedHeaders: true,+ locker,+ datastore: new S3Store({+ partSize: 8 * 1024 * 1024, // each uploaded part will have ~8MiB+ s3ClientConfig: {+ bucket: process.env.NEXT_PRIVATE_UPLOAD_BUCKET as string,+ region: process.env.NEXT_PRIVATE_UPLOAD_REGION as string,+ credentials: {+ accessKeyId: process.env.NEXT_PRIVATE_UPLOAD_ACCESS_KEY_ID as string,+ secretAccessKey: process.env+ .NEXT_PRIVATE_UPLOAD_SECRET_ACCESS_KEY as string,+ },+ },+ }),+ async namingFunction(req, metadata) {+ // Extract viewer data from metadata+ const { teamId, fileName, viewerId, linkId, dataroomId } = metadata as {+ teamId: string;+ fileName: string;+ viewerId: string;+ linkId: string;+ dataroomId: string;+ };++ // Validate the viewer exists and has permission+ let teamIdToUse = teamId;+ try {+ if (teamId !== "visitor-upload") {+ throw new Error("Unauthorized to access this team");+ }++ const link = await prisma.link.findUnique({+ where: {+ id: linkId,+ dataroomId: dataroomId || null,+ },+ select: { teamId: true, enableUpload: true },+ });++ if (!link || !link.enableUpload || !link.teamId) {+ throw new Error("Upload not allowed");+ }++ const viewer = await prisma.viewer.findUnique({+ where: { id: viewerId },+ select: { teamId: true },+ });++ if (!viewer || viewer.teamId !== link.teamId) {+ throw new Error("Unauthorized to access this team");+ }++ teamIdToUse = link.teamId;+ } catch (error) {+ console.error("Error validating viewer:", error);+ throw new Error("Unauthorized");+ }++ const docId = newId("doc");+ const { name, ext } = path.parse(fileName);+ const newName = `${teamIdToUse}/${docId}/${slugify(name)}${ext}`;+ return newName;+ },+ generateUrl(req, { proto, host, path, id }) {+ // Encode the ID to be URL safe+ id = Buffer.from(id, "utf-8").toString("base64url");+ return `${proto}://${host}${path}/${id}`;+ },+ getFileIdFromRequest(req) {+ // Extract the ID from the URL+ const id = (req.url as string).split("/api/file/tus-viewer/")[1];+ return Buffer.from(id, "base64url").toString("utf-8");+ },+ onResponseError(req, res, err) {+ log({+ message: "Error uploading a file via viewer. Error: \n\n" + err,+ type: "error",+ });+ return { status_code: 500, body: "Internal Server Error" };+ },+ async onUploadCreate(req, res, upload) {+ // Extract viewer data from metadata+ const { teamId, fileName, viewerId, linkId, dataroomId } =+ upload.metadata as {+ teamId: string;+ fileName: string;+ viewerId: string;+ dataroomId: string;+ linkId: string;+ };++ // Validate the viewer exists and has permission+ try {+ if (teamId !== "visitor-upload") {+ throw new Error("Unauthorized to access this team");+ }++ const link = await prisma.link.findUnique({+ where: {+ id: linkId,+ dataroomId: dataroomId || null,+ },+ select: { teamId: true, enableUpload: true },+ });++ if (!link || !link.enableUpload || !link.teamId) {+ throw new Error("Upload not allowed");+ }++ const viewer = await prisma.viewer.findUnique({+ where: { id: viewerId },+ select: { teamId: true },+ });++ if (!viewer || viewer.teamId !== link.teamId) {+ throw new Error("Unauthorized to access this team");+ }++ return res;+ } catch (error) {+ console.error("Error validating viewer:", error);+ throw new Error("Unauthorized");+ }+ },+ async onUploadFinish(req, res, upload) {+ try {+ const metadata = upload.metadata || {};+ const contentType = metadata.contentType || "application/octet-stream";+ const { name, ext } = path.parse(metadata.fileName!);+ const contentDisposition = `attachment; filename="${slugify(name)}${ext}"`;++ // The Key (object path) where the file was uploaded+ const objectKey = upload.id;++ // Copy the object onto itself, replacing the metadata+ const params = {+ Bucket: process.env.NEXT_PRIVATE_UPLOAD_BUCKET,+ CopySource: `${process.env.NEXT_PRIVATE_UPLOAD_BUCKET}/${objectKey}`,+ Key: objectKey,+ ContentType: contentType,+ ContentDisposition: contentDisposition,+ MetadataDirective: "REPLACE" as const,+ };++ const copyCommand = new CopyObjectCommand(params);+ await client.send(copyCommand);++ return res;+ } catch (error) {+ throw { status_code: 500, body: "Error updating metadata" };+ }+ },+ async onIncomingRequest(req, res, uploadId) {+ // Check if this is a new upload or continuation+ if (req.method === "POST" && !uploadId) {+ // For new uploads, we need to parse the Upload-Metadata header to get linkId and dataroomId+ const metadataHeader = req.headers["upload-metadata"];++ if (!metadataHeader) {+ throw { status_code: 403, body: "Missing upload metadata" };+ }++ // Parse TUS metadata (format: key base64value,key2 base64value2)+ const metadata: Record<string, string> = {};+ const headerString = Array.isArray(metadataHeader)+ ? metadataHeader[0]+ : metadataHeader;+ headerString.split(",").forEach((item: string) => {+ const [key, value] = item.trim().split(" ");+ if (key && value) {+ metadata[key] = Buffer.from(value, "base64").toString();+ }+ });++ const { linkId, dataroomId, viewerId } = metadata;++ if (!linkId || !dataroomId) {+ throw { status_code: 403, body: "Missing required metadata" };+ }++ // Verify the session+ const session = await verifyDataroomSessionInPagesRouter(+ req as NextApiRequest,+ linkId,+ dataroomId,+ );++ if (!session) {+ throw { status_code: 403, body: "Unauthorized" };+ }++ // Optional: Verify that the viewerId in the request matches the session+ if (viewerId && session.viewerId && viewerId !== session.viewerId) {+ throw { status_code: 403, body: "Invalid viewer" };+ }+ }+ },+});++// CORS headers to allow custom domains+const setCorsHeaders = (req: NextApiRequest, res: NextApiResponse) => {+ // Set CORS headers+ res.setHeader("Access-Control-Allow-Credentials", "true");+ res.setHeader("Access-Control-Allow-Origin", req.headers.origin || "*");+ res.setHeader(+ "Access-Control-Allow-Methods",+ "POST, GET, OPTIONS, DELETE, PATCH, HEAD",+ );+ res.setHeader(+ "Access-Control-Allow-Headers",+ "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version, Upload-Length, Upload-Metadata, Upload-Offset, Tus-Resumable, Upload-Defer-Length, Upload-Concat",+ );+ res.setHeader(+ "Access-Control-Expose-Headers",+ "Upload-Offset, Location, Upload-Length, Tus-Version, Tus-Resumable, Tus-Max-Size, Tus-Extension, Upload-Metadata, Upload-Defer-Length, Upload-Concat",+ );+};++export default function handler(req: NextApiRequest, res: NextApiResponse) {+ // Handle CORS preflight requests+ if (req.method === "OPTIONS") {+ setCorsHeaders(req, res);+ return res.status(204).end();+ }++ // Set CORS headers for all requests+ setCorsHeaders(req, res);++ // No session check - authentication is handled via viewer metadata+ return tusServer.handle(req, res);+}