Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat(dataroom): open dataroom documents in new tab
Marc Seitz1c82114aac7e
diff --git a/components/view/DataroomViewer.tsx b/components/view/DataroomViewer.tsxindex 079b6e1c..e284a88e 100644--- a/components/view/DataroomViewer.tsx+++ b/components/view/DataroomViewer.tsx@@ -24,7 +24,6 @@ import {import { cn } from "@/lib/utils";-import { TDocumentData } from "./dataroom/dataroom-view";import DocumentCard from "./dataroom/document-card";import FolderCard from "./dataroom/folder-card";import DataroomNav from "./dataroom/nav-dataroom";@@ -68,12 +67,8 @@ export default function DataroomViewer({brand,viewId,linkId,- dataroomViewId,dataroom,allowDownload,- setViewType,- setDocumentData,- setDataroomVerified,isPreview,folderId,setFolderId,@@ -81,14 +76,8 @@ export default function DataroomViewer({brand: Partial<DataroomBrand>;viewId?: string;linkId: string;- dataroomViewId: string;dataroom: any;allowDownload: boolean;- setViewType: React.Dispatch<- React.SetStateAction<"DOCUMENT_VIEW" | "DATAROOM_VIEW">- >;- setDocumentData: React.Dispatch<React.SetStateAction<TDocumentData | null>>;- setDataroomVerified: React.Dispatch<React.SetStateAction<boolean>>;isPreview?: boolean;folderId: string | null;setFolderId: React.Dispatch<React.SetStateAction<string | null>>;@@ -119,14 +108,7 @@ export default function DataroomViewer({const renderItem = (item: FolderOrDocument) => {if ("versions" in item) {- return (- <DocumentCard- key={item.id}- document={item}- setViewType={setViewType}- setDocumentData={setDocumentData}- />- );+ return <DocumentCard key={item.id} document={item} linkId={linkId} />;}return (diff --git a/components/view/dataroom/dataroom-document-view.tsx b/components/view/dataroom/dataroom-document-view.tsxnew file mode 100644index 00000000..14a94523--- /dev/null+++ b/components/view/dataroom/dataroom-document-view.tsx@@ -0,0 +1,327 @@+import { useRouter } from "next/router";++import React, { useEffect, useRef, useState } from "react";++import { DataroomBrand } from "@prisma/client";+import Cookies from "js-cookie";+import { ExtendedRecordMap } from "notion-types";+import { toast } from "sonner";++import LoadingSpinner from "@/components/ui/loading-spinner";+import AccessForm, {+ DEFAULT_ACCESS_FORM_DATA,+ DEFAULT_ACCESS_FORM_TYPE,+} from "@/components/view/access-form";++import { useAnalytics } from "@/lib/analytics";+import { SUPPORTED_DOCUMENT_SIMPLE_TYPES } from "@/lib/constants";+import { LinkWithDataroomDocument, NotionTheme } from "@/lib/types";++import EmailVerificationMessage from "../email-verification-form";+import ViewData, { TViewDocumentData } from "../view-data";++type RowData = { [key: string]: any };+type SheetData = {+ sheetName: string;+ columnData: string[];+ rowData: RowData[];+};++export type TSupportedDocumentSimpleType =+ (typeof SUPPORTED_DOCUMENT_SIMPLE_TYPES)[number];++type DEFAULT_DOCUMENT_VIEW_TYPE = {+ viewId?: string;+ dataroomViewId?: string;+ file?: string | null;+ pages?:+ | {+ file: string;+ pageNumber: string;+ embeddedLinks: string[];+ pageLinks: { href: string; coords: string }[];+ metadata: { width: number; height: number; scaleFactor: number };+ }[]+ | null;+ sheetData?: SheetData[] | null;+ notionData?: {+ recordMap: ExtendedRecordMap | null;+ theme: NotionTheme | null | undefined;+ };+ fileType?: string;+ ipAddress?: string;+ useAdvancedExcelViewer?: boolean;+ isPreview?: boolean;+ canDownload?: boolean;+ verificationToken?: string;+};++export default function DataroomDocumentView({+ link,+ userEmail,+ userId,+ isProtected,+ notionData,+ brand,+ token,+ verifiedEmail,+ useAdvancedExcelViewer,+ previewToken,+ disableEditEmail,+ useCustomAccessForm,+ isEmbedded,+ preview,+}: {+ link: LinkWithDataroomDocument;+ userEmail: string | null | undefined;+ userId: string | null | undefined;+ isProtected: boolean;+ notionData?: {+ rootNotionPageId: string | null;+ recordMap: ExtendedRecordMap | null;+ theme: NotionTheme | null;+ };+ brand?: Partial<DataroomBrand> | null;+ token?: string;+ verifiedEmail?: string;+ useAdvancedExcelViewer?: boolean;+ previewToken?: string;+ disableEditEmail?: boolean;+ useCustomAccessForm?: boolean;+ isEmbedded?: boolean;+ preview?: boolean;+}) {+ const {+ linkType,+ emailProtected,+ password: linkPassword,+ enableAgreement,+ } = link;++ const analytics = useAnalytics();+ const router = useRouter();++ const didMount = useRef<boolean>(false);+ const [submitted, setSubmitted] = useState<boolean>(false);+ const [isLoading, setIsLoading] = useState<boolean>(false);+ const [viewData, setViewData] = useState<DEFAULT_DOCUMENT_VIEW_TYPE>({+ viewId: "",+ });+ const [data, setData] = useState<DEFAULT_ACCESS_FORM_TYPE>(+ DEFAULT_ACCESS_FORM_DATA,+ );+ const [verificationRequested, setVerificationRequested] =+ useState<boolean>(false);+ const [dataroomVerified, setDataroomVerified] = useState<boolean>(false);+ const [verificationToken, setVerificationToken] = useState<string | null>(+ token ?? null,+ );++ const [code, setCode] = useState<string | null>(null);+ const [isInvalidCode, setIsInvalidCode] = useState<boolean>(false);++ const handleSubmission = async (): Promise<void> => {+ setIsLoading(true);+ const response = await fetch("/api/views-dataroom", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ ...data,+ email: data.email ?? verifiedEmail ?? userEmail ?? null,+ linkId: link.id,+ documentId: link.dataroomDocument.document.id,+ documentName: link.dataroomDocument.document.name,+ userId: userId ?? null,+ documentVersionId: link.dataroomDocument.document.versions[0].id,+ hasPages: link.dataroomDocument.document.versions[0].hasPages,+ dataroomVerified: dataroomVerified,+ dataroomId: link.dataroomId,+ linkType: "DATAROOM_LINK",+ dataroomViewId: viewData.dataroomViewId ?? null,+ viewType: "DOCUMENT_VIEW",+ useAdvancedExcelViewer,+ previewToken,+ code: code ?? undefined,+ token: verificationToken ?? undefined,+ verifiedEmail: verifiedEmail ?? undefined,+ }),+ });++ if (response.ok) {+ const fetchData = await response.json();++ if (fetchData.type === "email-verification") {+ setVerificationRequested(true);+ setIsLoading(false);+ } else {+ const {+ viewId,+ file,+ pages,+ notionData,+ sheetData,+ fileType,+ isPreview,+ ipAddress,+ useAdvancedExcelViewer,+ canDownload,+ verificationToken,+ } = fetchData as DEFAULT_DOCUMENT_VIEW_TYPE;+ analytics.identify(+ userEmail ?? verifiedEmail ?? data.email ?? undefined,+ );+ analytics.capture("Link Viewed", {+ linkId: link.id,+ documentId: link.dataroomDocument.document.id,+ dataroomId: link.dataroomId,+ linkType: linkType,+ viewerId: viewId,+ viewerEmail: data.email ?? verifiedEmail ?? userEmail,+ isEmbedded,+ });++ // set the verification token to the cookie+ // TODO: remove verificaiton token for something simpler as we are setting the token on cookie directly+ if (verificationToken) {+ // Cookies.set("pm_vft", verificationToken, {+ // path: router.asPath.split("?")[0],+ // expires: 1,+ // sameSite: "strict",+ // secure: true,+ // });+ setCode(null);+ }++ setViewData((prev) => ({+ viewId,+ dataroomViewId: prev.dataroomViewId,+ file,+ pages,+ notionData,+ sheetData,+ fileType,+ isPreview,+ ipAddress,+ useAdvancedExcelViewer,+ canDownload,+ }));+ setSubmitted(true);+ setVerificationRequested(false);+ setIsLoading(false);+ }+ } else {+ const data = await response.json();+ toast.error(data.message);++ if (data.resetVerification) {+ const currentPath = router.asPath.split("?")[0];++ Cookies.remove("pm_vft", { path: currentPath });+ setVerificationToken(null);+ setCode(null);+ setIsInvalidCode(true);+ setDataroomVerified(false);+ }+ setIsLoading(false);+ }+ };++ const handleSubmit: React.FormEventHandler<HTMLFormElement> = async (+ event: React.FormEvent,+ ): Promise<void> => {+ event.preventDefault();+ await handleSubmission();+ };++ // If token is present, run handle submit which will verify token and get document+ // If link is not submitted and does not have email / password protection, show the access form+ useEffect(() => {+ if (!didMount.current) {+ if (+ (!submitted && !isProtected) ||+ token ||+ preview ||+ viewData.dataroomViewId+ ) {+ handleSubmission();+ didMount.current = true;+ }+ }+ }, [submitted, isProtected, token, preview, viewData.dataroomViewId]);++ // Components to render when email is submitted but verification is pending+ if (verificationRequested) {+ return (+ <EmailVerificationMessage+ onSubmitHandler={handleSubmit}+ data={data}+ isLoading={isLoading}+ code={code}+ setCode={setCode}+ isInvalidCode={isInvalidCode}+ setIsInvalidCode={setIsInvalidCode}+ />+ );+ }++ // If link is not submitted and does not have email / password protection, show the access form+ if (!submitted && isProtected) {+ return (+ <AccessForm+ data={data}+ email={userEmail}+ setData={setData}+ onSubmitHandler={handleSubmit}+ requireEmail={emailProtected}+ requirePassword={!!linkPassword}+ requireAgreement={enableAgreement!}+ agreementName={link.agreement?.name}+ agreementContent={link.agreement?.content}+ requireName={link.agreement?.requireName}+ isLoading={isLoading}+ disableEditEmail={disableEditEmail}+ useCustomAccessForm={useCustomAccessForm}+ brand={brand}+ customFields={link.customFields}+ />+ );+ }++ if (isLoading) {+ return (+ <div className="flex h-screen items-center justify-center">+ <LoadingSpinner className="h-20 w-20" />+ </div>+ );+ }+ return (+ <div+ className="bg-gray-950"+ style={{+ backgroundColor:+ brand && brand.accentColor ? brand.accentColor : "rgb(3, 7, 18)",+ }}+ >+ {submitted ? (+ <ViewData+ dataroomId={link.dataroomId!}+ link={link}+ document={link.dataroomDocument.document as TViewDocumentData}+ viewData={viewData}+ notionData={notionData}+ brand={brand}+ showPoweredByBanner={false}+ showAccountCreationSlide={false}+ useAdvancedExcelViewer={useAdvancedExcelViewer}+ viewerEmail={data.email ?? verifiedEmail ?? userEmail ?? undefined}+ />+ ) : (+ <div className="flex h-screen items-center justify-center">+ <LoadingSpinner className="h-20 w-20" />+ </div>+ )}+ </div>+ );+}diff --git a/components/view/dataroom/dataroom-view.tsx b/components/view/dataroom/dataroom-view.tsxindex af783cc3..ccb980d9 100644--- a/components/view/dataroom/dataroom-view.tsx+++ b/components/view/dataroom/dataroom-view.tsx@@ -1,15 +1,11 @@-import dynamic from "next/dynamic";import { useRouter } from "next/router";import React, { useEffect, useRef, useState } from "react";import { DataroomBrand } from "@prisma/client";import Cookies from "js-cookie";-import { usePlausible } from "next-plausible";-import { ExtendedRecordMap } from "notion-types";import { toast } from "sonner";-import { NotionPage } from "@/components/NotionPage";import LoadingSpinner from "@/components/ui/loading-spinner";import AccessForm, {DEFAULT_ACCESS_FORM_DATA,@@ -18,28 +14,10 @@ import AccessForm, {import { useAnalytics } from "@/lib/analytics";import { SUPPORTED_DOCUMENT_SIMPLE_TYPES } from "@/lib/constants";-import { LinkWithDataroom, NotionTheme, WatermarkConfig } from "@/lib/types";+import { LinkWithDataroom } from "@/lib/types";import DataroomViewer from "../DataroomViewer";import EmailVerificationMessage from "../email-verification-form";-import AdvancedExcelViewer from "../viewer/advanced-excel-viewer";-import DownloadOnlyViewer from "../viewer/download-only-viewer";-import ImageViewer from "../viewer/image-viewer";-import PagesHorizontalViewer from "../viewer/pages-horizontal-viewer";-import PagesVerticalViewer from "../viewer/pages-vertical-viewer";-import VideoViewer from "../viewer/video-viewer";--const ExcelViewer = dynamic(- () => import("@/components/view/viewer/excel-viewer"),- { ssr: false },-);--type RowData = { [key: string]: any };-type SheetData = {- sheetName: string;- columnData: string[];- rowData: RowData[];-};export type TSupportedDocumentSimpleType =(typeof SUPPORTED_DOCUMENT_SIMPLE_TYPES)[number];@@ -55,29 +33,9 @@ export type TDocumentData = {isVertical?: boolean;};-export type DEFAULT_DOCUMENT_VIEW_TYPE = {+type DEFAULT_DATAROOM_VIEW_TYPE = {viewId?: string;isPreview?: boolean;- dataroomViewId?: string;- file?: string | null;- pages?:- | {- file: string;- pageNumber: string;- embeddedLinks: string[];- pageLinks: { href: string; coords: string }[];- metadata: { width: number; height: number; scaleFactor: number };- }[]- | null;- sheetData?: SheetData[] | null;- notionData?: {- recordMap: ExtendedRecordMap | null;- theme: NotionTheme | null | undefined;- };- fileType?: string;- ipAddress?: string;- useAdvancedExcelViewer?: boolean;- canDownload?: boolean;verificationToken?: string;};@@ -89,11 +47,11 @@ export default function DataroomView({brand,token,verifiedEmail,- useAdvancedExcelViewer,previewToken,disableEditEmail,useCustomAccessForm,isEmbedded,+ preview,}: {link: LinkWithDataroom;userEmail: string | null | undefined;@@ -102,11 +60,11 @@ export default function DataroomView({brand?: Partial<DataroomBrand> | null;token?: string;verifiedEmail?: string;- useAdvancedExcelViewer?: boolean;previewToken?: string;disableEditEmail?: boolean;useCustomAccessForm?: boolean;isEmbedded?: boolean;+ preview?: boolean;}) {const {linkType,@@ -116,7 +74,6 @@ export default function DataroomView({enableAgreement,} = link;- const plausible = usePlausible();const analytics = useAnalytics();const router = useRouter();const [folderId, setFolderId] = useState<string | null>(null);@@ -124,7 +81,7 @@ export default function DataroomView({const didMount = useRef<boolean>(false);const [submitted, setSubmitted] = useState<boolean>(false);const [isLoading, setIsLoading] = useState<boolean>(false);- const [viewData, setViewData] = useState<DEFAULT_DOCUMENT_VIEW_TYPE>({+ const [viewData, setViewData] = useState<DEFAULT_DATAROOM_VIEW_TYPE>({viewId: "",});const [data, setData] = useState<DEFAULT_ACCESS_FORM_TYPE>(@@ -132,8 +89,6 @@ export default function DataroomView({);const [verificationRequested, setVerificationRequested] =useState<boolean>(false);- const [dataroomVerified, setDataroomVerified] = useState<boolean>(false);- const [documentData, setDocumentData] = useState<TDocumentData | null>(null);const [verificationToken, setVerificationToken] = useState<string | null>(token ?? null,);@@ -141,10 +96,6 @@ export default function DataroomView({const [code, setCode] = useState<string | null>(null);const [isInvalidCode, setIsInvalidCode] = useState<boolean>(false);- const [viewType, setViewType] = useState<"DOCUMENT_VIEW" | "DATAROOM_VIEW">(- "DATAROOM_VIEW",- );-const handleSubmission = async (): Promise<void> => {setIsLoading(true);const response = await fetch("/api/views-dataroom", {@@ -156,17 +107,10 @@ export default function DataroomView({...data,email: data.email ?? verifiedEmail ?? userEmail ?? null,linkId: link.id,- documentId: documentData?.id,- documentName: documentData?.name,userId: userId ?? null,- documentVersionId: documentData?.documentVersionId,- hasPages: documentData?.hasPages,- dataroomVerified: dataroomVerified,dataroomId: dataroom?.id,- linkType: linkType,- dataroomViewId: viewData.dataroomViewId ?? null,- viewType: viewType,- useAdvancedExcelViewer,+ linkType: "DATAROOM_LINK",+ viewType: "DATAROOM_VIEW",previewToken,code: code ?? undefined,token: verificationToken ?? undefined,@@ -181,26 +125,14 @@ export default function DataroomView({setVerificationRequested(true);setIsLoading(false);} else {- const {- viewId,- file,- pages,- notionData,- sheetData,- fileType,- isPreview,- ipAddress,- useAdvancedExcelViewer,- canDownload,- verificationToken,- } = fetchData as DEFAULT_DOCUMENT_VIEW_TYPE;- plausible("dataroomViewed"); // track the event+ const { viewId, isPreview, verificationToken } =+ fetchData as DEFAULT_DATAROOM_VIEW_TYPE;+analytics.identify(userEmail ?? verifiedEmail ?? data.email ?? undefined,);analytics.capture("Link Viewed", {linkId: link.id,- documentId: documentData?.id,dataroomId: dataroom?.id,linkType: linkType,viewerId: viewId,@@ -210,32 +142,21 @@ export default function DataroomView({// set the verification token to the cookieif (verificationToken) {- Cookies.set("pm_vft", verificationToken, {- path: router.asPath.split("?")[0],- expires: 1,- sameSite: "strict",- secure: true,- });+ // Cookies.set("pm_vft", verificationToken, {+ // path: router.asPath.split("?")[0],+ // expires: 1,+ // sameSite: "strict",+ // secure: true,+ // });setCode(null);}- setViewData((prev) => ({+ setViewData({viewId,- dataroomViewId:- viewType === "DATAROOM_VIEW" ? viewId : prev.dataroomViewId,- file,- pages,- notionData,- sheetData,- fileType,isPreview,- ipAddress,- useAdvancedExcelViewer,- canDownload,- }));+ });setSubmitted(true);setVerificationRequested(false);- viewType === "DATAROOM_VIEW" && setDataroomVerified(true);setIsLoading(false);}} else {@@ -249,7 +170,6 @@ export default function DataroomView({setVerificationToken(null);setCode(null);setIsInvalidCode(true);- setDataroomVerified(false);}setIsLoading(false);}@@ -266,32 +186,12 @@ export default function DataroomView({// If link is not submitted and does not have email / password protection, show the access formuseEffect(() => {if (!didMount.current) {- if ((!submitted && !isProtected) || token || viewData.dataroomViewId) {- handleSubmission();- }- didMount.current = true;- }- }, [submitted, isProtected, token, viewData.dataroomViewId]);-- useEffect(() => {- // Ensure we're not running this logic on initial mount, but only when `documentData` changes thereafter- if (didMount.current) {- if (documentData !== null) {- // Call handleSubmission or any other logic that needs to run when a document is selected+ if ((!submitted && !isProtected) || token || preview) {handleSubmission();+ didMount.current = true;}}-- setViewData((prev) => ({- ...prev,- pages: undefined,- file: undefined,- viewId: prev.dataroomViewId,- notionData: undefined,- ipAddress: undefined,- }));- // This effect is specifically for handling changes to `documentData` post-mount- }, [documentData]);+ }, [submitted, isProtected, token, preview]);// Components to render when email is submitted but verification is pendingif (verificationRequested) {@@ -339,215 +239,7 @@ export default function DataroomView({);}- if (submitted && documentData) {- return viewData.notionData?.recordMap ? (- <div- className="bg-gray-950"- style={{- backgroundColor:- brand && brand.accentColor ? brand.accentColor : "rgb(3, 7, 18)",- }}- >- <NotionPage- recordMap={viewData.notionData.recordMap}- viewId={viewData.viewId}- isPreview={viewData.isPreview}- linkId={link.id}- documentId={documentData.id}- documentName={documentData.name}- versionNumber={documentData.documentVersionNumber}- brand={brand}- dataroomId={dataroom.id}- theme={viewData.notionData.theme}- setDocumentData={setDocumentData}- screenshotProtectionEnabled={link.enableScreenshotProtection!}- />- </div>- ) : documentData?.downloadOnly ? (- <DownloadOnlyViewer- file={viewData.file!}- linkId={link.id}- documentId={documentData.id}- viewId={viewData.viewId}- allowDownload={true}- versionNumber={documentData.documentVersionNumber}- brand={brand}- documentName={documentData.name}- isPreview={viewData.isPreview}- dataroomId={dataroom.id}- setDocumentData={setDocumentData}- />- ) : viewData.fileType === "sheet" && viewData.sheetData ? (- <div- className="bg-gray-950"- style={{- backgroundColor:- brand && brand.accentColor ? brand.accentColor : "rgb(3, 7, 18)",- }}- >- <ExcelViewer- linkId={link.id}- viewId={viewData.viewId}- isPreview={viewData.isPreview}- documentId={documentData.id}- documentName={documentData.name}- versionNumber={documentData.documentVersionNumber}- sheetData={viewData.sheetData}- brand={brand}- dataroomId={dataroom.id}- setDocumentData={setDocumentData}- allowDownload={viewData.canDownload ?? link.allowDownload!}- screenshotProtectionEnabled={link.enableScreenshotProtection!}- />- </div>- ) : viewData.fileType === "sheet" && viewData.useAdvancedExcelViewer ? (- <div- className="bg-gray-950"- style={{- backgroundColor:- brand && brand.accentColor ? brand.accentColor : "rgb(3, 7, 18)",- }}- >- <AdvancedExcelViewer- linkId={link.id}- viewId={viewData.viewId}- isPreview={viewData.isPreview}- documentId={documentData.id}- documentName={documentData.name}- versionNumber={documentData.documentVersionNumber}- file={viewData.file!}- allowDownload={viewData.canDownload ?? link.allowDownload!}- brand={brand}- dataroomId={dataroom.id}- setDocumentData={setDocumentData}- />- </div>- ) : viewData.fileType === "image" ? (- <div- className="bg-gray-950"- style={{- backgroundColor:- brand && brand.accentColor ? brand.accentColor : "rgb(3, 7, 18)",- }}- >- <ImageViewer- file={viewData.file!}- linkId={link.id}- viewId={viewData.viewId}- isPreview={viewData.isPreview}- documentId={documentData.id}- documentName={documentData.name}- allowDownload={viewData.canDownload ?? link.allowDownload!}- feedbackEnabled={link.enableFeedback!}- screenshotProtectionEnabled={link.enableScreenshotProtection!}- screenShieldPercentage={link.screenShieldPercentage}- versionNumber={documentData.documentVersionNumber}- brand={brand}- dataroomId={dataroom.id}- setDocumentData={setDocumentData}- viewerEmail={data.email ?? verifiedEmail ?? userEmail ?? undefined}- watermarkConfig={- link.enableWatermark- ? (link.watermarkConfig as WatermarkConfig)- : null- }- ipAddress={viewData.ipAddress}- linkName={link.name ?? `Link #${link.id.slice(-5)}`}- />- </div>- ) : viewData.fileType === "video" ? (- <div- className="bg-gray-950"- style={{- backgroundColor:- brand && brand.accentColor ? brand.accentColor : "rgb(3, 7, 18)",- }}- >- <VideoViewer- file={viewData.file!}- linkId={link.id}- documentId={documentData.id}- viewId={viewData.viewId}- documentName={documentData.name}- allowDownload={viewData.canDownload ?? link.allowDownload!}- screenshotProtectionEnabled={link.enableScreenshotProtection!}- versionNumber={documentData.documentVersionNumber}- brand={brand}- dataroomId={dataroom.id}- setDocumentData={setDocumentData}- isPreview={viewData.isPreview}- />- </div>- ) : viewData.pages && !documentData.isVertical ? (- <div- className="bg-gray-950"- style={{- backgroundColor:- brand && brand.accentColor ? brand.accentColor : "rgb(3, 7, 18)",- }}- >- <PagesHorizontalViewer- pages={viewData.pages}- viewId={viewData.viewId}- isPreview={viewData.isPreview}- linkId={link.id}- documentId={documentData.id}- documentName={documentData.name}- allowDownload={viewData.canDownload ?? link.allowDownload!}- feedbackEnabled={link.enableFeedback!}- screenshotProtectionEnabled={link.enableScreenshotProtection!}- screenShieldPercentage={link.screenShieldPercentage}- versionNumber={documentData.documentVersionNumber}- brand={brand}- dataroomId={dataroom.id}- setDocumentData={setDocumentData}- viewerEmail={data.email ?? verifiedEmail ?? userEmail ?? undefined}- watermarkConfig={- link.enableWatermark- ? (link.watermarkConfig as WatermarkConfig)- : null- }- ipAddress={viewData.ipAddress}- linkName={link.name ?? `Link #${link.id.slice(-5)}`}- />- </div>- ) : viewData.pages && documentData.isVertical ? (- <div- className="bg-gray-950"- style={{- backgroundColor:- brand && brand.accentColor ? brand.accentColor : "rgb(3, 7, 18)",- }}- >- <PagesVerticalViewer- pages={viewData.pages}- viewId={viewData.viewId}- isPreview={viewData.isPreview}- linkId={link.id}- documentId={documentData.id}- documentName={documentData.name}- allowDownload={viewData.canDownload ?? link.allowDownload!}- feedbackEnabled={link.enableFeedback!}- screenshotProtectionEnabled={link.enableScreenshotProtection!}- screenShieldPercentage={link.screenShieldPercentage}- versionNumber={documentData.documentVersionNumber}- brand={brand}- dataroomId={dataroom.id}- setDocumentData={setDocumentData}- viewerEmail={data.email ?? verifiedEmail ?? userEmail ?? undefined}- watermarkConfig={- link.enableWatermark- ? (link.watermarkConfig as WatermarkConfig)- : null- }- ipAddress={viewData.ipAddress}- linkName={link.name ?? `Link #${link.id.slice(-5)}`}- />- </div>- ) : null;- }-- if (submitted && !documentData) {+ if (submitted) {return (<div className="bg-gray-950"><DataroomViewer@@ -555,12 +247,8 @@ export default function DataroomView({viewId={viewData.viewId}isPreview={viewData.isPreview}linkId={link.id}- dataroomViewId={viewData.dataroomViewId!}dataroom={dataroom}allowDownload={link.allowDownload!}- setDocumentData={setDocumentData}- setViewType={setViewType}- setDataroomVerified={setDataroomVerified}folderId={folderId}setFolderId={setFolderId}/>diff --git a/components/view/dataroom/document-card.tsx b/components/view/dataroom/document-card.tsxindex 5fb27669..dbb41e5a 100644--- a/components/view/dataroom/document-card.tsx+++ b/components/view/dataroom/document-card.tsx@@ -1,11 +1,11 @@+import { useRouter } from "next/router";+import React from "react";import { useTheme } from "next-themes";import { fileIcon } from "@/lib/utils/get-file-icon";-import { TDocumentData, TSupportedDocumentSimpleType } from "./dataroom-view";-type DRDocument = {dataroomDocumentId: string;id: string;@@ -22,17 +22,34 @@ type DRDocument = {type DocumentsCardProps = {document: DRDocument;- setViewType: (type: "DOCUMENT_VIEW" | "DATAROOM_VIEW") => void;- setDocumentData: React.Dispatch<React.SetStateAction<TDocumentData | null>>;+ linkId: string;};-export default function DocumentCard({- document,- setViewType,- setDocumentData,-}: DocumentsCardProps) {++export default function DocumentCard({ document, linkId }: DocumentsCardProps) {const { theme, systemTheme } = useTheme();const isLight =theme === "light" || (theme === "system" && systemTheme === "light");+ const router = useRouter();+ const { previewToken, domain, slug } = router.query as {+ previewToken?: string;+ domain?: string;+ slug?: string;+ };++ const handleDocumentClick = (e: React.MouseEvent) => {+ e.preventDefault();+ // Open in new tab+ if (domain && slug) {+ window.open(`/${slug}/d/${document.dataroomDocumentId}`, "_blank");+ } else {+ window.open(+ `/view/${linkId}/d/${document.dataroomDocumentId}${+ previewToken ? `?previewToken=${previewToken}&preview=1` : ""+ }`,+ "_blank",+ );+ }+ };return (<>@@ -50,20 +67,7 @@ export default function DocumentCard({<div className="flex items-center"><h2 className="min-w-0 max-w-[300px] truncate text-sm font-semibold leading-6 text-foreground sm:max-w-lg"><button- onClick={() => {- setViewType("DOCUMENT_VIEW");- setDocumentData({- id: document.id,- name: document.name,- hasPages: document.versions[0].hasPages,- documentType: document.versions[0]- .type as TSupportedDocumentSimpleType,- documentVersionId: document.versions[0].id,- documentVersionNumber: document.versions[0].versionNumber,- downloadOnly: document.downloadOnly,- isVertical: document.versions[0].isVertical,- });- }}+ onClick={handleDocumentClick}className="w-full truncate"><span>{document.name}</span>diff --git a/components/view/document-view.tsx b/components/view/document-view.tsxindex 8063e4d3..3e77c365 100644--- a/components/view/document-view.tsx+++ b/components/view/document-view.tsx@@ -18,7 +18,7 @@ import { useAnalytics } from "@/lib/analytics";import { LinkWithDocument, NotionTheme, WatermarkConfig } from "@/lib/types";import EmailVerificationMessage from "./email-verification-form";-import ViewData from "./view-data";+import ViewData, { TViewDocumentData } from "./view-data";type RowData = { [key: string]: any };type SheetData = {@@ -281,6 +281,7 @@ export default function DocumentView({<ViewDatalink={link}viewData={viewData}+ document={document as unknown as TViewDocumentData}notionData={notionData}brand={brand}showPoweredByBanner={showPoweredByBanner}diff --git a/components/view/view-data.tsx b/components/view/view-data.tsxindex 48eb5d36..f5d80615 100644--- a/components/view/view-data.tsx+++ b/components/view/view-data.tsx@@ -1,14 +1,18 @@import dynamic from "next/dynamic";-import { Brand } from "@prisma/client";+import { Brand, Document, DocumentVersion } from "@prisma/client";import { ExtendedRecordMap } from "notion-types";import { NotionPage } from "@/components/NotionPage";import PDFViewer from "@/components/view/PDFViewer";-import PagesViewerNew from "@/components/view/PagesViewerNew";import { DEFAULT_DOCUMENT_VIEW_TYPE } from "@/components/view/document-view";-import { LinkWithDocument, NotionTheme, WatermarkConfig } from "@/lib/types";+import {+ LinkWithDataroomDocument,+ LinkWithDocument,+ NotionTheme,+ WatermarkConfig,+} from "@/lib/types";import AdvancedExcelViewer from "./viewer/advanced-excel-viewer";import DownloadOnlyViewer from "./viewer/download-only-viewer";@@ -22,18 +26,25 @@ const ExcelViewer = dynamic({ ssr: false },);+export type TViewDocumentData = Document & {+ versions: DocumentVersion[];+};+export default function ViewData({viewData,link,+ document,notionData,brand,showPoweredByBanner,showAccountCreationSlide,useAdvancedExcelViewer,viewerEmail,+ dataroomId,}: {viewData: DEFAULT_DOCUMENT_VIEW_TYPE;- link: LinkWithDocument;+ link: LinkWithDocument | LinkWithDataroomDocument;+ document: TViewDocumentData;notionData?: {rootNotionPageId: string | null;recordMap: ExtendedRecordMap | null;@@ -44,9 +55,8 @@ export default function ViewData({showAccountCreationSlide?: boolean;useAdvancedExcelViewer?: boolean;viewerEmail?: string;+ dataroomId?: string;}) {- const { document } = link;-return notionData?.recordMap ? (<NotionPagerecordMap={notionData.recordMap}@@ -59,6 +69,7 @@ export default function ViewData({brand={brand}theme={notionData.theme}screenshotProtectionEnabled={link.enableScreenshotProtection!}+ dataroomId={dataroomId}/>) : document.downloadOnly ? (<DownloadOnlyViewer@@ -71,6 +82,7 @@ export default function ViewData({brand={brand}documentName={document.name}isPreview={viewData.isPreview}+ dataroomId={dataroomId}/>) : viewData.fileType === "sheet" && viewData.sheetData ? (<ExcelViewer@@ -84,6 +96,7 @@ export default function ViewData({brand={brand}allowDownload={link.allowDownload!}screenshotProtectionEnabled={link.enableScreenshotProtection!}+ dataroomId={dataroomId}/>) : viewData.fileType === "sheet" && useAdvancedExcelViewer ? (<AdvancedExcelViewer@@ -96,6 +109,7 @@ export default function ViewData({file={viewData.file!}allowDownload={link.allowDownload!}brand={brand}+ dataroomId={dataroomId}/>) : viewData.fileType === "image" ? (<ImageViewer@@ -121,6 +135,7 @@ export default function ViewData({ipAddress={viewData.ipAddress}linkName={link.name ?? `Link #${link.id.slice(-5)}`}isPreview={viewData.isPreview}+ dataroomId={dataroomId}/>) : viewData.pages && !document.versions[0].isVertical ? (<PagesHorizontalViewer@@ -146,6 +161,7 @@ export default function ViewData({}ipAddress={viewData.ipAddress}linkName={link.name ?? `Link #${link.id.slice(-5)}`}+ dataroomId={dataroomId}/>) : viewData.pages && document.versions[0].isVertical ? (<PagesVerticalViewer@@ -171,6 +187,7 @@ export default function ViewData({}ipAddress={viewData.ipAddress}linkName={link.name ?? `Link #${link.id.slice(-5)}`}+ dataroomId={dataroomId}/>) : viewData.fileType === "video" ? (<VideoViewer@@ -178,12 +195,13 @@ export default function ViewData({linkId={link.id}viewId={viewData.viewId}documentId={document.id}- documentName={link.document?.name}+ documentName={document.name}allowDownload={link.allowDownload!}screenshotProtectionEnabled={link.enableScreenshotProtection!}versionNumber={document.versions[0].versionNumber}brand={brand}isPreview={viewData.isPreview}+ dataroomId={dataroomId}/>) : (<PDFViewer@@ -196,6 +214,7 @@ export default function ViewData({allowDownload={link.allowDownload}assistantEnabled={document.assistantEnabled}versionNumber={document.versions[0].versionNumber}+ dataroomId={dataroomId}/>);}diff --git a/components/visitors/dataroom-visitor-custom-fields.tsx b/components/visitors/dataroom-visitor-custom-fields.tsxindex 01c4d53e..23b379de 100644--- a/components/visitors/dataroom-visitor-custom-fields.tsx+++ b/components/visitors/dataroom-visitor-custom-fields.tsx@@ -24,8 +24,6 @@ export default function VisitorCustomFields({fetcher,);- console.log("customFieldResponse", customFieldResponse);-if (!customFieldResponse) return null;return (diff --git a/components/visitors/visitor-custom-fields.tsx b/components/visitors/visitor-custom-fields.tsxindex 297d1a70..760f7a84 100644--- a/components/visitors/visitor-custom-fields.tsx+++ b/components/visitors/visitor-custom-fields.tsx@@ -24,8 +24,6 @@ export default function VisitorCustomFields({fetcher,);- console.log("customFieldResponse", customFieldResponse);-if (!customFieldResponse) return null;return (diff --git a/lib/api/links/link-data.ts b/lib/api/links/link-data.tsindex 72624037..36486a2d 100644--- a/lib/api/links/link-data.ts+++ b/lib/api/links/link-data.ts@@ -116,6 +116,92 @@ export async function fetchDataroomLinkData({return { linkData, brand };}+export async function fetchDataroomDocumentLinkData({+ linkId,+ teamId,+ dataroomDocumentId,+ groupId,+}: {+ linkId: string;+ teamId: string;+ dataroomDocumentId: string;+ groupId?: string;+}) {+ if (groupId) {+ const groupPermissions = await prisma.viewerGroupAccessControls.findMany({+ where: {+ groupId,+ itemId: dataroomDocumentId,+ itemType: ItemType.DATAROOM_DOCUMENT,+ OR: [{ canView: true }, { canDownload: true }],+ },+ });++ // if it's a group link, we need to check if the document is in the group+ if (!groupPermissions || groupPermissions.length === 0) {+ throw new Error("Document not found in group");+ }+ }++ const linkData = await prisma.link.findUnique({+ where: { id: linkId, teamId, linkType: "DATAROOM_LINK" },+ select: {+ dataroom: {+ select: {+ id: true,+ name: true,+ documents: {+ where: { id: dataroomDocumentId },+ select: {+ id: true,+ updatedAt: true,+ orderIndex: true,+ document: {+ select: {+ id: true,+ name: true,+ advancedExcelEnabled: true,+ downloadOnly: true,+ versions: {+ where: { isPrimary: true },+ select: {+ id: true,+ versionNumber: true,+ type: true,+ hasPages: true,+ file: true,+ isVertical: true,+ },+ take: 1,+ },+ },+ },+ },+ },+ },+ },+ },+ });++ if (!linkData?.dataroom) {+ throw new Error("Dataroom not found");+ }++ const brand = await prisma.dataroomBrand.findFirst({+ where: {+ dataroomId: linkData.dataroom.id,+ },+ select: {+ logo: true,+ banner: true,+ brandColor: true,+ accentColor: true,+ },+ });++ return { linkData, brand };+}+export async function fetchDocumentLinkData({linkId,teamId,diff --git a/lib/auth/dataroom-auth.ts b/lib/auth/dataroom-auth.tsnew file mode 100644index 00000000..bc41fdaa--- /dev/null+++ b/lib/auth/dataroom-auth.ts@@ -0,0 +1,107 @@+import { NextApiRequest } from "next";++import crypto from "crypto";+import { z } from "zod";++import { redis } from "@/lib/redis";++import { getIpAddress } from "../utils/ip";++const COOKIE_EXPIRATION_TIME = 23 * 60 * 60 * 1000; // 23 hours++// Define the Zod schema for session data+export const DataroomSessionSchema = z.object({+ linkId: z.string(),+ dataroomId: z.string(),+ viewId: z.string(),+ viewerId: z.string().optional(),+ expiresAt: z.number(),+ ipAddress: z.string(),+});++// Generate TypeScript type from Zod schema+export type DataroomSession = z.infer<typeof DataroomSessionSchema>;++async function createDataroomSession(+ dataroomId: string,+ linkId: string,+ viewId: string,+ ipAddress: string,+ viewerId?: string,+): Promise<{ token: string; expiresAt: number }> {+ const sessionToken = crypto.randomBytes(32).toString("hex");+ const expiresAt = Date.now() + COOKIE_EXPIRATION_TIME;++ const sessionData: DataroomSession = {+ dataroomId,+ linkId,+ viewId,+ viewerId,+ expiresAt,+ ipAddress,+ };++ // Validate session data before storing+ DataroomSessionSchema.parse(sessionData);++ // Store session in Redis+ await redis.set(+ `dataroom_session:${sessionToken}`,+ JSON.stringify(sessionData),+ { pxat: expiresAt },+ );++ return {+ token: sessionToken,+ expiresAt,+ };+}++async function verifyDataroomSession(+ req: NextApiRequest,+ linkId: string,+ dataroomId: string,+): Promise<DataroomSession | null> {+ if (!dataroomId) return null;++ const sessionToken = req.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;+ }++ const ipAddress = getIpAddress(req.headers);++ if (ipAddress !== 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/auth/preview-auth.ts b/lib/auth/preview-auth.tsnew file mode 100644index 00000000..83f51dc9--- /dev/null+++ b/lib/auth/preview-auth.ts@@ -0,0 +1,86 @@+import crypto from "crypto";+import { z } from "zod";++import { redis } from "@/lib/redis";++export const PREVIEW_EXPIRATION_TIME = 20 * 60 * 1000; // 20 minutes++const ZPreviewSessionSchema = z.object({+ userId: z.string(),+ linkId: z.string(),+ expiresAt: z.number(),+});++type PreviewSession = z.infer<typeof ZPreviewSessionSchema>;++async function createPreviewSession(+ linkId: string,+ userId: string,+): Promise<{ token: string; expiresAt: number }> {+ const sessionToken = crypto.randomBytes(32).toString("hex");+ const expiresAt = Date.now() + PREVIEW_EXPIRATION_TIME;++ const sessionData: PreviewSession = {+ linkId,+ userId,+ expiresAt,+ };++ // Validate session data before storing+ ZPreviewSessionSchema.parse(sessionData);++ // Store session in Redis+ await redis.set(+ `preview_session:${sessionToken}`,+ JSON.stringify(sessionData),+ { pxat: expiresAt },+ );++ return {+ token: sessionToken,+ expiresAt,+ };+}++async function verifyPreviewSession(+ previewToken: string,+ userId: string,+ linkId: string,+): Promise<PreviewSession | null> {+ const sessionToken = previewToken;+ if (!sessionToken) return null;++ const session = await redis.get(`preview_session:${sessionToken}`);+ if (!session) return null;++ try {+ const sessionData = ZPreviewSessionSchema.parse(session);++ // Check if the session is for the correct user+ if (sessionData.userId !== userId) {+ await redis.del(`preview_session:${sessionToken}`);+ return null;+ }++ // Check if session is expired+ if (sessionData.expiresAt < Date.now()) {+ await redis.del(`preview_session:${sessionToken}`);+ return null;+ }++ // Check if the session is for the correct link and dataroom+ if (sessionData.linkId !== linkId) {+ await redis.del(`preview_session:${sessionToken}`);+ return null;+ }++ return sessionData;+ } catch (error) {+ console.error("Preview session verification error:", error);+ await redis.del(`preview_session:${sessionToken}`);+ return null;+ }+}++export { createPreviewSession, verifyPreviewSession };+export type { PreviewSession };diff --git a/lib/types.ts b/lib/types.tsindex 68f4cba9..c7bc0359 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -75,6 +75,34 @@ export interface LinkWithDocument extends Link {customFields: CustomField[];}+export interface LinkWithDataroomDocument extends Link {+ dataroomDocument: DataroomDocument & {+ document: Document & {+ versions: {+ id: string;+ versionNumber: number;+ type: string;+ hasPages: boolean;+ file: string;+ isVertical: boolean;+ }[];+ };+ };+ feedback: {+ id: string;+ data: {+ question: string;+ type: string;+ };+ } | null;+ agreement: Agreement | null;+ customFields: CustomField[];+ teamId: string;+ team: {+ plan: string;+ };+}+export interface LinkWithDataroom extends Link {dataroom: {id: string;diff --git a/pages/api/links/[id]/documents/[documentId].ts b/pages/api/links/[id]/documents/[documentId].tsnew file mode 100644index 00000000..6f044743--- /dev/null+++ b/pages/api/links/[id]/documents/[documentId].ts@@ -0,0 +1,127 @@+import { NextApiRequest, NextApiResponse } from "next";++import { DataroomBrand, LinkAudienceType } from "@prisma/client";++import { fetchDataroomDocumentLinkData } from "@/lib/api/links/link-data";+import { errorhandler } from "@/lib/errorHandler";+import prisma from "@/lib/prisma";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ if (req.method !== "GET") {+ res.setHeader("Allow", ["GET"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }++ const { id, documentId: dataroomDocumentId } = req.query as {+ id: string;+ documentId: string;+ };++ try {+ // First fetch the link and verify it's a dataroom link+ const link = await prisma.link.findUnique({+ where: { id, linkType: "DATAROOM_LINK" },+ select: {+ id: true,+ expiresAt: true,+ emailProtected: true,+ emailAuthenticated: true,+ allowDownload: true,+ enableFeedback: true,+ enableScreenshotProtection: true,+ screenShieldPercentage: true,+ password: true,+ isArchived: true,+ enableCustomMetatag: true,+ metaTitle: true,+ metaDescription: true,+ metaImage: true,+ metaFavicon: true,+ enableQuestion: true,+ linkType: true,+ feedback: {+ select: {+ id: true,+ data: true,+ },+ },+ enableAgreement: true,+ agreement: true,+ showBanner: true,+ enableWatermark: true,+ watermarkConfig: true,+ groupId: true,+ audienceType: true,+ dataroomId: true,+ teamId: true,+ team: {+ select: {+ plan: true,+ },+ },+ customFields: {+ select: {+ id: true,+ type: true,+ identifier: true,+ label: true,+ placeholder: true,+ required: true,+ disabled: true,+ orderIndex: true,+ },+ orderBy: {+ orderIndex: "asc",+ },+ },+ },+ });++ if (!link) {+ return res.status(404).json({ error: "Link not found" });+ }++ if (link.isArchived) {+ return res.status(404).json({ error: "Link is archived" });+ }++ let brand: Partial<DataroomBrand> | null = null;+ let linkData: any;++ const data = await fetchDataroomDocumentLinkData({+ linkId: id,+ teamId: link.teamId!,+ dataroomDocumentId: dataroomDocumentId,+ ...(link.audienceType === LinkAudienceType.GROUP &&+ link.groupId && {+ groupId: link.groupId,+ }),+ });++ console.log("data documents", data.linkData.dataroom?.documents[0]);++ linkData = data.linkData;+ brand = data.brand;++ const teamPlan = link.team?.plan || "free";+ const linkType = link.linkType;++ const returnLink = {+ ...link,+ dataroomDocument: linkData.dataroom?.documents[0],+ ...(teamPlan === "free" && {+ customFields: [], // reset custom fields for free plan+ enableAgreement: false,+ enableWatermark: false,+ }),+ };++ return res.status(200).json({ linkType, link: returnLink, brand });+ } catch (error) {+ console.error("Error fetching document:", error);+ errorhandler(error, res);+ }+}diff --git a/pages/api/links/[id]/preview.ts b/pages/api/links/[id]/preview.tsindex 84163b38..a4991550 100644--- a/pages/api/links/[id]/preview.ts+++ b/pages/api/links/[id]/preview.ts@@ -2,8 +2,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { getServerSession } from "next-auth/next";-import { newId } from "@/lib/id-helper";-import prisma from "@/lib/prisma";+import { createPreviewSession } from "@/lib/auth/preview-auth";import { CustomUser } from "@/lib/types";import { authOptions } from "../../auth/[...nextauth]";@@ -21,20 +20,12 @@ export default async function handle(const { id } = req.query as { id: string };- // Create a new preview token- const previewToken = newId("preview");- const expiresAt = new Date();- expiresAt.setMinutes(expiresAt.getMinutes() + 20); // previewToken expires in 20 minutes+ const previewSession = await createPreviewSession(+ id,+ (session.user as CustomUser).id,+ );- await prisma.verificationToken.create({- data: {- token: previewToken,- identifier: `preview:${id}:${(session.user as CustomUser).id}`,- expires: expiresAt,- },- });-- return res.status(200).json({ previewToken });+ return res.status(200).json({ previewToken: previewSession.token });} else {// We only allow POST requestsres.setHeader("Allow", ["POST"]);diff --git a/pages/api/links/domains/[...domainSlug].ts b/pages/api/links/domains/[...domainSlug].tsindex 889e71f8..6434c9f1 100644--- a/pages/api/links/domains/[...domainSlug].ts+++ b/pages/api/links/domains/[...domainSlug].ts@@ -2,6 +2,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { Brand, DataroomBrand, LinkAudienceType } from "@prisma/client";+import { fetchDataroomDocumentLinkData } from "@/lib/api/links/link-data";import {fetchDataroomLinkData,fetchDocumentLinkData,@@ -22,6 +23,7 @@ export default async function handle(const domain = domainSlug[0];const slug = domainSlug[1];+ const documentId = domainSlug[3];if (slug === "404") {return res.status(404).json({@@ -139,16 +141,30 @@ export default async function handle(linkData = data.linkData;brand = data.brand;} else if (linkType === "DATAROOM_LINK") {- const data = await fetchDataroomLinkData({- linkId: link.id,- teamId: link.teamId!,- ...(link.audienceType === LinkAudienceType.GROUP &&- link.groupId && {- groupId: link.groupId,- }),- });- linkData = data.linkData;- brand = data.brand;+ if (documentId) {+ const data = await fetchDataroomDocumentLinkData({+ linkId: link.id,+ teamId: link.teamId!,+ dataroomDocumentId: documentId,+ ...(link.audienceType === LinkAudienceType.GROUP &&+ link.groupId && {+ groupId: link.groupId,+ }),+ });+ linkData = data.linkData;+ brand = data.brand;+ } else {+ const data = await fetchDataroomLinkData({+ linkId: link.id,+ teamId: link.teamId!,+ ...(link.audienceType === LinkAudienceType.GROUP &&+ link.groupId && {+ groupId: link.groupId,+ }),+ });+ linkData = data.linkData;+ brand = data.brand;+ }}// remove document and domain from link@@ -169,6 +185,7 @@ export default async function handle(const returnLink = {...sanitizedLink,...linkData,+ dataroomDocument: linkData.dataroom?.documents[0] || undefined,};res.status(200).json({ linkType, link: returnLink, brand });diff --git a/pages/api/views-dataroom.ts b/pages/api/views-dataroom.tsindex 83980029..d6996f83 100644--- a/pages/api/views-dataroom.ts+++ b/pages/api/views-dataroom.ts@@ -8,6 +8,12 @@ import { parsePageId } from "notion-utils";import { hashToken } from "@/lib/api/auth/token";import sendNotification from "@/lib/api/notification-helper";import { recordVisit } from "@/lib/api/views/record-visit";+import {+ DataroomSession,+ createDataroomSession,+ verifyDataroomSession,+} from "@/lib/auth/dataroom-auth";+import { PreviewSession, verifyPreviewSession } from "@/lib/auth/preview-auth";import { sendOtpVerificationEmail } from "@/lib/emails/send-email-otp-verification";import { getFile } from "@/lib/files/get-file";import { newId } from "@/lib/id-helper";@@ -57,7 +63,7 @@ export default async function handle(} = req.body as {linkId: string;documentId: string | undefined;- dataroomId: string | undefined;+ dataroomId: string;userId: string | null;documentVersionId: string | undefined;documentName: string | undefined;@@ -70,6 +76,8 @@ export default async function handle(groupId?: string;};+ console.log("req.body", req.body);+const { email, password, name, hasConfirmedAgreement } = data as {email: string;password: string;@@ -105,6 +113,8 @@ export default async function handle(id: linkId,},select: {+ documentId: true,+ dataroomId: true,emailProtected: true,enableNotification: true,emailAuthenticated: true,@@ -112,6 +122,7 @@ export default async function handle(domainSlug: true,isArchived: true,slug: true,+ domainId: true,allowList: true,denyList: true,enableAgreement: true,@@ -146,349 +157,357 @@ export default async function handle(return;}- // Check if email is required for visiting the link- if (link.emailProtected) {- if (!email || email.trim() === "") {- res.status(400).json({ message: "Email is required." });- return;- }-- // validate email- if (!validateEmail(email)) {- res.status(400).json({ message: "Invalid email address." });- return;- }- }-- // Check if password is required for visiting the link- if (link.password) {- if (!password || password.trim() === "") {- res.status(400).json({ message: "Password is required." });- return;- }-- let isPasswordValid: boolean = false;- const textParts: string[] = link.password.split(":");- if (!textParts || textParts.length !== 2) {- isPasswordValid = await checkPassword(password, link.password);- } else {- const decryptedPassword = decryptEncrpytedPassword(link.password);- isPasswordValid = decryptedPassword === password;+ // Check if there's a valid preview session+ let previewSession: PreviewSession | null = null;+ let isPreview: boolean = false;+ if (previewToken) {+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res+ .status(401)+ .json({ message: "You need to be logged in to preview the link." });}+ previewSession = await verifyPreviewSession(+ previewToken,+ (session.user as CustomUser).id,+ linkId,+ );- if (!isPasswordValid) {- res.status(403).json({ message: "Invalid password." });+ console.log("previewSession", previewSession);+ if (!previewSession) {+ res.status(401).json({+ message: "Preview session expired or invalid. Request a new one.",+ resetPreview: true,+ });return;}+ isPreview = true;}- // Check if agreement is required for visiting the link- if (link.enableAgreement && !hasConfirmedAgreement) {- res.status(400).json({ message: "Agreement to NDA is required." });- return;+ let dataroomSession: DataroomSession | null = null;+ if (!isPreview) {+ dataroomSession = await verifyDataroomSession(req, linkId, dataroomId);}- // Check if email is allowed to visit the link- if (link.allowList && link.allowList.length > 0) {- // Extract the domain from the email address- const emailDomain = email.substring(email.lastIndexOf("@"));+ console.log("dataroomSession", dataroomSession);- // Determine if the email or its domain is allowed- const isAllowed = link.allowList.some((allowed) => {- return (- allowed === email ||- (allowed.startsWith("@") && emailDomain === allowed)- );- });+ let isEmailVerified: boolean = false;+ let hashedVerificationToken: string | null = null;+ // If there is no session, then we need to check if the link is protected and enforce the checks+ if (!dataroomSession && !isPreview) {+ // Check if email is required for visiting the link+ if (link.emailProtected) {+ if (!email || email.trim() === "") {+ res.status(400).json({ message: "Email is required." });+ return;+ }- // Deny access if the email is not allowed- if (!isAllowed) {- res.status(403).json({ message: "Unauthorized access" });- return;+ // validate email+ if (!validateEmail(email)) {+ res.status(400).json({ message: "Invalid email address." });+ return;+ }}- }- // Check if email is denied to visit the link- if (link.denyList && link.denyList.length > 0) {- // Extract the domain from the email address- const emailDomain = email.substring(email.lastIndexOf("@"));+ // Check if password is required for visiting the link+ if (link.password) {+ if (!password || password.trim() === "") {+ res.status(400).json({ message: "Password is required." });+ return;+ }- // Determine if the email or its domain is denied- const isDenied = link.denyList.some((denied) => {- return (- denied === email || (denied.startsWith("@") && emailDomain === denied)- );- });+ let isPasswordValid: boolean = false;+ const textParts: string[] = link.password.split(":");+ if (!textParts || textParts.length !== 2) {+ isPasswordValid = await checkPassword(password, link.password);+ } else {+ const decryptedPassword = decryptEncrpytedPassword(link.password);+ isPasswordValid = decryptedPassword === password;+ }- // Deny access if the email is denied- if (isDenied) {- res.status(403).json({ message: "Unauthorized access" });- return;+ if (!isPasswordValid) {+ res.status(403).json({ message: "Invalid password." });+ return;+ }}- }-- // Check if group is allowed to visit the link- if (link.audienceType === LinkAudienceType.GROUP && link.groupId) {- const group = await prisma.viewerGroup.findUnique({- where: { id: link.groupId },- select: {- members: { include: { viewer: { select: { email: true } } } },- domains: true,- allowAll: true,- },- });- if (!group) {- res.status(404).json({ message: "Group not found." });+ // Check if agreement is required for visiting the link+ if (link.enableAgreement && !hasConfirmedAgreement) {+ res.status(400).json({ message: "Agreement to NDA is required." });return;}- // Check if all emails are allowed- if (group.allowAll) {- // Allow access- } else {- // Check individual membership- const isMember = group.members.some(- (member) => member.viewer.email === email,- );-- // Extract domain from email+ // Check if email is allowed to visit the link+ if (link.allowList && link.allowList.length > 0) {+ // Extract the domain from the email addressconst emailDomain = email.substring(email.lastIndexOf("@"));- // Check domain access- const hasDomainAccess = group.domains.some(- (domain) => domain === emailDomain,- );- if (!isMember && !hasDomainAccess) {+ // Determine if the email or its domain is allowed+ const isAllowed = link.allowList.some((allowed) => {+ return (+ allowed === email ||+ (allowed.startsWith("@") && emailDomain === allowed)+ );+ });++ // Deny access if the email is not allowed+ if (!isAllowed) {res.status(403).json({ message: "Unauthorized access" });return;}}- }- // Request OTP Code for email verification if- // 1) email verification is required and- // 2) code is not provided or token not provided- if (link.emailAuthenticated && !code && !token && !dataroomVerified) {- const ipAddress = getIpAddress(req.headers);+ // Check if email is denied to visit the link+ if (link.denyList && link.denyList.length > 0) {+ // Extract the domain from the email address+ const emailDomain = email.substring(email.lastIndexOf("@"));- const { success } = await ratelimit(10, "1 m").limit(- `send-otp:${ipAddress}`,- );- if (!success) {- res- .status(429)- .json({ message: "Too many requests. Please try again later." });- return;+ // Determine if the email or its domain is denied+ const isDenied = link.denyList.some((denied) => {+ return (+ denied === email || (denied.startsWith("@") && emailDomain === denied)+ );+ });++ // Deny access if the email is denied+ if (isDenied) {+ res.status(403).json({ message: "Unauthorized access" });+ return;+ }}- await prisma.verificationToken.deleteMany({- where: {- identifier: `otp:${linkId}:${email}`,- },- });+ // Check if group is allowed to visit the link+ if (link.audienceType === LinkAudienceType.GROUP && link.groupId) {+ const group = await prisma.viewerGroup.findUnique({+ where: { id: link.groupId },+ select: {+ members: { include: { viewer: { select: { email: true } } } },+ domains: true,+ allowAll: true,+ },+ });- const otpCode = generateOTP();- const expiresAt = new Date();- expiresAt.setMinutes(expiresAt.getMinutes() + 10); // token expires at 10 minutes+ if (!group) {+ res.status(404).json({ message: "Group not found." });+ return;+ }- await prisma.verificationToken.create({- data: {- token: otpCode,- identifier: `otp:${linkId}:${email}`,- expires: expiresAt,- },- });+ // Check if all emails are allowed+ if (group.allowAll) {+ // Allow access+ } else {+ // Check individual membership+ const isMember = group.members.some(+ (member) => member.viewer.email === email,+ );- waitUntil(sendOtpVerificationEmail(email, otpCode, true));- res.status(200).json({- type: "email-verification",- message: "Verification email sent.",- });- return;- }+ // Extract domain from email+ const emailDomain = email.substring(email.lastIndexOf("@"));+ // Check domain access+ const hasDomainAccess = group.domains.some(+ (domain) => domain === emailDomain,+ );- let isEmailVerified: boolean = false;- let hashedVerificationToken: string | null = null;- if (link.emailAuthenticated && code && !dataroomVerified) {- const ipAddress = getIpAddress(req.headers);- const { success } = await ratelimit(10, "1 m").limit(- `verify-otp:${ipAddress}`,- );- if (!success) {- res- .status(429)- .json({ message: "Too many requests. Please try again later." });- return;+ if (!isMember && !hasDomainAccess) {+ res.status(403).json({ message: "Unauthorized access" });+ return;+ }+ }}- // Check if the OTP code is valid- const verification = await prisma.verificationToken.findUnique({- where: {- token: code,- identifier: `otp:${linkId}:${email}`,- },- });+ // Request OTP Code for email verification if+ // 1) email verification is required and+ // 2) code is not provided or token not provided+ if (link.emailAuthenticated && !code && !token && !dataroomVerified) {+ const ipAddress = getIpAddress(req.headers);- if (!verification) {- res.status(401).json({- message: "Unauthorized access. Request new access.",- resetVerification: true,- });- return;- }+ const { success } = await ratelimit(10, "1 m").limit(+ `send-otp:${ipAddress}`,+ );+ if (!success) {+ res+ .status(429)+ .json({ message: "Too many requests. Please try again later." });+ return;+ }- // Check the OTP code's expiration date- if (Date.now() > verification.expires.getTime()) {- await prisma.verificationToken.delete({+ await prisma.verificationToken.deleteMany({where: {- token: code,+ identifier: `otp:${linkId}:${email}`,},});- res.status(401).json({- message: "Access expired. Request new access.",- resetVerification: true,- });- return;- }- // delete the OTP code after verification- await prisma.verificationToken.delete({- where: {- token: code,- },- });+ const otpCode = generateOTP();+ const expiresAt = new Date();+ expiresAt.setMinutes(expiresAt.getMinutes() + 10); // token expires at 10 minutes- // Create a email verification token for repeat access- const token = newId("email");- hashedVerificationToken = hashToken(token);- const tokenExpiresAt = new Date();- tokenExpiresAt.setHours(tokenExpiresAt.getHours() + 23); // token expires at 23 hours- await prisma.verificationToken.create({- data: {- token: hashedVerificationToken,- identifier: `link-verification:${linkId}:${link.teamId}:${email}`,- expires: tokenExpiresAt,- },- });-- isEmailVerified = true;- }+ await prisma.verificationToken.create({+ data: {+ token: otpCode,+ identifier: `otp:${linkId}:${email}`,+ expires: expiresAt,+ },+ });- if (link.emailAuthenticated && token && !dataroomVerified) {- const ipAddress = getIpAddress(req.headers);- const { success } = await ratelimit(10, "1 m").limit(- `verify-email:${ipAddress}`,- );- if (!success) {- res- .status(429)- .json({ message: "Too many requests. Please try again later." });+ waitUntil(sendOtpVerificationEmail(email, otpCode, true));+ res.status(200).json({+ type: "email-verification",+ message: "Verification email sent.",+ });return;}- // Check if the long-term verification token is valid- const verification = await prisma.verificationToken.findUnique({- where: {- token: token,- identifier: `link-verification:${linkId}:${link.teamId}:${email}`,- },- });+ if (link.emailAuthenticated && code && !dataroomVerified) {+ const ipAddress = getIpAddress(req.headers);+ const { success } = await ratelimit(10, "1 m").limit(+ `verify-otp:${ipAddress}`,+ );+ if (!success) {+ res+ .status(429)+ .json({ message: "Too many requests. Please try again later." });+ return;+ }- if (!verification) {- res.status(401).json({- message: "Unauthorized access. Request new access.",- resetVerification: true,+ // Check if the OTP code is valid+ const verification = await prisma.verificationToken.findUnique({+ where: {+ token: code,+ identifier: `otp:${linkId}:${email}`,+ },});- return;- }- // Check the long-term verification token's expiration date- if (Date.now() > verification.expires.getTime()) {- // delete the long-term verification token after verification+ if (!verification) {+ res.status(401).json({+ message: "Unauthorized access. Request new access.",+ resetVerification: true,+ });+ return;+ }++ // Check the OTP code's expiration date+ if (Date.now() > verification.expires.getTime()) {+ await prisma.verificationToken.delete({+ where: {+ token: code,+ },+ });+ res.status(401).json({+ message: "Access expired. Request new access.",+ resetVerification: true,+ });+ return;+ }++ // delete the OTP code after verificationawait prisma.verificationToken.delete({where: {- token: token,+ token: code,},});- res.status(401).json({- message: "Access expired. Request new access.",- resetVerification: true,++ // Create a email verification token for repeat access+ const token = newId("email");+ hashedVerificationToken = hashToken(token);+ const tokenExpiresAt = new Date();+ tokenExpiresAt.setHours(tokenExpiresAt.getHours() + 23); // token expires at 23 hours+ await prisma.verificationToken.create({+ data: {+ token: hashedVerificationToken,+ identifier: `link-verification:${linkId}:${link.teamId}:${email}`,+ expires: tokenExpiresAt,+ },});- return;++ isEmailVerified = true;}- isEmailVerified = true;- }+ if (link.emailAuthenticated && token && !dataroomVerified) {+ const ipAddress = getIpAddress(req.headers);+ const { success } = await ratelimit(10, "1 m").limit(+ `verify-email:${ipAddress}`,+ );+ if (!success) {+ res+ .status(429)+ .json({ message: "Too many requests. Please try again later." });+ return;+ }- if (link.emailAuthenticated && dataroomVerified) {- isEmailVerified = true;- }+ // Check if the long-term verification token is valid+ const verification = await prisma.verificationToken.findUnique({+ where: {+ token: token,+ identifier: `link-verification:${linkId}:${link.teamId}:${email}`,+ },+ });- // Check if the view is a preview- let isPreview: boolean = false;- if (previewToken) {- const session = await getServerSession(req, res, authOptions);- if (!session) {- return res- .status(401)- .json({ message: "You need to be logged in to preview the link." });- }- const verification = await prisma.verificationToken.findUnique({- where: {- token: previewToken,- identifier: `preview:${linkId}:${(session.user as CustomUser).id}`,- },- });+ if (!verification) {+ res.status(401).json({+ message: "Unauthorized access. Request new access.",+ resetVerification: true,+ });+ return;+ }- if (!verification) {- res.status(401).json({- message: "Unauthorized access.",- });- return;- }+ // Check the long-term verification token's expiration date+ if (Date.now() > verification.expires.getTime()) {+ // delete the long-term verification token after verification+ await prisma.verificationToken.delete({+ where: {+ token: token,+ },+ });+ res.status(401).json({+ message: "Access expired. Request new access.",+ resetVerification: true,+ });+ return;+ }- // Check the token's expiration date- if (Date.now() > verification.expires.getTime()) {- res.status(401).json({ message: "Preview access expired" });- return;+ isEmailVerified = true;}- // TODO: delete previewToken- // delete the token after verification- // await prisma.verificationToken.delete({- // where: {- // token: previewToken,- // },- // });-- isPreview = true;+ if (link.emailAuthenticated && dataroomVerified) {+ isEmailVerified = true;+ }}- let viewer: { id: string } | null = null;- if (email && !isPreview) {- // find or create a viewer- console.time("find-viewer");- viewer = await prisma.viewer.findFirst({- where: {- email: email,- teamId: link.teamId!,- },- select: { id: true },- });- console.timeEnd("find-viewer");-- if (!viewer) {- console.time("create-viewer");- viewer = await prisma.viewer.create({- data: {- email: email,- verified: isEmailVerified,- teamId: link.teamId!,- },- select: { id: true },- });- console.timeEnd("create-viewer");+ let viewer: { id: string; email: string } | null = null;+ if (!isPreview) {+ if (!dataroomSession) {+ if (email) {+ // find or create a viewer+ console.time("find-viewer");+ viewer = await prisma.viewer.findFirst({+ where: {+ email: email,+ teamId: link.teamId!,+ },+ select: { id: true, email: true },+ });+ console.timeEnd("find-viewer");++ if (!viewer) {+ console.time("create-viewer");+ viewer = await prisma.viewer.create({+ data: {+ email: email,+ verified: isEmailVerified,+ teamId: link.teamId!,+ },+ select: { id: true, email: true },+ });+ console.timeEnd("create-viewer");+ }+ }+ } else {+ if (dataroomSession.viewerId) {+ viewer = await prisma.viewer.findUnique({+ where: { id: dataroomSession.viewerId, teamId: link.teamId! },+ select: { id: true, email: true },+ });+ }}}@@ -497,55 +516,60 @@ export default async function handle(// viewer?.id || undefined// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator+ // Common fields for the view object shared between DATAROOM_VIEW and DOCUMENT_VIEW+ const viewFields = {+ linkId: linkId,+ viewerEmail: viewer?.email ?? email,+ viewerName: name,+ verified: isEmailVerified,+ dataroomId: dataroomId,+ viewerId: viewer?.id ?? undefined,+ teamId: link.teamId,+ ...(link.enableAgreement &&+ link.agreementId &&+ hasConfirmedAgreement && {+ agreementResponse: {+ create: {+ agreementId: link.agreementId,+ },+ },+ }),+ ...(link.audienceType === LinkAudienceType.GROUP &&+ link.groupId && {+ groupId: link.groupId,+ }),+ ...(customFields &&+ link.customFields.length > 0 && {+ customFieldResponse: {+ create: {+ data: link.customFields.map((field) => ({+ identifier: field.identifier,+ label: field.label,+ response: customFields[field.identifier] || "",+ })),+ },+ },+ }),+ };+if (viewType === "DATAROOM_VIEW") {+ console.log("viewType is DATAROOM_VIEW");try {let newDataroomView: { id: string } | null = null;if (!isPreview) {- console.time("create-view");- newDataroomView = await prisma.view.create({- data: {- linkId: linkId,- viewerEmail: email,- viewerName: name,- verified: isEmailVerified,- dataroomId: dataroomId,- viewType: "DATAROOM_VIEW",- viewerId: viewer?.id ?? undefined,- teamId: link.teamId!,- ...(link.enableAgreement &&- link.agreementId &&- hasConfirmedAgreement && {- agreementResponse: {- create: {- agreementId: link.agreementId,- },- },- }),- ...(link.audienceType === LinkAudienceType.GROUP &&- link.groupId && {- groupId: link.groupId,- }),- ...(customFields &&- link.customFields.length > 0 && {- customFieldResponse: {- create: {- data: link.customFields.map((field) => ({- identifier: field.identifier,- label: field.label,- response: customFields[field.identifier] || "",- })),- },- },- }),- },- select: { id: true },- });- console.timeEnd("create-view");+ if (!dataroomSession) {+ console.time("create-view");+ newDataroomView = await prisma.view.create({+ data: { ...viewFields, viewType: "DATAROOM_VIEW" },+ select: { id: true },+ });+ console.timeEnd("create-view");- if (link.enableNotification) {- console.time("sendemail");- waitUntil(sendNotification({ viewId: newDataroomView.id }));- console.timeEnd("sendemail");+ if (link.enableNotification) {+ console.time("sendemail");+ waitUntil(sendNotification({ viewId: newDataroomView.id }));+ console.timeEnd("sendemail");+ }}}@@ -562,9 +586,37 @@ export default async function handle();}+ // Create a dataroom session token if a dataroom session doesn't exist yet+ if (!dataroomSession && !isPreview) {+ const newDataroomSession = await createDataroomSession(+ dataroomId,+ linkId,+ newDataroomView?.id!,+ getIpAddress(req.headers),+ viewer?.id,+ );++ let basePath = `/view/${linkId}`;+ const cookieId = `pm_drs_${linkId}`;+ let flagCookieId = `pm_drs_flag_${linkId}`;++ if (link.domainId) {+ basePath = `/${link.slug}`;+ flagCookieId = `pm_drs_flag_${link.slug}`;+ }++ res.setHeader("Set-Cookie", [+ `${cookieId}=${newDataroomSession?.token}; Path=/; Expires=${new Date(newDataroomSession?.expiresAt).toUTCString()}; HttpOnly; SameSite=Strict`,+ `${flagCookieId}=true; Path=${basePath}; Expires=${new Date(newDataroomSession?.expiresAt).toUTCString()}; SameSite=Strict`,+ ]);+ }++ const dataroomViewId =+ newDataroomView?.id ?? dataroomSession?.viewId ?? undefined;+const returnObject = {message: "Dataroom View recorded",- viewId: !isPreview && newDataroomView ? newDataroomView.id : undefined,+ viewId: dataroomViewId,isPreview: isPreview ? true : undefined,file: undefined,pages: undefined,@@ -585,33 +637,27 @@ export default async function handle(try {let newView: { id: string } | null = null;+ let dataroomView: { id: string } | null = null;if (!isPreview) {console.time("create-view");++ // if dataroomSession is not present, create a dataroom view first+ if (!dataroomSession) {+ console.log("no dataroom session present, creating new dataroom view");+ dataroomView = await prisma.view.create({+ data: { ...viewFields, viewType: "DATAROOM_VIEW" },+ select: { id: true },+ });+ }++ // create the document viewnewView = await prisma.view.create({data: {- linkId: linkId,- viewerEmail: email,- viewerName: name,+ ...viewFields,documentId: documentId,- verified: isEmailVerified,- dataroomViewId: dataroomViewId,- dataroomId: dataroomId,+ dataroomViewId:+ dataroomSession?.viewId ?? dataroomView?.id ?? dataroomViewId,viewType: "DOCUMENT_VIEW",- viewerId: viewer?.id ?? undefined,- teamId: link.teamId,- ...(link.enableAgreement &&- link.agreementId &&- hasConfirmedAgreement && {- agreementResponse: {- create: {- agreementId: link.agreementId,- },- },- }),- ...(link.audienceType === LinkAudienceType.GROUP &&- link.groupId && {- groupId: link.groupId,- }),},select: { id: true },});@@ -757,6 +803,30 @@ export default async function handle(}}+ // Create a dataroom session token if a dataroom session doesn't exist yet+ if (!dataroomSession && !isPreview) {+ const newDataroomSession = await createDataroomSession(+ dataroomId,+ linkId,+ dataroomView?.id!,+ getIpAddress(req.headers),+ viewer?.id,+ );++ let basePath = `/view/${linkId}`;+ const cookieId = `pm_drs_${linkId}`;+ let flagCookieId = `pm_drs_flag_${linkId}`;+ if (link.domainId) {+ basePath = `/${link.slug}`;+ flagCookieId = `pm_drs_flag_${link.slug}`;+ }++ res.setHeader("Set-Cookie", [+ `${cookieId}=${newDataroomSession?.token}; Path=/; Expires=${new Date(newDataroomSession?.expiresAt).toUTCString()}; HttpOnly; SameSite=Strict`,+ `${flagCookieId}=true; Path=${basePath}; Expires=${new Date(newDataroomSession?.expiresAt).toUTCString()}; SameSite=Strict`,+ ]);+ }+const returnObject = {message: "View recorded",viewId: !isPreview && newView ? newView.id : undefined,diff --git a/pages/api/views.ts b/pages/api/views.tsindex 78716075..ce0369b6 100644--- a/pages/api/views.ts+++ b/pages/api/views.ts@@ -6,6 +6,8 @@ import { getServerSession } from "next-auth/next";import { hashToken } from "@/lib/api/auth/token";import sendNotification from "@/lib/api/notification-helper";import { recordVisit } from "@/lib/api/views/record-visit";+import { verifyPreviewSession } from "@/lib/auth/preview-auth";+import { PreviewSession } from "@/lib/auth/preview-auth";import { sendOtpVerificationEmail } from "@/lib/emails/send-email-otp-verification";import { getFile } from "@/lib/files/get-file";import { newId } from "@/lib/id-helper";@@ -363,7 +365,8 @@ export default async function handle(isEmailVerified = true;}- // Check if the view is a preview+ // Check if there's a valid preview session+ let previewSession: PreviewSession | null = null;let isPreview: boolean = false;if (previewToken) {const session = await getServerSession(req, res, authOptions);@@ -372,34 +375,20 @@ export default async function handle(.status(401).json({ message: "You need to be logged in to preview the link." });}- const verification = await prisma.verificationToken.findUnique({- where: {- token: previewToken,- identifier: `preview:${linkId}:${(session.user as CustomUser).id}`,- },- });+ previewSession = await verifyPreviewSession(+ previewToken,+ (session.user as CustomUser).id,+ linkId,+ );- if (!verification) {+ console.log("previewSession", previewSession);+ if (!previewSession) {res.status(401).json({- message: "Unauthorized access.",+ message: "Preview session expired or invalid. Request a new one.",+ resetPreview: true,});return;}-- // Check the token's expiration date- if (Date.now() > verification.expires.getTime()) {- res.status(401).json({ message: "Preview access expired" });- return;- }-- // TODO: delete previewToken- // delete the token after verification- // await prisma.verificationToken.delete({- // where: {- // token: previewToken,- // },- // });-isPreview = true;}diff --git a/pages/view/[linkId]/d/[documentId].tsx b/pages/view/[linkId]/d/[documentId].tsxnew file mode 100644index 00000000..29c7a112--- /dev/null+++ b/pages/view/[linkId]/d/[documentId].tsx@@ -0,0 +1,273 @@+import { GetStaticPropsContext } from "next";+import { useRouter } from "next/router";++import React, { useEffect, useState } from "react";++import NotFound from "@/pages/404";+import { DataroomBrand } from "@prisma/client";+import Cookies from "js-cookie";+import { useSession } from "next-auth/react";+import { ExtendedRecordMap } from "notion-types";+import { parsePageId } from "notion-utils";++import LoadingSpinner from "@/components/ui/loading-spinner";+import CustomMetaTag from "@/components/view/custom-metatag";+import DataroomDocumentView from "@/components/view/dataroom/dataroom-document-view";++import notion from "@/lib/notion";+import { addSignedUrls } from "@/lib/notion/utils";+import { CustomUser, LinkWithDataroomDocument, NotionTheme } from "@/lib/types";++type DataroomDocumentLinkData = {+ linkType: "DATAROOM_LINK";+ link: LinkWithDataroomDocument;+ brand: DataroomBrand | null;+};++type DataroomDocumentProps = {+ linkData: DataroomDocumentLinkData;+ notionData: {+ rootNotionPageId: string | null;+ recordMap: ExtendedRecordMap | null;+ theme: NotionTheme | null;+ };+ meta: {+ enableCustomMetatag: boolean;+ metaTitle: string | null;+ metaDescription: string | null;+ metaImage: string | null;+ metaFavicon: string;+ metaUrl: string;+ };+ showPoweredByBanner: boolean;+ showAccountCreationSlide: boolean;+ useAdvancedExcelViewer: boolean;+ useCustomAccessForm: boolean;+};++export default function DataroomDocumentViewPage({+ linkData,+ notionData,+ meta,+ showPoweredByBanner,+ showAccountCreationSlide,+ useAdvancedExcelViewer,+ useCustomAccessForm,+}: DataroomDocumentProps) {+ const router = useRouter();+ const { data: session, status } = useSession();+ const [storedToken, setStoredToken] = useState<string | undefined>(undefined);+ const [storedEmail, setStoredEmail] = useState<string | undefined>(undefined);++ useEffect(() => {+ // Retrieve token from cookie on component mount+ const cookieToken = Cookies.get(`pm_drs_flag_${router.query.linkId}`);+ const storedEmail = window.localStorage.getItem("papermark.email");+ if (cookieToken) {+ setStoredToken(cookieToken);+ if (storedEmail) {+ setStoredEmail(storedEmail.toLowerCase());+ }+ }+ }, [router.query.linkId]);++ if (router.isFallback) {+ return (+ <div className="flex h-screen items-center justify-center bg-black">+ <LoadingSpinner className="h-20 w-20" />+ </div>+ );+ }++ const {+ email: verifiedEmail,+ d: disableEditEmail,+ previewToken,+ preview,+ } = router.query as {+ email: string;+ d: string;+ previewToken?: string;+ preview?: string;+ };+ const { link, brand } = linkData;++ // Render the document view for DATAROOM_LINK+ if (!linkData || status === "loading" || router.isFallback) {+ return (+ <>+ <CustomMetaTag+ favicon={meta.metaFavicon}+ enableBranding={meta.enableCustomMetatag ?? false}+ title={+ meta.metaTitle ??+ `${link?.dataroomDocument?.document?.name} | Powered by Papermark` ??+ "Document powered by Papermark"+ }+ description={meta.metaDescription ?? null}+ imageUrl={meta.metaImage ?? null}+ url={meta.metaUrl ?? ""}+ />+ <div className="flex h-screen items-center justify-center">+ <LoadingSpinner className="h-20 w-20" />+ </div>+ </>+ );+ }++ const {+ expiresAt,+ emailProtected,+ emailAuthenticated,+ password: linkPassword,+ enableAgreement,+ isArchived,+ } = link;++ const { email: userEmail, id: userId } = (session?.user as CustomUser) || {};++ // Check if the link is expired+ if (expiresAt && new Date(expiresAt) < new Date()) {+ return (+ <NotFound message="Sorry, the link you're looking for is expired." />+ );+ }++ // Check if the link is archived+ if (isArchived) {+ return (+ <NotFound message="Sorry, the link you're looking for is archived." />+ );+ }++ return (+ <>+ <CustomMetaTag+ favicon={meta.metaFavicon}+ enableBranding={meta.enableCustomMetatag ?? false}+ title={+ meta.metaTitle ??+ `${link?.dataroomDocument?.document?.name} | Powered by Papermark` ??+ "Dataroom powered by Papermark"+ }+ description={meta.metaDescription ?? null}+ imageUrl={meta.metaImage ?? null}+ url={meta.metaUrl ?? ""}+ />+ <DataroomDocumentView+ link={link}+ userEmail={verifiedEmail ?? storedEmail ?? userEmail}+ userId={userId}+ isProtected={!!(emailProtected || linkPassword || enableAgreement)}+ notionData={notionData}+ brand={brand}+ useAdvancedExcelViewer={useAdvancedExcelViewer}+ previewToken={previewToken}+ disableEditEmail={!!disableEditEmail}+ useCustomAccessForm={useCustomAccessForm}+ token={storedToken}+ verifiedEmail={verifiedEmail}+ preview={!!preview}+ />+ </>+ );+}++export async function getStaticProps(context: GetStaticPropsContext) {+ const { linkId, documentId } = context.params as {+ linkId: string;+ documentId: string;+ };++ try {+ const res = await fetch(+ `${process.env.NEXTAUTH_URL}/api/links/${linkId}/documents/${documentId}`,+ );+ const { linkType, link, brand } =+ (await res.json()) as DataroomDocumentLinkData;++ if (!link || !linkType) {+ return { notFound: true };+ }++ if (linkType !== "DATAROOM_LINK") {+ return { notFound: true };+ }++ let pageId = null;+ let recordMap = null;+ let theme = null;++ const { type, file, ...versionWithoutTypeAndFile } =+ link.dataroomDocument.document.versions[0];++ if (type === "notion") {+ theme = new URL(file).searchParams.get("mode");+ const notionPageId = parsePageId(file, { uuid: false });+ if (!notionPageId) {+ return {+ notFound: true,+ };+ }++ pageId = notionPageId;+ recordMap = await notion.getPage(pageId, { signFileUrls: false });+ // TODO: separately sign the file urls until PR merged and published; ref: https://github.com/NotionX/react-notion-x/issues/580#issuecomment-2542823817+ await addSignedUrls({ recordMap });+ }++ const { teamId, team, ...linkData } = link;++ const { advancedExcelEnabled, ...linkDocument } =+ linkData.dataroomDocument.document;++ return {+ props: {+ linkData: {+ linkType: "DATAROOM_LINK",+ link: {+ ...linkData,+ dataroomDocument: {+ ...linkData.dataroomDocument,+ document: {+ ...linkDocument,+ versions: [versionWithoutTypeAndFile],+ },+ },+ },+ brand,+ },+ notionData: {+ rootNotionPageId: null, // do not pass rootNotionPageId to the client+ recordMap,+ theme,+ },+ meta: {+ enableCustomMetatag: link.enableCustomMetatag || false,+ metaTitle: link.metaTitle,+ metaDescription: link.metaDescription,+ metaImage: link.metaImage,+ metaFavicon: link.metaFavicon ?? "/favicon.ico",+ metaUrl: `https://www.papermark.io/view/${linkId}`,+ },+ showPoweredByBanner: false,+ showAccountCreationSlide: false,+ useAdvancedExcelViewer: advancedExcelEnabled,+ useCustomAccessForm:+ teamId === "cm0154tiv0000lr2t6nr5c6kp" ||+ teamId === "clup33by90000oewh4rfvp2eg",+ },+ revalidate: brand || recordMap ? 10 : false,+ };+ } catch (error) {+ console.error("Fetching error:", error);+ return { notFound: true };+ }+}++export async function getStaticPaths() {+ return {+ paths: [],+ fallback: true,+ };+}diff --git a/pages/view/[linkId]/index.tsx b/pages/view/[linkId]/index.tsxindex b909b05f..301cc0a6 100644--- a/pages/view/[linkId]/index.tsx+++ b/pages/view/[linkId]/index.tsx@@ -222,7 +222,9 @@ export default function ViewPage({useEffect(() => {// Retrieve token from cookie on component mount- const cookieToken = Cookies.get("pm_vft");+ const cookieToken =+ Cookies.get("pm_vft") ||+ Cookies.get(`pm_drs_flag_${router.query.linkId}`);const storedEmail = window.localStorage.getItem("papermark.email");if (cookieToken) {setStoredToken(cookieToken);@@ -230,7 +232,7 @@ export default function ViewPage({setStoredEmail(storedEmail.toLowerCase());}}- }, []);+ }, [router.query.linkId]);if (router.isFallback) {return (@@ -244,10 +246,12 @@ export default function ViewPage({email: verifiedEmail,d: disableEditEmail,previewToken,+ preview,} = router.query as {email: string;d: string;previewToken?: string;+ preview?: string;};const { linkType, link, brand } = linkData;@@ -400,15 +404,15 @@ export default function ViewPage({<DataroomViewlink={link}userEmail={verifiedEmail ?? storedEmail ?? userEmail}+ verifiedEmail={verifiedEmail}userId={userId}isProtected={!!(emailProtected || linkPassword || enableAgreement)}brand={brand}- useAdvancedExcelViewer={useAdvancedExcelViewer}- previewToken={previewToken}disableEditEmail={!!disableEditEmail}useCustomAccessForm={useCustomAccessForm}token={storedToken}- verifiedEmail={verifiedEmail}+ previewToken={previewToken}+ preview={!!preview}/></>);diff --git a/pages/view/domains/[domain]/[slug]/d/[documentId].tsx b/pages/view/domains/[domain]/[slug]/d/[documentId].tsxnew file mode 100644index 00000000..94f4b9a2--- /dev/null+++ b/pages/view/domains/[domain]/[slug]/d/[documentId].tsx@@ -0,0 +1,281 @@+import { GetStaticPropsContext } from "next";+import { useRouter } from "next/router";++import React, { useEffect, useState } from "react";++import NotFound from "@/pages/404";+import { DataroomBrand } from "@prisma/client";+import Cookies from "js-cookie";+import { useSession } from "next-auth/react";+import { ExtendedRecordMap } from "notion-types";+import { parsePageId } from "notion-utils";++import LoadingSpinner from "@/components/ui/loading-spinner";+import CustomMetaTag from "@/components/view/custom-metatag";+import DataroomDocumentView from "@/components/view/dataroom/dataroom-document-view";++import notion from "@/lib/notion";+import { addSignedUrls } from "@/lib/notion/utils";+import { CustomUser, LinkWithDataroomDocument, NotionTheme } from "@/lib/types";++type DataroomDocumentLinkData = {+ linkType: "DATAROOM_LINK";+ link: LinkWithDataroomDocument;+ brand: DataroomBrand | null;+};++type DataroomDocumentProps = {+ linkData: DataroomDocumentLinkData;+ notionData: {+ rootNotionPageId: string | null;+ recordMap: ExtendedRecordMap | null;+ theme: NotionTheme | null;+ };+ meta: {+ enableCustomMetatag: boolean;+ metaTitle: string | null;+ metaDescription: string | null;+ metaImage: string | null;+ metaFavicon: string;+ metaUrl: string;+ };+ showPoweredByBanner: boolean;+ showAccountCreationSlide: boolean;+ useAdvancedExcelViewer: boolean;+ useCustomAccessForm: boolean;+};++export default function DataroomDocumentViewPage({+ linkData,+ notionData,+ meta,+ showPoweredByBanner,+ showAccountCreationSlide,+ useAdvancedExcelViewer,+ useCustomAccessForm,+}: DataroomDocumentProps) {+ const router = useRouter();+ const { data: session, status } = useSession();+ const [storedToken, setStoredToken] = useState<string | undefined>(undefined);+ const [storedEmail, setStoredEmail] = useState<string | undefined>(undefined);++ useEffect(() => {+ // Retrieve token from cookie on component mount+ const cookieToken =+ Cookies.get("pm_vft") || Cookies.get(`pm_drs_flag_${router.query.slug}`);+ const storedEmail = window.localStorage.getItem("papermark.email");+ if (cookieToken) {+ setStoredToken(cookieToken);+ if (storedEmail) {+ setStoredEmail(storedEmail.toLowerCase());+ }+ }+ }, [router.query.slug]);++ if (router.isFallback) {+ return (+ <div className="flex h-screen items-center justify-center bg-black">+ <LoadingSpinner className="h-20 w-20" />+ </div>+ );+ }++ const {+ email: verifiedEmail,+ d: disableEditEmail,+ previewToken,+ preview,+ } = router.query as {+ email: string;+ d: string;+ previewToken?: string;+ preview?: string;+ };+ const { link, brand } = linkData;++ // Render the document view for DATAROOM_LINK+ if (!linkData || status === "loading" || router.isFallback) {+ return (+ <>+ <CustomMetaTag+ favicon={meta.metaFavicon}+ enableBranding={meta.enableCustomMetatag ?? false}+ title={+ meta.metaTitle ??+ `${link?.dataroomDocument?.document?.name} | Powered by Papermark` ??+ "Document powered by Papermark"+ }+ description={meta.metaDescription ?? null}+ imageUrl={meta.metaImage ?? null}+ url={meta.metaUrl ?? ""}+ />+ <div className="flex h-screen items-center justify-center">+ <LoadingSpinner className="h-20 w-20" />+ </div>+ </>+ );+ }++ const {+ expiresAt,+ emailProtected,+ emailAuthenticated,+ password: linkPassword,+ enableAgreement,+ isArchived,+ } = link;++ const { email: userEmail, id: userId } = (session?.user as CustomUser) || {};++ // Check if the link is expired+ if (expiresAt && new Date(expiresAt) < new Date()) {+ return (+ <NotFound message="Sorry, the link you're looking for is expired." />+ );+ }++ // Check if the link is archived+ if (isArchived) {+ return (+ <NotFound message="Sorry, the link you're looking for is archived." />+ );+ }++ return (+ <>+ <CustomMetaTag+ favicon={meta.metaFavicon}+ enableBranding={meta.enableCustomMetatag ?? false}+ title={+ meta.metaTitle ??+ `${link?.dataroomDocument?.document?.name} | Powered by Papermark` ??+ "Dataroom powered by Papermark"+ }+ description={meta.metaDescription ?? null}+ imageUrl={meta.metaImage ?? null}+ url={meta.metaUrl ?? ""}+ />+ <DataroomDocumentView+ link={link}+ userEmail={verifiedEmail ?? storedEmail ?? userEmail}+ userId={userId}+ isProtected={!!(emailProtected || linkPassword || enableAgreement)}+ notionData={notionData}+ brand={brand}+ useAdvancedExcelViewer={useAdvancedExcelViewer}+ previewToken={previewToken}+ disableEditEmail={!!disableEditEmail}+ useCustomAccessForm={useCustomAccessForm}+ token={storedToken}+ verifiedEmail={verifiedEmail}+ preview={!!preview}+ />+ </>+ );+}++export async function getStaticProps(context: GetStaticPropsContext) {+ const { domain, slug, documentId } = context.params as {+ domain: string;+ slug: string;+ documentId: string;+ };++ try {+ const res = await fetch(+ `${process.env.NEXTAUTH_URL}/api/links/domains/${encodeURIComponent(+ domain,+ )}/${encodeURIComponent(slug)}/documents/${documentId}`,+ );+ if (!res.ok) {+ throw new Error(`Failed to fetch: ${res.status}`);+ }++ const { linkType, link, brand } =+ (await res.json()) as DataroomDocumentLinkData;++ if (!link || !linkType) {+ return { notFound: true };+ }++ if (linkType !== "DATAROOM_LINK") {+ return { notFound: true };+ }++ let pageId = null;+ let recordMap = null;+ let theme = null;++ const { type, file, ...versionWithoutTypeAndFile } =+ link.dataroomDocument.document.versions[0];++ if (type === "notion") {+ theme = new URL(file).searchParams.get("mode");+ const notionPageId = parsePageId(file, { uuid: false });+ if (!notionPageId) {+ return {+ notFound: true,+ };+ }++ pageId = notionPageId;+ recordMap = await notion.getPage(pageId, { signFileUrls: false });+ // TODO: separately sign the file urls until PR merged and published; ref: https://github.com/NotionX/react-notion-x/issues/580#issuecomment-2542823817+ await addSignedUrls({ recordMap });+ }++ const { teamId, team, ...linkData } = link;++ const { advancedExcelEnabled, ...linkDocument } =+ linkData.dataroomDocument.document;++ return {+ props: {+ linkData: {+ linkType: "DATAROOM_LINK",+ link: {+ ...linkData,+ dataroomDocument: {+ ...linkData.dataroomDocument,+ document: {+ ...linkDocument,+ versions: [versionWithoutTypeAndFile],+ },+ },+ },+ brand,+ },+ notionData: {+ rootNotionPageId: null, // do not pass rootNotionPageId to the client+ recordMap,+ theme,+ },+ meta: {+ enableCustomMetatag: link.enableCustomMetatag || false,+ metaTitle: link.metaTitle,+ metaDescription: link.metaDescription,+ metaImage: link.metaImage,+ metaFavicon: link.metaFavicon ?? "/favicon.ico",+ metaUrl: `https://${domain}/${slug}` || null,+ },+ showPoweredByBanner: false,+ showAccountCreationSlide: false,+ useAdvancedExcelViewer: advancedExcelEnabled,+ useCustomAccessForm:+ teamId === "cm0154tiv0000lr2t6nr5c6kp" ||+ teamId === "clup33by90000oewh4rfvp2eg",+ },+ revalidate: brand || recordMap ? 10 : false,+ };+ } catch (error) {+ console.error("Fetching error:", error);+ return { notFound: true };+ }+}++export async function getStaticPaths() {+ return {+ paths: [],+ fallback: true,+ };+}diff --git a/pages/view/domains/[domain]/[slug]/index.tsx b/pages/view/domains/[domain]/[slug]/index.tsxindex 48f69726..3bf87dee 100644--- a/pages/view/domains/[domain]/[slug]/index.tsx+++ b/pages/view/domains/[domain]/[slug]/index.tsx@@ -219,7 +219,8 @@ export default function ViewPage({useEffect(() => {// Retrieve token from cookie on component mount- const cookieToken = Cookies.get("pm_vft");+ const cookieToken =+ Cookies.get("pm_vft") || Cookies.get(`pm_drs_flag_${router.query.slug}`);const storedEmail = window.localStorage.getItem("papermark.email");if (cookieToken) {setStoredToken(cookieToken);@@ -227,7 +228,7 @@ export default function ViewPage({setStoredEmail(storedEmail.toLowerCase());}}- }, []);+ }, [router.query.slug]);if (router.isFallback) {return (