Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add email verification route
Marc Seitzfb86f0acc11d
diff --git a/app/(auth)/auth/email/[[...params]]/page-client.tsx b/app/(auth)/auth/email/[[...params]]/page-client.tsxnew file mode 100644index 00000000..3d9dcf01--- /dev/null+++ b/app/(auth)/auth/email/[[...params]]/page-client.tsx@@ -0,0 +1,335 @@+"use client";++import Link from "next/link";+import { useRouter } from "next/navigation";++import { useCallback, useEffect, useState } from "react";++import { LogoCloud } from "@/components/shared/logo-cloud";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";++interface EmailVerificationClientProps {+ email?: string;+ code?: string;+ uuid?: string;+ autoVerify?: boolean;+}++export default function EmailVerificationClient({+ email: initialEmail,+ code: initialCode,+ uuid,+ autoVerify = false,+}: EmailVerificationClientProps) {+ const router = useRouter();+ const [email, setEmail] = useState(initialEmail || "");+ const [code, setCode] = useState("");+ const [isLoading, setIsLoading] = useState(autoVerify);+ const [error, setError] = useState<string | null>(null);+ const [isExpired, setIsExpired] = useState(false);++ // Auto-verify when coming from email link+ const verifyWithLink = useCallback(async () => {+ if (!uuid || !initialCode || !initialEmail) return;++ setIsLoading(true);+ setError(null);++ try {+ const response = await fetch(+ `/api/auth/verify-code?uuid=${encodeURIComponent(uuid)}`,+ );+ const data = await response.json();++ if (!response.ok) {+ if (response.status === 410 || data.error?.includes("expired")) {+ setIsExpired(true);+ setError("This code has expired or is invalid.");+ } else if (response.status === 429) {+ setError(+ data.error || "Too many attempts. Please wait before trying again.",+ );+ } else {+ setError(data.error || "Verification failed. Please try again.");+ }+ setIsLoading(false);+ return;+ }++ // Redirect to the callback URL+ if (data.callbackUrl) {+ router.push(data.callbackUrl);+ }+ } catch (err) {+ setError("An error occurred. Please try again.");+ setIsLoading(false);+ }+ }, [uuid, initialCode, initialEmail, router]);++ useEffect(() => {+ if (autoVerify) {+ verifyWithLink();+ }+ }, [autoVerify, verifyWithLink]);++ // Manual code verification+ const handleSubmit = async (e: React.FormEvent) => {+ e.preventDefault();+ setIsLoading(true);+ setError(null);++ try {+ const response = await fetch("/api/auth/verify-code", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ email: email.trim().toLowerCase(),+ code: code.trim().toUpperCase(),+ }),+ });++ const data = await response.json();++ if (!response.ok) {+ if (response.status === 410 || data.error?.includes("expired")) {+ setIsExpired(true);+ setError("This code has expired or is invalid.");+ } else if (response.status === 429) {+ setError(+ data.error || "Too many attempts. Please wait before trying again.",+ );+ } else {+ setError(data.error || "Verification failed. Please try again.");+ }+ setIsLoading(false);+ return;+ }++ // Redirect to the callback URL+ if (data.callbackUrl) {+ router.push(data.callbackUrl);+ }+ } catch (err) {+ setError("An error occurred. Please try again.");+ setIsLoading(false);+ }+ };++ // Show expired state+ 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">+ Code Expired+ </span>+ <h3 className="text-balance text-sm text-gray-800">+ This login code has expired or has already been used.+ </h3>+ </div>+ <div className="flex flex-col gap-4 px-4 pt-8 sm:px-12">+ <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 code+ </Button>+ </Link>+ </div>+ </div>+ </div>+ <TestimonialSection />+ </div>+ );+ }++ return (+ <div className="flex h-screen w-full flex-wrap">+ {/* Left part */}+ <div className="flex w-full justify-center bg-gray-50 md:w-1/2 lg:w-1/2">+ <div+ className="absolute inset-x-0 top-10 -z-10 flex transform-gpu justify-center overflow-hidden blur-3xl"+ aria-hidden="true"+ ></div>+ <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"+ />+ <Link href="/">+ <span className="text-balance text-3xl font-semibold text-gray-900">+ {autoVerify && isLoading+ ? "Verifying..."+ : "Enter verification code"}+ </span>+ </Link>+ <h3 className="text-balance text-sm text-gray-800">+ {autoVerify && isLoading+ ? "Please wait while we verify your login."+ : "Enter the code sent to your email."}+ </h3>+ </div>++ {/* Loading state for auto-verify */}+ {autoVerify && isLoading && (+ <div className="flex flex-col gap-4 px-4 pt-8 sm:px-12">+ <div className="flex items-center justify-center py-8">+ <div className="h-8 w-8 animate-spin rounded-full border-b-2 border-gray-800"></div>+ </div>+ </div>+ )}++ {/* Manual entry form */}+ {(!autoVerify || !isLoading) && (+ <form+ className="flex flex-col gap-4 px-4 pt-8 sm:px-12"+ onSubmit={handleSubmit}+ >+ <div className="space-y-2">+ <Label htmlFor="email">Email</Label>+ <Input+ id="email"+ placeholder="[email protected]"+ type="email"+ autoCapitalize="none"+ autoComplete="email"+ autoCorrect="off"+ disabled={isLoading || !!initialEmail}+ value={email}+ onChange={(e) => setEmail(e.target.value)}+ className="flex h-10 w-full rounded-md border-0 bg-background bg-white px-3 py-2 text-sm text-gray-900 ring-1 ring-gray-200 transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"+ />+ </div>+ <div className="space-y-2">+ <Label htmlFor="code">Verification Code</Label>+ <Input+ id="code"+ placeholder="Enter 10-character code"+ type="text"+ autoCapitalize="characters"+ autoComplete="one-time-code"+ autoCorrect="off"+ disabled={isLoading}+ value={code}+ onChange={(e) => setCode(e.target.value.toUpperCase())}+ maxLength={10}+ className="flex h-10 w-full rounded-md border-0 bg-background bg-white px-3 py-2 font-mono text-lg tracking-widest text-gray-900 ring-1 ring-gray-200 transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground placeholder:font-sans placeholder:text-sm placeholder:tracking-normal focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50"+ />+ </div>++ {error && (+ <p className="text-sm text-red-600" role="alert">+ {error}+ </p>+ )}++ <Button+ type="submit"+ loading={isLoading}+ disabled={isLoading || !email || code.length < 10}+ 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+ </Button>+ </form>+ )}++ <p className="mt-6 px-4 text-center text-sm text-muted-foreground sm:px-12">+ Didn't receive a code?{" "}+ <Link href="/login" className="text-gray-900 underline">+ Try again+ </Link>+ </p>++ <p className="mt-10 w-full max-w-md px-4 text-xs text-muted-foreground sm:px-12">+ By clicking continue, you acknowledge that you have read and agree+ to Papermark's{" "}+ <a+ href={`${process.env.NEXT_PUBLIC_MARKETING_URL}/terms`}+ target="_blank"+ className="underline"+ >+ Terms of Service+ </a>{" "}+ and{" "}+ <a+ href={`${process.env.NEXT_PUBLIC_MARKETING_URL}/privacy`}+ target="_blank"+ className="underline"+ >+ Privacy Policy+ </a>+ .+ </p>+ </div>+ </div>+ <TestimonialSection />+ </div>+ );+}++function TestimonialSection() {+ return (+ <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"+ >+ {/* Testimonial top 2/3 */}+ <div+ className="flex w-full flex-col items-center justify-center"+ style={{ height: "66.6666%" }}+ >+ {/* Image container */}+ <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>+ {/* Text content */}+ <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>+ {/* White block with logos bottom 1/3, full width/height */}+ <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>+ );+}diff --git a/app/(auth)/auth/email/[[...params]]/page.tsx b/app/(auth)/auth/email/[[...params]]/page.tsxnew file mode 100644index 00000000..b0661791--- /dev/null+++ b/app/(auth)/auth/email/[[...params]]/page.tsx@@ -0,0 +1,57 @@+import { Metadata } from "next";++import EmailVerificationClient from "./page-client";++const data = {+ description: "Verify your login to Papermark",+ title: "Verify Login | Papermark",+ url: "/auth/email",+};++export const metadata: Metadata = {+ metadataBase: new URL("https://www.papermark.com"),+ title: data.title,+ description: data.description,+ openGraph: {+ title: data.title,+ description: data.description,+ url: data.url,+ siteName: "Papermark",+ images: [+ {+ url: "/_static/meta-image.png",+ width: 800,+ height: 600,+ },+ ],+ locale: "en_US",+ type: "website",+ },+ twitter: {+ card: "summary_large_image",+ title: data.title,+ description: data.description,+ creator: "@papermarkio",+ images: ["/_static/meta-image.png"],+ },+};++export default async function EmailVerificationPage({+ params,+}: {+ params: { params?: string[] };+}) {+ // Extract email, code, and uuid from params+ // URL format: /auth/email/{email}/{code}/{uuid}+ const [encodedEmail, code, uuid] = params.params || [];+ const email = encodedEmail ? decodeURIComponent(encodedEmail) : undefined;++ return (+ <EmailVerificationClient+ email={email}+ code={code}+ uuid={uuid}+ autoVerify={!!(email && code && uuid)}+ />+ );+}diff --git a/app/(auth)/verify/page.tsx b/app/(auth)/verify/page.tsxindex 7576d8fa..b2e0b6c3 100644--- a/app/(auth)/verify/page.tsx+++ b/app/(auth)/verify/page.tsx@@ -1,7 +1,6 @@import { Metadata } from "next";import Link from "next/link";--import NotFound from "@/pages/404";+import { redirect } from "next/navigation";import { getMagicLinkData } from "@/lib/emails/send-verification-request";import { generateChecksum } from "@/lib/utils/generate-checksum";@@ -66,15 +65,20 @@ export default async function VerifyPage({}) {const { token, verification_url, checksum } = searchParams;+ // If no params at all, redirect to the new auth email page for manual code entry+ if (!token && !verification_url && !checksum) {+ redirect("/auth/email");+ }+let verifyUrl: string | null = null;let isExpired = false;- // New flow: token-based verification (stored in Redis)+ // New flow: token-based verification (now UUID-based, stored in Redis)if (token) {const magicLinkData = await getMagicLinkData(token);if (magicLinkData) {- // Use the API route that will delete the token and redirect- verifyUrl = `/api/verify/login-link?token=${token}`;+ // Redirect to the new verify-code API+ verifyUrl = `/api/auth/verify-code?uuid=${token}`;} else {// Token not found or expired (Redis TTL handles expiration automatically)isExpired = true;@@ -87,87 +91,89 @@ export default async function VerifyPage({}}- // If no valid verify URL found, show appropriate error- if (!verifyUrl) {- 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>+ // If expired, show expired page with option to request new code+ 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 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>+ <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="relative flex h-full w-full flex-col justify-between"- id="features"+ className="flex w-full flex-col items-center justify-center"+ style={{ height: "66.6666%" }}>- <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 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="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 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>- );- }- return <NotFound />;+ </div>+ );+ }++ // If no valid verify URL found, redirect to auth email page for manual entry+ if (!verifyUrl) {+ redirect("/auth/email");}return (diff --git a/app/api/auth/verify-code/route.ts b/app/api/auth/verify-code/route.tsnew file mode 100644index 00000000..e7ad365c--- /dev/null+++ b/app/api/auth/verify-code/route.ts@@ -0,0 +1,142 @@+import { NextRequest, NextResponse } from "next/server";++import {+ deleteMagicLinkData,+ getMagicLinkData,+ getMagicLinkDataByCode,+} from "@/lib/emails/send-verification-request";+import { ratelimit } from "@/lib/redis";++// Rate limiters+const emailRateLimit = ratelimit(5, "1 m"); // 5 attempts per minute per email+const ipRateLimit = ratelimit(10, "1 m"); // 10 attempts per minute per IP++function getClientIp(request: NextRequest): string {+ const forwarded = request.headers.get("x-forwarded-for");+ const realIp = request.headers.get("x-real-ip");+ return forwarded?.split(",")[0]?.trim() || realIp || "unknown";+}++// GET: Verify via UUID (from email link)+export async function GET(request: NextRequest) {+ const searchParams = request.nextUrl.searchParams;+ const uuid = searchParams.get("uuid");++ if (!uuid) {+ return NextResponse.json({ error: "Missing UUID parameter" }, { status: 400 });+ }++ const ip = getClientIp(request);++ // Check IP rate limit+ const ipLimit = await ipRateLimit.limit(`verify_code:ip:${ip}`);+ if (!ipLimit.success) {+ return NextResponse.json(+ {+ error: "Too many attempts. Please wait before trying again.",+ retryAfter: Math.ceil((ipLimit.reset - Date.now()) / 1000),+ },+ { status: 429 },+ );+ }++ try {+ const magicLinkData = await getMagicLinkData(uuid);++ if (!magicLinkData) {+ return NextResponse.json(+ { error: "This code has expired or is invalid." },+ { status: 410 },+ );+ }++ const { callbackUrl, email, code } = magicLinkData;++ // Delete both Redis keys to prevent reuse+ await deleteMagicLinkData(uuid, email, code);++ return NextResponse.json({ callbackUrl });+ } catch (error) {+ console.error("Error verifying code:", error);+ return NextResponse.json(+ { error: "Verification failed. Please try again." },+ { status: 500 },+ );+ }+}++// POST: Verify via email + code (manual entry)+export async function POST(request: NextRequest) {+ try {+ const body = await request.json();+ const { email, code } = body;++ if (!email || !code) {+ return NextResponse.json(+ { error: "Email and code are required." },+ { status: 400 },+ );+ }++ const normalizedEmail = email.trim().toLowerCase();+ const normalizedCode = code.trim().toUpperCase();++ const ip = getClientIp(request);++ // Check both rate limits+ const [emailLimit, ipLimit] = await Promise.all([+ emailRateLimit.limit(`verify_code:${normalizedEmail}`),+ ipRateLimit.limit(`verify_code:ip:${ip}`),+ ]);++ if (!emailLimit.success) {+ return NextResponse.json(+ {+ error: "Too many attempts. Please wait before trying again.",+ retryAfter: Math.ceil((emailLimit.reset - Date.now()) / 1000),+ remaining: 0,+ },+ { status: 429 },+ );+ }++ if (!ipLimit.success) {+ return NextResponse.json(+ {+ error: "Too many attempts. Please wait before trying again.",+ retryAfter: Math.ceil((ipLimit.reset - Date.now()) / 1000),+ remaining: 0,+ },+ { status: 429 },+ );+ }++ const magicLinkData = await getMagicLinkDataByCode(+ normalizedEmail,+ normalizedCode,+ );++ if (!magicLinkData) {+ return NextResponse.json(+ {+ error: "Invalid code. Please check your email and try again.",+ remaining: emailLimit.remaining,+ },+ { status: 401 },+ );+ }++ const { callbackUrl, uuid } = magicLinkData;++ // Delete both Redis keys to prevent reuse+ await deleteMagicLinkData(uuid, normalizedEmail, normalizedCode);++ return NextResponse.json({ callbackUrl });+ } catch (error) {+ console.error("Error verifying code:", error);+ return NextResponse.json(+ { error: "Verification failed. Please try again." },+ { status: 500 },+ );+ }+}diff --git a/app/api/verify/login-link/route.ts b/app/api/verify/login-link/route.tsindex a732b2d3..e94f66d8 100644--- a/app/api/verify/login-link/route.ts+++ b/app/api/verify/login-link/route.ts@@ -10,27 +10,34 @@ export async function GET(request: NextRequest) {const token = searchParams.get("token");if (!token) {- return NextResponse.redirect(new URL("/login?error=InvalidToken", request.url));+ return NextResponse.redirect(+ new URL("/login?error=InvalidToken", request.url),+ );}try {- // Get the magic link data from Redis+ // Get the magic link data from Redis (token is now a UUID)const magicLinkData = await getMagicLinkData(token);if (!magicLinkData) {// Token not found or expired - redirect back to verify page to show error- return NextResponse.redirect(new URL(`/verify?token=${token}`, request.url));+ return NextResponse.redirect(+ new URL(`/verify?token=${token}`, request.url),+ );}- const { callbackUrl } = magicLinkData;+ const { callbackUrl, email, code } = magicLinkData;// Delete the token from Redis to prevent reuse- await deleteMagicLinkData(token);+ // Pass email and code for the new dual-key system+ await deleteMagicLinkData(token, email, code);// Redirect to the callback URL (NextAuth verification URL)return NextResponse.redirect(callbackUrl);} catch (error) {console.error("Error verifying magic link:", error);- return NextResponse.redirect(new URL("/login?error=VerificationError", request.url));+ return NextResponse.redirect(+ new URL("/login?error=VerificationError", request.url),+ );}}diff --git a/components/emails/verification-link.tsx b/components/emails/verification-link.tsxindex 91a3bc0a..a9de9f28 100644--- a/components/emails/verification-link.tsx+++ b/components/emails/verification-link.tsx@@ -5,6 +5,7 @@ import {Container,Head,Heading,+ Hr,Html,Link,Preview,@@ -15,33 +16,19 @@ 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://app.papermark.com/verify?token=example",+ url = "https://app.papermark.com/auth/email/[email protected]/45PFSNUDYW/abc-123",email = "[email protected]",- expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000),+ code = "45PFSNUDYW",}: {url: string;email?: string;- expiresAt?: Date;+ code?: string;}) => {- const requestedAt = new Date();-return (<Html><Head />- <Preview>Your Papermark Login Link - Sign in to your account</Preview>+ <Preview>To login to Papermark, follow this link {url}</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">@@ -50,59 +37,44 @@ const VerificationLinkEmail = ({Papermark</Text></Section>- <Heading className="mx-0 my-7 p-0 text-lg font-medium text-black">- Your secure login link+ <Heading className="mx-0 my-7 p-0 text-xl font-semibold text-black">+ Your login code for Papermark</Heading>- <Text className="text-sm leading-6 text-black">Hi there,</Text>- <Text className="text-sm leading-6 text-black">- You’re receiving this email because a secure sign-in was requested- for your <strong>Papermark</strong> account associated with{" "}- <strong>{email}</strong>.- </Text>- <Section className="my-8 text-center">+ <Section className="my-8"><LinkclassName="rounded-lg bg-black px-6 py-3 text-center text-[12px] font-semibold text-white no-underline"href={url}>- Sign in to Papermark+ Login to Papermark</Link></Section>- <Text className="text-sm leading-6 text-black">- If the button doesn’t work, copy and paste this link into your- browser:- </Text>- <Text className="max-w-sm flex-wrap break-words font-medium text-purple-600 no-underline">- {url}+ <Text className="text-sm leading-6 text-neutral-600">+ This link and code will only be valid for the next 15 minutes. If+ the link does not work, you can use the login verification code+ directly:</Text>- <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)})+ <Section className="my-4">+ <Text+ className="m-0 w-fit rounded-lg bg-neutral-100 px-2 py-1 text-base font-bold tracking-wider text-black"+ style={{ fontFamily: "monospace" }}+ >+ {code}</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.+ </Section>+ <Text className="text-sm leading-5 text-neutral-500">+ If you didn't try to log in, you can safely ignore this+ email.+ </Text>+ <Hr />+ <Section className="text-gray-400">+ <Text className="text-xs text-neutral-500">+ Papermark, Inc.+ <br />+ 1111B S Governors Ave #28117+ <br />+ Dover, DE 19904</Text></Section>- <Footer- withAddress={true}- footerText="This is a 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 346d59ca..b2216679 100644--- a/lib/emails/send-verification-request.ts+++ b/lib/emails/send-verification-request.ts@@ -5,19 +5,22 @@ import { sendEmail } from "@/lib/resend";import LoginLink from "@/components/emails/verification-link";-// Generate a secure 20-character token using alphanumeric characters-const generateMagicLinkToken = customAlphabet(- "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",- 20,+// Generate a 10-character uppercase alphanumeric verification code (like Linear's style)+const generateVerificationCode = customAlphabet(+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ",+ 10,);-// Redis key prefix for magic link tokens-const MAGIC_LINK_PREFIX = "magic_link:";-// Token expiration time in seconds (24 hours)-const TOKEN_EXPIRATION_SECONDS = 24 * 60 * 60;+// Redis key prefixes for login codes+const LOGIN_CODE_PREFIX = "login_code:";+const LOGIN_CODE_EMAIL_PREFIX = "login_code:email:";+// Token expiration time in seconds (15 minutes)+const TOKEN_EXPIRATION_SECONDS = 15 * 60;export interface MagicLinkData {email: string;+ code: string;+ uuid: string;callbackUrl: string;createdAt: number;}@@ -28,39 +31,48 @@ export const sendVerificationRequestEmail = async (params: {}) => {const { url, email } = params;- // Generate a short, unique token- const token = generateMagicLinkToken();+ // Generate verification code and UUID+ const code = generateVerificationCode();+ const uuid = crypto.randomUUID();- // Store the callback URL in Redis with 24-hour TTL+ // Store the login data in Redis with 15-minute TTLconst magicLinkData: MagicLinkData = {email,+ code,+ uuid,callbackUrl: url,createdAt: Date.now(),};+ // Store with UUID as primary keyawait redis.set(- `${MAGIC_LINK_PREFIX}${token}`,+ `${LOGIN_CODE_PREFIX}${uuid}`,JSON.stringify(magicLinkData),{ ex: TOKEN_EXPIRATION_SECONDS },);- // Create simplified verification URL (under 100 characters)- const verificationUrl = `${process.env.NEXTAUTH_URL}/verify?token=${token}`;+ // Store secondary key for code lookup: email:code -> uuid+ await redis.set(+ `${LOGIN_CODE_EMAIL_PREFIX}${email.toLowerCase()}:${code}`,+ uuid,+ { ex: TOKEN_EXPIRATION_SECONDS },+ );- // Calculate expiration time for the email- const expiresAt = new Date(Date.now() + TOKEN_EXPIRATION_SECONDS * 1000);+ // Create verification URL with email, code, and uuid+ const encodedEmail = encodeURIComponent(email);+ const verificationUrl = `${process.env.NEXTAUTH_URL}/auth/email/${encodedEmail}/${code}/${uuid}`;const emailTemplate = LoginLink({url: verificationUrl,email,- expiresAt,+ code,});try {await sendEmail({to: email as string,system: true,- subject: "Your secure Papermark sign-in link",+ subject: "Login for Papermark",react: emailTemplate,test: process.env.NODE_ENV === "development",});@@ -70,14 +82,14 @@ export const sendVerificationRequestEmail = async (params: {};/**- * Retrieve magic link data from Redis- * Returns null if token doesn't exist or has expired (Redis handles TTL automatically)+ * Retrieve magic link data from Redis by UUID+ * Returns null if UUID doesn't exist or has expired (Redis handles TTL automatically)*/export const getMagicLinkData = async (- token: string,+ uuid: string,): Promise<MagicLinkData | null> => {try {- const data = await redis.get(`${MAGIC_LINK_PREFIX}${token}`);+ const data = await redis.get(`${LOGIN_CODE_PREFIX}${uuid}`);if (!data) return null;// Handle both string and already-parsed object (Redis client behavior)@@ -91,13 +103,49 @@ export const getMagicLinkData = async (}};+/**+ * Retrieve magic link data from Redis by email and code+ * Returns null if not found or expired+ */+export const getMagicLinkDataByCode = async (+ email: string,+ code: string,+): Promise<MagicLinkData | null> => {+ try {+ // Look up UUID from email:code key+ const uuid = await redis.get(+ `${LOGIN_CODE_EMAIL_PREFIX}${email.toLowerCase()}:${code.toUpperCase()}`,+ );+ if (!uuid || typeof uuid !== "string") return null;++ // Get the full data using the UUID+ return getMagicLinkData(uuid);+ } catch (error) {+ console.error("Error fetching magic link data by code:", error);+ return null;+ }+};+/*** Delete magic link data from Redis after successful use* This prevents the link from being reused*/-export const deleteMagicLinkData = async (token: string): Promise<boolean> => {+export const deleteMagicLinkData = async (+ uuid: string,+ email?: string,+ code?: string,+): Promise<boolean> => {try {- const result = await redis.del(`${MAGIC_LINK_PREFIX}${token}`);+ // Delete primary key+ const result = await redis.del(`${LOGIN_CODE_PREFIX}${uuid}`);++ // Delete secondary key if email and code are provided+ if (email && code) {+ await redis.del(+ `${LOGIN_CODE_EMAIL_PREFIX}${email.toLowerCase()}:${code.toUpperCase()}`,+ );+ }+return result === 1;} catch (error) {console.error("Error deleting magic link data:", error);diff --git a/middleware.ts b/middleware.tsindex 118d6910..ca4f5b74 100644--- a/middleware.ts+++ b/middleware.ts@@ -69,7 +69,8 @@ export default async function middleware(req: NextRequest, ev: NextFetchEvent) {if (!path.startsWith("/view/") &&!path.startsWith("/verify") &&- !path.startsWith("/unsubscribe")+ !path.startsWith("/unsubscribe") &&+ !path.startsWith("/auth/email")) {return AppMiddleware(req);}