Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: Improve Magic Link Email Deliverability
Cursor Agentd9c3d373e141
diff --git a/app/(auth)/verify/page.tsx b/app/(auth)/verify/page.tsxindex d0016d81..42204d94 100644--- a/app/(auth)/verify/page.tsx+++ b/app/(auth)/verify/page.tsx@@ -3,6 +3,7 @@ import Link from "next/link";import NotFound from "@/pages/404";+import prisma from "@/lib/prisma";import { generateChecksum } from "@/lib/utils/generate-checksum";import { LogoCloud } from "@/components/shared/logo-cloud";@@ -42,30 +43,156 @@ export const metadata: Metadata = {},};-export default function VerifyPage({+// Validate legacy verification URL with checksum+const isValidVerificationUrl = (url: string, checksum: string): boolean => {+ try {+ const urlObj = new URL(url);+ if (urlObj.origin !== process.env.NEXTAUTH_URL) return false;+ const expectedChecksum = generateChecksum(url);+ return checksum === expectedChecksum;+ } catch {+ return false;+ }+};++// Look up magic link token from database+async function getMagicLinkToken(token: string) {+ try {+ const magicLinkToken = await prisma.magicLinkToken.findUnique({+ where: { token },+ });++ if (!magicLinkToken) {+ return null;+ }++ // Check if token has expired+ if (new Date() > magicLinkToken.expires) {+ // Clean up expired token+ await prisma.magicLinkToken.delete({+ where: { token },+ });+ return null;+ }++ return magicLinkToken;+ } catch (error) {+ console.error("Error fetching magic link token:", error);+ return null;+ }+}++export default async function VerifyPage({searchParams,}: {- searchParams: { verification_url?: string; checksum?: string };+ searchParams: {+ token?: string;+ verification_url?: string;+ checksum?: string;+ };}) {- const { verification_url, checksum } = searchParams;+ const { token, verification_url, checksum } = searchParams;- if (!verification_url || !checksum) {- return <NotFound />;- }+ let callbackUrl: string | null = null;+ let isExpired = false;- // Server-side validation- const isValidVerificationUrl = (url: string, checksum: string): boolean => {- try {- const urlObj = new URL(url);- if (urlObj.origin !== process.env.NEXTAUTH_URL) return false;- const expectedChecksum = generateChecksum(url);- return checksum === expectedChecksum;- } catch {- return false;+ // New flow: token-based verification+ if (token) {+ const magicLinkToken = await getMagicLinkToken(token);+ if (magicLinkToken) {+ callbackUrl = magicLinkToken.callbackUrl;+ } else {+ // Token not found or expired+ isExpired = true;}- };+ }+ // Legacy flow: verification_url with checksum (backward compatibility)+ else if (verification_url && checksum) {+ if (isValidVerificationUrl(verification_url, checksum)) {+ callbackUrl = verification_url;+ }+ }- if (!isValidVerificationUrl(verification_url, checksum)) {+ // If no valid callback URL found, show appropriate error+ if (!callbackUrl) {+ if (isExpired) {+ return (+ <div className="flex h-screen w-full flex-wrap">+ <div className="flex w-full justify-center bg-gray-50 md:w-1/2 lg:w-1/2">+ <div className="z-10 mx-5 mt-[calc(1vh)] h-fit w-full max-w-md overflow-hidden rounded-lg sm:mx-0 sm:mt-[calc(2vh)] md:mt-[calc(3vh)]">+ <div className="items-left flex flex-col space-y-3 px-4 py-6 pt-8 sm:px-12">+ <img+ src="/_static/papermark-logo.svg"+ alt="Papermark Logo"+ className="-mt-8 mb-36 h-7 w-auto self-start sm:mb-32 md:mb-48"+ />+ <span className="text-balance text-3xl font-semibold text-gray-900">+ Link Expired+ </span>+ <h3 className="text-balance text-sm text-gray-800">+ This login link has expired or has already been used.+ </h3>+ </div>+ <div className="flex flex-col gap-4 px-4 pt-8 sm:px-12">+ <div className="relative">+ <Link href="/login">+ <Button className="focus:shadow-outline w-full transform rounded bg-gray-800 px-4 py-2 text-white transition-colors duration-300 ease-in-out hover:bg-gray-900 focus:outline-none">+ Request a new link+ </Button>+ </Link>+ </div>+ </div>+ </div>+ </div>+ <div className="relative hidden w-full justify-center overflow-hidden bg-black md:flex md:w-1/2 lg:w-1/2">+ <div className="relative m-0 flex h-full min-h-[700px] w-full p-0">+ <div+ className="relative flex h-full w-full flex-col justify-between"+ id="features"+ >+ <div+ className="flex w-full flex-col items-center justify-center"+ style={{ height: "66.6666%" }}+ >+ <div className="mb-4 h-64 w-80">+ <img+ className="h-full w-full rounded-2xl object-cover shadow-2xl"+ src="/_static/testimonials/backtrace.jpeg"+ alt="Backtrace Capital"+ />+ </div>+ <div className="max-w-xl text-center">+ <blockquote className="text-balance font-normal leading-8 text-white sm:text-xl sm:leading-9">+ <p>+ "We raised our €30M Fund with Papermark Data Rooms.+ Love the customization, security and ease of use."+ </p>+ </blockquote>+ <figcaption className="mt-4">+ <div className="text-balance font-normal text-white">+ Michael Münnix+ </div>+ <div className="text-balance font-light text-gray-400">+ Partner, Backtrace Capital+ </div>+ </figcaption>+ </div>+ </div>+ <div+ className="absolute bottom-0 left-0 flex w-full flex-col items-center justify-center bg-white"+ style={{ height: "33.3333%" }}+ >+ <div className="mb-4 max-w-xl text-balance text-center font-semibold text-gray-900">+ Trusted by teams at+ </div>+ <LogoCloud />+ </div>+ </div>+ </div>+ </div>+ </div>+ );+ }return <NotFound />;}@@ -95,7 +222,7 @@ export default function VerifyPage({</div><div className="flex flex-col gap-4 px-4 pt-8 sm:px-12"><div className="relative">- <Link href={verification_url}>+ <Link href={callbackUrl}><Button className="focus:shadow-outline w-full transform rounded bg-gray-800 px-4 py-2 text-white transition-colors duration-300 ease-in-out hover:bg-gray-900 focus:outline-none">Verify email</Button>diff --git a/app/api/cron/cleanup-magic-link-tokens/route.ts b/app/api/cron/cleanup-magic-link-tokens/route.tsnew file mode 100644index 00000000..902f938c--- /dev/null+++ b/app/api/cron/cleanup-magic-link-tokens/route.ts@@ -0,0 +1,53 @@+import { NextResponse } from "next/server";++import { receiver } from "@/lib/cron";+import prisma from "@/lib/prisma";+import { log } from "@/lib/utils";++/**+ * Cron job to clean up expired magic link tokens.+ * Runs daily to remove tokens that have passed their expiration date.+ * This complements the lazy cleanup that happens when tokens are accessed.+ */++export const maxDuration = 60; // 1 minute should be plenty++export async function POST(req: Request) {+ const body = await req.json();++ if (process.env.VERCEL === "1") {+ const isValid = await receiver.verify({+ signature: req.headers.get("Upstash-Signature") || "",+ body: JSON.stringify(body),+ });+ if (!isValid) {+ return new Response("Unauthorized", { status: 401 });+ }+ }++ try {+ // Delete all expired magic link tokens+ const result = await prisma.magicLinkToken.deleteMany({+ where: {+ expires: {+ lt: new Date(),+ },+ },+ });++ console.log(+ `[Cleanup] Deleted ${result.count} expired magic link tokens`,+ );++ return NextResponse.json({+ success: true,+ deletedCount: result.count,+ });+ } catch (error) {+ await log({+ message: `Magic link token cleanup cron failed. \n\nError: ${(error as Error).message}`,+ type: "cron",+ });+ return NextResponse.json({ error: (error as Error).message });+ }+}diff --git a/components/emails/verification-link.tsx b/components/emails/verification-link.tsxindex 6269d889..e8b0cd4f 100644--- a/components/emails/verification-link.tsx+++ b/components/emails/verification-link.tsx@@ -15,15 +15,33 @@ import {import { Footer } from "./shared/footer";+const formatExpirationTime = (expiresAt: Date): string => {+ return expiresAt.toLocaleString("en-US", {+ weekday: "long",+ year: "numeric",+ month: "long",+ day: "numeric",+ hour: "numeric",+ minute: "2-digit",+ timeZoneName: "short",+ });+};+const VerificationLinkEmail = ({- url = "https://www.papermark.com",+ url = "https://app.papermark.com/verify?token=example",+ email = "[email protected]",+ expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000),}: {url: string;+ email?: string;+ expiresAt?: Date;}) => {+ const requestedAt = new Date();+return (<Html><Head />- <Preview>Your Papermark Login Link</Preview>+ <Preview>Your Papermark Login Link - Sign in to your account</Preview><Tailwind><Body className="mx-auto my-auto bg-white font-sans"><Container className="mx-auto my-10 max-w-[600px] rounded border border-solid border-neutral-200 px-10 py-5">@@ -33,29 +51,59 @@ const VerificationLinkEmail = ({</Text></Section><Heading className="mx-0 my-7 p-0 text-lg font-medium text-black">- Your Login Link+ Sign in to Papermark</Heading><Text className="text-sm leading-6 text-black">- Welcome to Papermark!+ Hi there,</Text><Text className="text-sm leading-6 text-black">- Please click the magic link below to sign in to your account.+ We received a request to sign in to your Papermark account+ associated with <strong>{email}</strong>. Click the button below+ to securely sign in.</Text>- <Section className="my-8">+ <Section className="my-8 text-center"><LinkclassName="rounded-lg bg-black px-6 py-3 text-center text-[12px] font-semibold text-white no-underline"href={url}>- Sign in+ Sign in to Papermark</Link></Section><Text className="text-sm leading-6 text-black">- or copy and paste this URL into your browser:+ Or copy and paste this URL into your browser:</Text><Text className="max-w-sm flex-wrap break-words font-medium text-purple-600 no-underline">- {url.replace(/^https?:\/\//, "")}+ {url}</Text>- <Footer />+ <Section className="mt-8 rounded-lg bg-neutral-50 p-4">+ <Text className="m-0 text-xs leading-5 text-neutral-600">+ <strong>Security Information:</strong>+ </Text>+ <Text className="m-0 mt-2 text-xs leading-5 text-neutral-600">+ • This link was requested on{" "}+ {requestedAt.toLocaleString("en-US", {+ weekday: "long",+ year: "numeric",+ month: "long",+ day: "numeric",+ hour: "numeric",+ minute: "2-digit",+ timeZoneName: "short",+ })}+ </Text>+ <Text className="m-0 mt-1 text-xs leading-5 text-neutral-600">+ • This link expires in 24 hours (+ {formatExpirationTime(expiresAt)})+ </Text>+ <Text className="m-0 mt-1 text-xs leading-5 text-neutral-600">+ • If you didn't request this link, you can safely ignore+ this email. Your account remains secure.+ </Text>+ </Section>+ <Footer+ withAddress={true}+ footerText="This is an automated security email from Papermark. If you have any questions, simply reply to this email."+ /></Container></Body></Tailwind>diff --git a/lib/emails/send-verification-request.ts b/lib/emails/send-verification-request.tsindex b283a95d..2804b772 100644--- a/lib/emails/send-verification-request.ts+++ b/lib/emails/send-verification-request.ts@@ -1,22 +1,46 @@+import { customAlphabet } from "nanoid";++import prisma from "@/lib/prisma";import { sendEmail } from "@/lib/resend";import LoginLink from "@/components/emails/verification-link";-import { generateChecksum } from "../utils/generate-checksum";+// Generate a secure 20-character token using alphanumeric characters+const generateMagicLinkToken = customAlphabet(+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",+ 20,+);export const sendVerificationRequestEmail = async (params: {email: string;url: string;}) => {const { url, email } = params;- const checksum = generateChecksum(url);- const verificationUrlParams = new URLSearchParams({- verification_url: url,- checksum,++ // Generate a short, unique token+ const token = generateMagicLinkToken();++ // Store the callback URL server-side with 24-hour expiration+ const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24 hours++ await prisma.magicLinkToken.create({+ data: {+ token,+ email,+ callbackUrl: url,+ expires: expiresAt,+ },+ });++ // Create simplified verification URL (under 100 characters)+ const verificationUrl = `${process.env.NEXTAUTH_URL}/verify?token=${token}`;++ const emailTemplate = LoginLink({+ url: verificationUrl,+ email,+ expiresAt,});- const verificationUrl = `${process.env.NEXTAUTH_URL}/verify?${verificationUrlParams}`;- const emailTemplate = LoginLink({ url: verificationUrl });try {await sendEmail({to: email as string,diff --git a/pages/api/auth/[...nextauth].ts b/pages/api/auth/[...nextauth].tsindex 0c3d79c0..57b1a7a9 100644--- a/pages/api/auth/[...nextauth].ts+++ b/pages/api/auth/[...nextauth].ts@@ -17,7 +17,6 @@ import hanko from "@/lib/hanko";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";import { log } from "@/lib/utils";-import { generateChecksum } from "@/lib/utils/generate-checksum";import { getIpAddress } from "@/lib/utils/ip";const VERCEL_DEPLOYMENT = !!process.env.VERCEL_URL;@@ -80,20 +79,13 @@ export const authOptions: NextAuthOptions = {finalUrl = urlObj.toString();}+ // In development, send the email but also log the URLif (process.env.NODE_ENV === "development") {- const checksum = generateChecksum(finalUrl);- const verificationUrlParams = new URLSearchParams({- verification_url: finalUrl,- checksum,+ await sendVerificationRequestEmail({+ url: finalUrl,+ email: identifier,});-- const baseUrl = hasValidNextAuthUrl- ? process.env.NEXTAUTH_URL- : getMainDomainUrl();-- const verificationUrl = `${baseUrl}/verify?${verificationUrlParams}`;- console.log("[Login URL]", verificationUrl);- return;+ console.log("[Login Email Sent] Check your inbox for:", identifier);} else {await sendVerificationRequestEmail({url: finalUrl,diff --git a/prisma/migrations/20260121000000_add_magic_link_token/migration.sql b/prisma/migrations/20260121000000_add_magic_link_token/migration.sqlnew file mode 100644index 00000000..8e7ed409--- /dev/null+++ b/prisma/migrations/20260121000000_add_magic_link_token/migration.sql@@ -0,0 +1,23 @@+-- CreateTable+CREATE TABLE "MagicLinkToken" (+ "id" TEXT NOT NULL,+ "token" TEXT NOT NULL,+ "email" TEXT NOT NULL,+ "callbackUrl" TEXT NOT NULL,+ "expires" TIMESTAMP(3) NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,++ CONSTRAINT "MagicLinkToken_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE UNIQUE INDEX "MagicLinkToken_token_key" ON "MagicLinkToken"("token");++-- CreateIndex+CREATE INDEX "MagicLinkToken_token_idx" ON "MagicLinkToken"("token");++-- CreateIndex+CREATE INDEX "MagicLinkToken_expires_idx" ON "MagicLinkToken"("expires");++-- CreateIndex+CREATE INDEX "MagicLinkToken_email_idx" ON "MagicLinkToken"("email");diff --git a/prisma/schema/schema.prisma b/prisma/schema/schema.prismaindex 785c95c1..28783061 100644--- a/prisma/schema/schema.prisma+++ b/prisma/schema/schema.prisma@@ -92,6 +92,19 @@ model VerificationToken {@@unique([identifier, token])}+model MagicLinkToken {+ id String @id @default(cuid())+ token String @unique // Short unique token for the simplified URL+ email String // The user's email address+ callbackUrl String @db.Text // The original NextAuth callback URL+ expires DateTime+ createdAt DateTime @default(now())++ @@index([token])+ @@index([expires])+ @@index([email])+}+model Domain {id String @id @default(cuid())slug String @unique