Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add otp email verification token
Marc Seitz8274270fa1c6
diff --git a/components/emails/otp-verification.tsx b/components/emails/otp-verification.tsxnew file mode 100644index 00000000..618248b3--- /dev/null+++ b/components/emails/otp-verification.tsx@@ -0,0 +1,64 @@+import React from "react";++import {+ Body,+ Container,+ Head,+ Heading,+ Hr,+ Html,+ Preview,+ Section,+ Tailwind,+ Text,+} from "@react-email/components";++export default function OtpEmailVerification({+ email = "[email protected]",+ code = "123456",+ isDataroom = false,+}: {+ email: string;+ code: string;+ isDataroom: boolean;+}) {+ return (+ <Html>+ <Head />+ <Preview>Your Email Verification Code</Preview>+ <Tailwind>+ <Body className="mx-auto my-auto bg-white font-sans">+ <Container className="mx-auto my-10 w-[465px] p-5">+ <Text className="mx-0 mb-8 mt-4 p-0 text-center text-2xl font-normal">+ <span className="font-bold tracking-tighter">Papermark</span>+ </Text>+ <Heading className="mx-0 my-7 p-0 text-center text-xl font-semibold text-black">+ Please confirm your email address+ </Heading>+ <Text className="mx-auto text-sm leading-6">+ Enter this code on the link verification page to view the{" "}+ {isDataroom ? "dataroom" : "document"}:+ </Text>+ <Section className="my-8">+ <div className="mx-auto w-fit rounded-xl px-6 py-3 text-center font-mono text-2xl font-semibold tracking-[0.25em]">+ {code}+ </div>+ </Section>+ <Text className="text-sm leading-6 text-black">+ This code expires in 10 minutes.+ </Text>+ <Hr />+ <Section className="mt-8 text-gray-400">+ <Text className="text-xs">+ This email was intended for{" "}+ <span className="text-black">{email}</span>. If you were not+ expecting this email, you can ignore this email. If you have any+ feedback or questions about this email, simply reply to it.+ </Text>+ </Section>+ </Container>+ </Body>+ </Tailwind>+ </Html>+ );+}diff --git a/components/ui/input-otp.tsx b/components/ui/input-otp.tsxnew file mode 100644index 00000000..5d9ee806--- /dev/null+++ b/components/ui/input-otp.tsx@@ -0,0 +1,71 @@+import * as React from "react";++import { OTPInput, OTPInputContext } from "input-otp";+import { Dot } from "lucide-react";++import { cn } from "@/lib/utils";++const InputOTP = React.forwardRef<+ React.ElementRef<typeof OTPInput>,+ React.ComponentPropsWithoutRef<typeof OTPInput>+>(({ className, containerClassName, ...props }, ref) => (+ <OTPInput+ ref={ref}+ data-1p-ignore+ containerClassName={cn(+ "flex items-center gap-2 has-[:disabled]:opacity-50",+ containerClassName,+ )}+ className={cn("disabled:cursor-not-allowed", className)}+ {...props}+ />+));+InputOTP.displayName = "InputOTP";++const InputOTPGroup = React.forwardRef<+ React.ElementRef<"div">,+ React.ComponentPropsWithoutRef<"div">+>(({ className, ...props }, ref) => (+ <div ref={ref} className={cn("flex items-center", className)} {...props} />+));+InputOTPGroup.displayName = "InputOTPGroup";++const InputOTPSlot = React.forwardRef<+ React.ElementRef<"div">,+ React.ComponentPropsWithoutRef<"div"> & { index: number }+>(({ index, className, ...props }, ref) => {+ const inputOTPContext = React.useContext(OTPInputContext);+ const { char, hasFakeCaret, isActive } = inputOTPContext.slots[index];++ return (+ <div+ ref={ref}+ className={cn(+ "relative flex h-10 w-10 items-center justify-center border-y border-r border-input text-sm text-white transition-all first:rounded-l-md first:border-l last:rounded-r-md",+ isActive && "z-10 text-white ring-2 ring-ring ring-offset-white",+ className,+ )}+ {...props}+ >+ {char}+ {hasFakeCaret && (+ <div className="pointer-events-none absolute inset-0 flex items-center justify-center">+ <div className="h-4 w-px animate-caret-blink bg-white duration-1000" />+ </div>+ )}+ </div>+ );+});+InputOTPSlot.displayName = "InputOTPSlot";++const InputOTPSeparator = React.forwardRef<+ React.ElementRef<"div">,+ React.ComponentPropsWithoutRef<"div">+>(({ ...props }, ref) => (+ <div ref={ref} role="separator" {...props}>+ <Dot />+ </div>+));+InputOTPSeparator.displayName = "InputOTPSeparator";++export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator };diff --git a/components/view/DataroomViewer.tsx b/components/view/DataroomViewer.tsxindex 8fce80b6..0825bc9a 100644--- a/components/view/DataroomViewer.tsx+++ b/components/view/DataroomViewer.tsx@@ -90,42 +90,12 @@ export default function DataroomViewer({setDataroomVerified: React.Dispatch<React.SetStateAction<boolean>>;isPreview?: boolean;}) {- const router = useRouter();const [folderId, setFolderId] = useState<string | null>(null);const { documents, folders } = dataroom as {documents: DataroomDocument[];folders: DataroomFolder[];};- useEffect(() => {- // Remove token and email query parameters on component mount- const removeQueryParams = () => {- const currentQuery = { ...router.query };-- if (!currentQuery.token && !currentQuery.email) return;-- setDataroomVerified(true);- delete currentQuery.token;- delete currentQuery.email;- delete currentQuery.domain;- delete currentQuery.slug;- delete currentQuery.linkId;-- const currentPath = router.asPath.split("?")[0];-- router.replace(- {- pathname: currentPath,- query: currentQuery,- },- undefined,- { shallow: true },- );- };-- removeQueryParams();- }, []); // Run once on mount-const breadcrumbFolders = useMemo(() => getParentFolders(folderId, folders),[folderId, folders],diff --git a/components/view/dataroom/dataroom-view.tsx b/components/view/dataroom/dataroom-view.tsxindex 149c74c7..98fcf7da 100644--- a/components/view/dataroom/dataroom-view.tsx+++ b/components/view/dataroom/dataroom-view.tsx@@ -71,6 +71,7 @@ export type DEFAULT_DOCUMENT_VIEW_TYPE = {ipAddress?: string;useAdvancedExcelViewer?: boolean;canDownload?: boolean;+ verificationToken?: string;};export default function DataroomView({@@ -127,6 +128,9 @@ export default function DataroomView({token ?? null,);+ const [code, setCode] = useState<string | null>(null);+ const [isInvalidCode, setIsInvalidCode] = useState<boolean>(false);+const [viewType, setViewType] = useState<"DOCUMENT_VIEW" | "DATAROOM_VIEW">("DATAROOM_VIEW",);@@ -147,8 +151,6 @@ export default function DataroomView({userId: userId ?? null,documentVersionId: documentData?.documentVersionId,hasPages: documentData?.hasPages,- token: verificationToken ?? null,- verifiedEmail: verifiedEmail ?? null,dataroomVerified: dataroomVerified,dataroomId: dataroom?.id,linkType: linkType,@@ -156,6 +158,9 @@ export default function DataroomView({viewType: viewType,useAdvancedExcelViewer,previewToken,+ code: code ?? undefined,+ token: verificationToken ?? undefined,+ verifiedEmail: verifiedEmail ?? undefined,}),});@@ -177,6 +182,7 @@ export default function DataroomView({ipAddress,useAdvancedExcelViewer,canDownload,+ verificationToken,} = fetchData as DEFAULT_DOCUMENT_VIEW_TYPE;plausible("dataroomViewed"); // track the eventanalytics.identify(@@ -190,6 +196,18 @@ export default function DataroomView({viewerId: viewId,viewerEmail: data.email ?? verifiedEmail ?? userEmail,});++ // set the verification token to the cookie+ if (verificationToken) {+ Cookies.set("pm_vft", verificationToken, {+ path: router.asPath.split("?")[0],+ expires: 1,+ sameSite: "strict",+ secure: true,+ });+ setCode(null);+ }+setViewData((prev) => ({viewId,dataroomViewId:@@ -206,6 +224,7 @@ export default function DataroomView({}));setSubmitted(true);setVerificationRequested(false);+ viewType === "DATAROOM_VIEW" && setDataroomVerified(true);setIsLoading(false);}} else {@@ -213,26 +232,13 @@ export default function DataroomView({toast.error(data.message);if (data.resetVerification) {- const currentQuery = { ...router.query };- delete currentQuery.token;- delete currentQuery.email;- delete currentQuery.domain;- delete currentQuery.slug;- delete currentQuery.linkId;-const currentPath = router.asPath.split("?")[0];- router.replace(- {- pathname: currentPath,- query: currentQuery,- },- undefined,- { shallow: true },- );-Cookies.remove("pm_vft", { path: currentPath });setVerificationToken(null);+ setCode(null);+ setIsInvalidCode(true);+ setDataroomVerified(false);}setIsLoading(false);}@@ -283,6 +289,10 @@ export default function DataroomView({onSubmitHandler={handleSubmit}data={data}isLoading={isLoading}+ code={code}+ setCode={setCode}+ isInvalidCode={isInvalidCode}+ setIsInvalidCode={setIsInvalidCode}/>);}diff --git a/components/view/document-view.tsx b/components/view/document-view.tsxindex 03a1d9fc..4b6aee10 100644--- a/components/view/document-view.tsx+++ b/components/view/document-view.tsx@@ -43,6 +43,7 @@ export type DEFAULT_DOCUMENT_VIEW_TYPE = {fileType?: string;isPreview?: boolean;ipAddress?: string;+ verificationToken?: string;};export default function DocumentView({@@ -104,6 +105,8 @@ export default function DocumentView({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);@@ -122,10 +125,11 @@ export default function DocumentView({userId: userId ?? null,documentVersionId: document.versions[0].id,hasPages: document.versions[0].hasPages,- token: verificationToken ?? null,- verifiedEmail: verifiedEmail ?? null,useAdvancedExcelViewer,previewToken,+ code: code ?? undefined,+ token: verificationToken ?? undefined,+ verifiedEmail: verifiedEmail ?? undefined,}),});@@ -144,6 +148,7 @@ export default function DocumentView({fileType,isPreview,ipAddress,+ verificationToken,} = fetchData as DEFAULT_DOCUMENT_VIEW_TYPE;plausible("documentViewed"); // track the eventanalytics.identify(@@ -156,6 +161,18 @@ export default function DocumentView({viewerId: viewId,viewerEmail: data.email ?? verifiedEmail ?? userEmail,});++ // set the verification token to the cookie+ if (verificationToken) {+ Cookies.set("pm_vft", verificationToken, {+ path: router.asPath.split("?")[0],+ expires: 1,+ sameSite: "strict",+ secure: true,+ });+ setCode(null);+ }+setViewData({viewId,file,@@ -174,26 +191,12 @@ export default function DocumentView({toast.error(data.message);if (data.resetVerification) {- const currentQuery = { ...router.query };- delete currentQuery.token;- delete currentQuery.email;- delete currentQuery.domain;- delete currentQuery.slug;- delete currentQuery.linkId;-const currentPath = router.asPath.split("?")[0];- router.replace(- {- pathname: currentPath,- query: currentQuery,- },- undefined,- { shallow: true },- );-Cookies.remove("pm_vft", { path: currentPath });setVerificationToken(null);+ setCode(null);+ setIsInvalidCode(true);}setIsLoading(false);}@@ -224,6 +227,10 @@ export default function DocumentView({onSubmitHandler={handleSubmit}data={data}isLoading={isLoading}+ code={code}+ setCode={setCode}+ isInvalidCode={isInvalidCode}+ setIsInvalidCode={setIsInvalidCode}/>);}diff --git a/components/view/email-verification-form.tsx b/components/view/email-verification-form.tsxindex b2fac372..0ba08297 100644--- a/components/view/email-verification-form.tsx+++ b/components/view/email-verification-form.tsx@@ -1,42 +1,126 @@+import { useEffect, useState } from "react";+import { Button } from "@/components/ui/button";+import {+ InputOTP,+ InputOTPGroup,+ InputOTPSlot,+} from "@/components/ui/input-otp";import { DEFAULT_ACCESS_FORM_TYPE } from "@/components/view/access-form";+import { useMediaQuery } from "@/lib/utils/use-media-query";++const REGEXP_ONLY_DIGITS = "^\\d+$";+export default function EmailVerificationMessage({onSubmitHandler,isLoading,data,+ code,+ setCode,+ isInvalidCode,+ setIsInvalidCode,}: {onSubmitHandler: React.FormEventHandler<HTMLFormElement>;data: DEFAULT_ACCESS_FORM_TYPE;isLoading: boolean;+ code: string | null;+ setCode: (code: string | null) => void;+ isInvalidCode: boolean;+ setIsInvalidCode: (invalidCode: boolean) => void;}) {+ const { isMobile } = useMediaQuery();+ const [isResendLoading, setIsResendLoading] = useState(false);+ const [delaySeconds, setDelaySeconds] = useState(60);++ useEffect(() => {+ if (delaySeconds > 0) {+ const interval = setInterval(+ () => setDelaySeconds(delaySeconds - 1),+ 1000,+ );++ return () => clearInterval(interval);+ }+ }, [delaySeconds]);+return (<><div className="flex h-screen flex-1 flex-col bg-black px-6 py-12 lg:px-8"><div className="sm:mx-auto sm:w-full sm:max-w-md"><h2 className="mt-10 text-2xl font-bold leading-9 tracking-tight text-white">- Please verify your email+ Verify your email address</h2><p className="text-pretty text-sm leading-6 text-white">- A verification link has been send to your email:{" "}- <span className="font-medium">{data.email}</span>+ Enter the six digit verification code sent to{" "}+ <strong className="font-medium" title={data.email ?? ""}>+ {data.email}+ </strong></p>- <form className="mt-10 space-y-4" onSubmit={onSubmitHandler}>+ <form onSubmit={onSubmitHandler}>+ <InputOTP+ maxLength={6}+ pattern={REGEXP_ONLY_DIGITS}+ autoFocus={!isMobile}+ value={code ?? ""}+ onChange={(code) => {+ setIsInvalidCode(false);+ setCode(code || null);+ }}+ containerClassName="my-6"+ >+ <InputOTPGroup>+ {[0, 1, 2, 3, 4, 5].map((index) => (+ <InputOTPSlot key={index} index={index} />+ ))}+ </InputOTPGroup>+ </InputOTP>++ {isInvalidCode && (+ <p className="mb-6 mt-2 text-sm text-red-500">+ Invalid code. Please try again.+ </p>+ )}++ <Button+ type="submit"+ disabled={!code || isLoading}+ loading={isLoading && !isResendLoading}+ className="bg-white text-black hover:bg-white/90"+ >+ {isLoading && !isResendLoading ? "Verifying..." : "Continue"}+ </Button>+ </form>++ <div className="mt-10 space-y-4"><div className="flex items-center">- <p className="text-sm text-gray-600">+ <p className="text-xs text-gray-600">Didn't receive the email?</p>{" "}<Button- type="submit"variant="link"size="sm"- className="text-sm font-normal text-gray-400"- loading={isLoading}+ className="text-xs font-normal text-gray-500"+ disabled={isLoading || delaySeconds > 0}+ onClick={(e) => {+ e.preventDefault();+ setIsResendLoading(true);+ setDelaySeconds(60);+ setCode(null);+ setIsInvalidCode(false);+ onSubmitHandler(+ e as unknown as React.FormEvent<HTMLFormElement>,+ );+ }}>- Resend Link+ {isResendLoading && !isLoading+ ? "Resending code..."+ : delaySeconds > 0+ ? `Resend Code (${delaySeconds}s)`+ : "Resend Code"}</Button></div>- </form>+ </div></div></div></>diff --git a/lib/emails/send-email-otp-verification.ts b/lib/emails/send-email-otp-verification.tsnew file mode 100644index 00000000..a8179fd4--- /dev/null+++ b/lib/emails/send-email-otp-verification.ts@@ -0,0 +1,26 @@+import OtpEmailVerification from "@/components/emails/otp-verification";++import { sendEmail } from "@/lib/resend";++export const sendOtpVerificationEmail = async (+ email: string,+ code: string,+ isDataroom: boolean = false,+) => {+ const emailTemplate = OtpEmailVerification({+ email,+ code,+ isDataroom,+ });+ try {+ await sendEmail({+ to: email,+ subject: `One-time passcode to access the ${isDataroom ? "dataroom" : "document"}`,+ react: emailTemplate,+ test: process.env.NODE_ENV === "development",+ verify: true,+ });+ } catch (e) {+ console.error(e);+ }+};diff --git a/lib/emails/send-email-verification.ts b/lib/emails/send-email-verification.tsindex d2a2d2ff..b32fb7a8 100644--- a/lib/emails/send-email-verification.ts+++ b/lib/emails/send-email-verification.ts@@ -15,7 +15,7 @@ export const sendVerificationEmail = async (try {await sendEmail({to: email,- subject: `Verify your email address to access the ${isDataroom ? "dataroom" : "document"}.`,+ subject: `Verify your email address to access the ${isDataroom ? "dataroom" : "document"}`,react: emailTemplate,test: process.env.NODE_ENV === "development",verify: true,diff --git a/lib/redis.ts b/lib/redis.tsindex 9145934f..94493be4 100644--- a/lib/redis.ts+++ b/lib/redis.ts@@ -1,3 +1,4 @@+import { Ratelimit } from "@upstash/ratelimit";import { Redis } from "@upstash/redis";export const redis = new Redis({@@ -9,3 +10,21 @@ export const lockerRedisClient = new Redis({url: process.env.UPSTASH_REDIS_REST_LOCKER_URL as string,token: process.env.UPSTASH_REDIS_REST_LOCKER_TOKEN as string,});++// Create a new ratelimiter, that allows 10 requests per 10 seconds by default+export const ratelimit = (+ requests: number = 10,+ seconds:+ | `${number} ms`+ | `${number} s`+ | `${number} m`+ | `${number} h`+ | `${number} d` = "10 s",+) => {+ return new Ratelimit({+ redis: redis,+ limiter: Ratelimit.slidingWindow(requests, seconds),+ analytics: true,+ prefix: "papermark",+ });+};diff --git a/lib/utils/generate-otp.ts b/lib/utils/generate-otp.tsnew file mode 100644index 00000000..46dd98c0--- /dev/null+++ b/lib/utils/generate-otp.ts@@ -0,0 +1,9 @@+export function generateOTP(): string {+ // Generate a random number between 0 and 999999+ const randomNumber = Math.floor(Math.random() * 1000000);++ // Pad the number with leading zeros if necessary to ensure it is always 6 digits+ const otp = randomNumber.toString().padStart(6, "0");++ return otp;+}diff --git a/package-lock.json b/package-lock.jsonindex 56d3ecb3..bba74243 100644--- a/package-lock.json+++ b/package-lock.json@@ -72,6 +72,7 @@"eslint-config-next": "^14.2.13","framer-motion": "^11.8.0","handlebars": "^4.7.8",+ "input-otp": "^1.2.4","js-cookie": "^3.0.5","lucide-react": "^0.446.0","mime-types": "^2.1.35",@@ -11296,6 +11297,15 @@"prop-types": "^15.8.1"}},+ "node_modules/input-otp": {+ "version": "1.2.4",+ "resolved": "https://registry.npmjs.org/input-otp/-/input-otp-1.2.4.tgz",+ "integrity": "sha512-md6rhmD+zmMnUh5crQNSQxq3keBRYvE3odbr4Qb9g2NWzQv9azi+t1a3X4TBTbh98fsGHgEEJlzbe1q860uGCA==",+ "peerDependencies": {+ "react": "^16.8 || ^17.0 || ^18.0",+ "react-dom": "^16.8 || ^17.0 || ^18.0"+ }+ },"node_modules/internal-slot": {"version": "1.0.7","resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.0.7.tgz",diff --git a/package.json b/package.jsonindex 515f7c5e..87b0a15c 100644--- a/package.json+++ b/package.json@@ -81,6 +81,7 @@"eslint-config-next": "^14.2.13","framer-motion": "^11.8.0","handlebars": "^4.7.8",+ "input-otp": "^1.2.4","js-cookie": "^3.0.5","lucide-react": "^0.446.0","mime-types": "^2.1.35",diff --git a/pages/api/views-dataroom.ts b/pages/api/views-dataroom.tsindex 2bda028b..927394e4 100644--- a/pages/api/views-dataroom.ts+++ b/pages/api/views-dataroom.ts@@ -7,14 +7,17 @@ import { parsePageId } from "notion-utils";import { hashToken } from "@/lib/api/auth/token";import sendNotification from "@/lib/api/notification-helper";+import { sendOtpVerificationEmail } from "@/lib/emails/send-email-otp-verification";import { sendVerificationEmail } from "@/lib/emails/send-email-verification";import { getFile } from "@/lib/files/get-file";import { newId } from "@/lib/id-helper";import notion from "@/lib/notion";import prisma from "@/lib/prisma";+import { ratelimit } from "@/lib/redis";import { parseSheet } from "@/lib/sheet";import { CustomUser, WatermarkConfigSchema } from "@/lib/types";import { checkPassword, decryptEncrpytedPassword, log } from "@/lib/utils";+import { generateOTP } from "@/lib/utils/generate-otp";import { getIpAddress } from "@/lib/utils/ip";import { authOptions } from "./auth/[...nextauth]";@@ -42,9 +45,7 @@ export default async function handle(documentVersionId,documentName,hasPages,- token,ownerId,- verifiedEmail,dataroomVerified,linkType,dataroomViewId,@@ -59,9 +60,7 @@ export default async function handle(documentVersionId: string | undefined;documentName: string | undefined;hasPages: boolean | undefined;- token: string | null;ownerId: string | null;- verifiedEmail: string | null;dataroomVerified: boolean | undefined;linkType: string;dataroomViewId?: string;@@ -86,6 +85,13 @@ export default async function handle(previewToken?: string;};+ // Email Verification Data+ const { code, token, verifiedEmail } = data as {+ code?: string;+ token?: string;+ verifiedEmail?: string;+ };+// Fetch the link to verify the settingsconst link = await prisma.link.findUnique({where: {@@ -222,34 +228,41 @@ export default async function handle(}}- // Check if email verification is required for visiting the link- if (link.emailAuthenticated && !token && !dataroomVerified) {- const token = newId("email");- const hashedToken = hashToken(token);- const expiresAt = new Date();- expiresAt.setHours(expiresAt.getHours() + 23); // token expires at 23 hours-+ // 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);+ const { success } = await ratelimit(2, "1 m").limit(+ `send-otp:${ipAddress}`,+ );+ if (!success) {+ res+ .status(429)+ .json({ message: "Too many requests. Please try again later." });+ return;+ }++ await prisma.verificationToken.deleteMany({+ where: {+ identifier: `otp:${linkId}:${hashToken(ipAddress)}:${email}`,+ },+ });++ const otpCode = generateOTP();+ const expiresAt = new Date();+ expiresAt.setMinutes(expiresAt.getMinutes() + 10); // token expires at 10 minutes+await prisma.verificationToken.create({data: {- token: hashedToken,- identifier: `${linkId}:${hashToken(ipAddress)}:${email}`,+ token: otpCode,+ identifier: `otp:${linkId}:${hashToken(ipAddress)}:${email}`,expires: expiresAt,},});- // set the default verification url- let verificationUrl: string =- `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${linkId}?token=${hashedToken}&email=${encodeURIComponent(email)}` +- (previewToken ? `&previewToken=${previewToken}` : "");-- if (link.domainSlug && link.slug) {- // if custom domain is enabled, use the custom domain- verificationUrl = `https://${link.domainSlug}/${link.slug}?token=${hashedToken}&email=${encodeURIComponent(email)}`;- }-- waitUntil(sendVerificationEmail(email, verificationUrl, true));+ waitUntil(sendOtpVerificationEmail(email, otpCode, true));res.status(200).json({type: "email-verification",message: "Verification email sent.",@@ -258,13 +271,24 @@ export default async function handle(}let isEmailVerified: boolean = false;- if (link.emailAuthenticated && token && !dataroomVerified) {- const hashedToken = token; // INFO: token is already hashed+ let hashedVerificationToken: string | null = null;+ if (link.emailAuthenticated && code && !dataroomVerified) {const ipAddress = getIpAddress(req.headers);+ const { success } = await ratelimit(2, "1 m").limit(+ `verify-otp:${ipAddress}`,+ );+ if (!success) {+ res+ .status(429)+ .json({ message: "Too many requests. Please try again later." });+ return;+ }++ // Check if the OTP code is validconst verification = await prisma.verificationToken.findUnique({where: {- token: hashedToken,- identifier: `${linkId}:${hashToken(ipAddress)}:${email}`,+ token: code,+ identifier: `otp:${linkId}:${hashToken(ipAddress)}:${email}`,},});@@ -276,18 +300,85 @@ export default async function handle(return;}- // Check the token's expiration date+ // Check the OTP code's expiration dateif (Date.now() > verification.expires.getTime()) {- res.status(401).json({ message: "Access expired" });+ await prisma.verificationToken.delete({+ where: {+ token: code,+ },+ });+ res.status(401).json({+ message: "Access expired. Request new access.",+ resetVerification: true,+ });return;}- // // delete the token after verification- // await prisma.verificationToken.delete({- // where: {- // token: hashedToken,- // },- // });+ // delete the OTP code after verification+ await prisma.verificationToken.delete({+ where: {+ token: code,+ },+ });++ // 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}:${hashToken(ipAddress)}:${email}`,+ expires: tokenExpiresAt,+ },+ });++ isEmailVerified = true;+ }++ if (link.emailAuthenticated && token && !dataroomVerified) {+ const ipAddress = getIpAddress(req.headers);+ const { success } = await ratelimit(5, "1 m").limit(+ `verify-email:${ipAddress}`,+ );+ if (!success) {+ res+ .status(429)+ .json({ message: "Too many requests. Please try again later." });+ return;+ }++ // Check if the long-term verification token is valid+ const verification = await prisma.verificationToken.findUnique({+ where: {+ token: token,+ identifier: `link-verification:${linkId}:${hashToken(ipAddress)}:${email}`,+ },+ });++ if (!verification) {+ res.status(401).json({+ message: "Unauthorized access. Request new access.",+ resetVerification: true,+ });+ 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;+ }isEmailVerified = true;}@@ -415,6 +506,7 @@ export default async function handle(file: undefined,pages: undefined,notionData: undefined,+ verificationToken: hashedVerificationToken,};return res.status(200).json(returnObject);diff --git a/pages/api/views.ts b/pages/api/views.tsindex e91d6712..645f8eca 100644--- a/pages/api/views.ts+++ b/pages/api/views.ts@@ -5,13 +5,15 @@ import { getServerSession } from "next-auth/next";import { hashToken } from "@/lib/api/auth/token";import sendNotification from "@/lib/api/notification-helper";-import { sendVerificationEmail } from "@/lib/emails/send-email-verification";+import { sendOtpVerificationEmail } from "@/lib/emails/send-email-otp-verification";import { getFile } from "@/lib/files/get-file";import { newId } from "@/lib/id-helper";import prisma from "@/lib/prisma";+import { ratelimit } from "@/lib/redis";import { parseSheet } from "@/lib/sheet";import { CustomUser, WatermarkConfigSchema } from "@/lib/types";import { checkPassword, decryptEncrpytedPassword, log } from "@/lib/utils";+import { generateOTP } from "@/lib/utils/generate-otp";import { getIpAddress } from "@/lib/utils/ip";import { authOptions } from "./auth/[...nextauth]";@@ -38,9 +40,7 @@ export default async function handle(documentVersionId,documentName,hasPages,- token,ownerId,- verifiedEmail,...data} = req.body as {linkId: string;@@ -49,9 +49,7 @@ export default async function handle(documentVersionId: string;documentName: string;hasPages: boolean;- token: string | null;ownerId: string;- verifiedEmail: string | null;};const { email, password, name, hasConfirmedAgreement } = data as {@@ -71,6 +69,13 @@ export default async function handle(previewToken?: string;};+ // Email Verification Data+ const { code, token, verifiedEmail } = data as {+ code?: string;+ token?: string;+ verifiedEmail?: string;+ };+// Fetch the link to verify the settingsconst link = await prisma.link.findUnique({where: {@@ -178,34 +183,41 @@ export default async function handle(}}- // Check if email verification is required for visiting the link- if (link.emailAuthenticated && !token) {- const token = newId("email");- const hashedToken = hashToken(token);- const expiresAt = new Date();- expiresAt.setHours(expiresAt.getHours() + 23); // token expires at 23 hours-+ // 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) {const ipAddress = getIpAddress(req.headers);+ const { success } = await ratelimit(2, "1 m").limit(+ `send-otp:${ipAddress}`,+ );+ if (!success) {+ res+ .status(429)+ .json({ message: "Too many requests. Please try again later." });+ return;+ }++ await prisma.verificationToken.deleteMany({+ where: {+ identifier: `otp:${linkId}:${hashToken(ipAddress)}:${email}`,+ },+ });++ const otpCode = generateOTP();+ const expiresAt = new Date();+ expiresAt.setMinutes(expiresAt.getMinutes() + 10); // token expires at 10 minutes+await prisma.verificationToken.create({data: {- token: hashedToken,- identifier: `${linkId}:${hashToken(ipAddress)}:${email}`,+ token: otpCode,+ identifier: `otp:${linkId}:${hashToken(ipAddress)}:${email}`,expires: expiresAt,},});- // set the default verification url- let verificationUrl: string =- `${process.env.NEXT_PUBLIC_MARKETING_URL}/view/${linkId}?token=${hashedToken}&email=${encodeURIComponent(email)}` +- (previewToken ? `&previewToken=${previewToken}` : "");-- if (link.domainSlug && link.slug && !previewToken) {- // if custom domain is enabled, use the custom domain- verificationUrl = `https://${link.domainSlug}/${link.slug}?token=${hashedToken}&email=${encodeURIComponent(email)}`;- }-- await sendVerificationEmail(email, verificationUrl);+ waitUntil(sendOtpVerificationEmail(email, otpCode));res.status(200).json({type: "email-verification",message: "Verification email sent.",@@ -214,13 +226,24 @@ export default async function handle(}let isEmailVerified: boolean = false;- if (link.emailAuthenticated && token) {- const hashedToken = token; // INFO: token is already hashed+ let hashedVerificationToken: string | null = null;+ if (link.emailAuthenticated && code) {const ipAddress = getIpAddress(req.headers);+ const { success } = await ratelimit(2, "1 m").limit(+ `verify-otp:${ipAddress}`,+ );+ if (!success) {+ res+ .status(429)+ .json({ message: "Too many requests. Please try again later." });+ return;+ }++ // Check if the OTP code is validconst verification = await prisma.verificationToken.findUnique({where: {- token: hashedToken,- identifier: `${linkId}:${hashToken(ipAddress)}:${email}`,+ token: code,+ identifier: `otp:${linkId}:${hashToken(ipAddress)}:${email}`,},});@@ -232,18 +255,85 @@ export default async function handle(return;}- // Check the token's expiration date+ // Check the OTP code's expiration dateif (Date.now() > verification.expires.getTime()) {- res.status(401).json({ message: "Access expired" });+ await prisma.verificationToken.delete({+ where: {+ token: code,+ },+ });+ res.status(401).json({+ message: "Access expired. Request new access.",+ resetVerification: true,+ });return;}- // // delete the token after verification- // await prisma.verificationToken.delete({- // where: {- // token: hashedToken,- // },- // });+ // delete the OTP code after verification+ await prisma.verificationToken.delete({+ where: {+ token: code,+ },+ });++ // 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}:${hashToken(ipAddress)}:${email}`,+ expires: tokenExpiresAt,+ },+ });++ isEmailVerified = true;+ }++ if (link.emailAuthenticated && token) {+ const ipAddress = getIpAddress(req.headers);+ const { success } = await ratelimit(5, "1 m").limit(+ `verify-email:${ipAddress}`,+ );+ if (!success) {+ res+ .status(429)+ .json({ message: "Too many requests. Please try again later." });+ return;+ }++ // Check if the long-term verification token is valid+ const verification = await prisma.verificationToken.findUnique({+ where: {+ token: token,+ identifier: `link-verification:${linkId}:${hashToken(ipAddress)}:${email}`,+ },+ });++ if (!verification) {+ res.status(401).json({+ message: "Unauthorized access. Request new access.",+ resetVerification: true,+ });+ 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;+ }isEmailVerified = true;}@@ -426,6 +516,7 @@ export default async function handle()? getIpAddress(req.headers): undefined,+ verificationToken: hashedVerificationToken ?? undefined,};return res.status(200).json(returnObject);diff --git a/pages/view/[linkId]/index.tsx b/pages/view/[linkId]/index.tsxindex 59537827..1ee3b34c 100644--- a/pages/view/[linkId]/index.tsx+++ b/pages/view/[linkId]/index.tsx@@ -218,21 +218,6 @@ export default function ViewPage({}}, []);- useEffect(() => {- const { token } = router.query as { token?: string };- // Store token in cookie when it's available from the query- if (token) {- // set the cookie to expire in 24 hours- Cookies.set("pm_vft", token, {- path: router.asPath.split("?")[0],- expires: 1,- sameSite: "strict",- secure: true,- });- setStoredToken(token);- }- }, [router.query]);-if (router.isFallback) {return (<div className="flex h-screen items-center justify-center bg-black">@@ -242,12 +227,10 @@ export default function ViewPage({}const {- token,email: verifiedEmail,d: disableEditEmail,previewToken,} = router.query as {- token: string;email: string;d: string;previewToken?: string;@@ -330,7 +313,7 @@ export default function ViewPage({previewToken={previewToken}disableEditEmail={!!disableEditEmail}useCustomAccessForm={useCustomAccessForm}- token={storedToken ?? token}+ token={storedToken}verifiedEmail={verifiedEmail}/></>@@ -410,7 +393,7 @@ export default function ViewPage({previewToken={previewToken}disableEditEmail={!!disableEditEmail}useCustomAccessForm={useCustomAccessForm}- token={storedToken ?? token}+ token={storedToken}verifiedEmail={verifiedEmail}/></>diff --git a/pages/view/domains/[domain]/[slug]/index.tsx b/pages/view/domains/[domain]/[slug]/index.tsxindex 97463ece..4ea5a708 100644--- a/pages/view/domains/[domain]/[slug]/index.tsx+++ b/pages/view/domains/[domain]/[slug]/index.tsx@@ -219,21 +219,6 @@ export default function ViewPage({}}, []);- useEffect(() => {- const { token } = router.query as { token?: string };- // Store token in cookie when it's available from the query- if (token) {- // set the cookie to expire in 24 hours- Cookies.set("pm_vft", token, {- path: router.asPath.split("?")[0],- expires: 1,- sameSite: "strict",- secure: true,- });- setStoredToken(token);- }- }, [router.query]);-if (router.isFallback) {return (<div className="flex h-screen items-center justify-center bg-black">@@ -243,12 +228,10 @@ export default function ViewPage({}const {- token,email: verifiedEmail,d: disableEditEmail,previewToken,} = router.query as {- token: string;email: string;d: string;previewToken?: string;@@ -329,7 +312,7 @@ export default function ViewPage({previewToken={previewToken}disableEditEmail={!!disableEditEmail}useCustomAccessForm={useCustomAccessForm}- token={storedToken ?? token}+ token={storedToken}verifiedEmail={verifiedEmail}/></>@@ -409,7 +392,7 @@ export default function ViewPage({previewToken={previewToken}disableEditEmail={!!disableEditEmail}useCustomAccessForm={useCustomAccessForm}- token={storedToken ?? token}+ token={storedToken}verifiedEmail={verifiedEmail}/></>diff --git a/tailwind.config.js b/tailwind.config.jsindex 55903688..f9f410ca 100644--- a/tailwind.config.js+++ b/tailwind.config.js@@ -187,6 +187,11 @@ module.exports = {from: { height: "var(--radix-accordion-content-height)" },to: { height: "0" },},+ // input-otp+ "caret-blink": {+ "0%,70%,100%": { opacity: "1" },+ "20%,50%": { opacity: "0" },+ },},gridTemplateColumns: {16: "repeat(16, minmax(0, 1fr))",@@ -201,6 +206,8 @@ module.exports = {flyEmoji: "flyEmoji 1s forwards","accordion-down": "accordion-down 0.2s ease-out","accordion-up": "accordion-up 0.2s ease-out",+ // input-otp+ "caret-blink": "caret-blink 1.25s ease-out infinite",},},},