Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
improvement: notify team if blocked email tried to access a link
Ashish Viradiya3ff9ea2b2caa
diff --git a/app/api/views-dataroom/route.ts b/app/api/views-dataroom/route.tsindex 633af43a..7d8d705f 100644--- a/app/api/views-dataroom/route.ts+++ b/app/api/views-dataroom/route.ts@@ -27,6 +27,7 @@ import { generateOTP } from "@/lib/utils/generate-otp";import { LOCALHOST_IP } from "@/lib/utils/geo";import { checkGlobalBlockList } from "@/lib/utils/global-block-list";import { validateEmail } from "@/lib/utils/validate-email";+import { sendBlockedEmailAttemptNotification } from "@/lib/emails/send-blocked-email-attempt";export async function POST(request: NextRequest) {try {@@ -98,6 +99,8 @@ export async function POST(request: NextRequest) {id: linkId,},select: {+ id: true,+ name: true,documentId: true,dataroomId: true,emailProtected: true,@@ -286,6 +289,11 @@ export async function POST(request: NextRequest) {);}if (globalBlockCheck.isBlocked) {+ try {+ await notifyBlockedAttempt(link, email);+ } catch (e) {+ console.error(e);+ }return NextResponse.json({ message: "Access denied" }, { status: 403 });}@@ -314,6 +322,11 @@ export async function POST(request: NextRequest) {// Deny access if the email is deniedif (isDenied) {+ try {+ await notifyBlockedAttempt(link, email);+ } catch (e) {+ console.error(e);+ }return NextResponse.json({ message: "Unauthorized access" },{ status: 403 },@@ -1012,3 +1025,57 @@ export async function POST(request: NextRequest) {);}}++export async function notifyBlockedAttempt(link: any, email: string) {+ if (!link) return;+ const users = await prisma.userTeam.findMany({+ where: {+ role: { in: ["ADMIN", "MANAGER"] },+ status: "ACTIVE",+ teamId: link.teamId!,+ },+ select: {+ user: { select: { email: true } },+ },+ });+ const adminEmails = users.map((u) => u.user?.email).filter((e): e is string => !!e);+ let ownerEmail: string | undefined;+ let resourceType: "dataroom" | "document" = "dataroom";+ let resourceName = "Dataroom";+ if (link.documentId) {+ resourceType = "document";+ const doc = await prisma.document.findUnique({ where: { id: link.documentId }, select: { name: true, ownerId: true } });+ resourceName = doc?.name || "Document";+ if (doc?.ownerId) {+ const owner = await prisma.userTeam.findUnique({+ where: {+ userId_teamId: {+ userId: doc.ownerId,+ teamId: link.teamId!,+ },+ status: "ACTIVE",+ },+ select: { user: { select: { email: true } } },+ });+ ownerEmail = owner?.user?.email || undefined;+ }+ } else if (link.dataroomId) {+ resourceType = "dataroom";+ resourceName = (await prisma.dataroom.findUnique({ where: { id: link.dataroomId }, select: { name: true } }))?.name || "Dataroom";+ }++ let cc = adminEmails.slice(1);+ const to = ownerEmail || adminEmails[0] || "";+ if (ownerEmail && !cc.includes(ownerEmail) && ownerEmail !== to) {+ cc = [ownerEmail, ...cc];+ }++ await sendBlockedEmailAttemptNotification({+ to,+ cc,+ blockedEmail: email!,+ linkName: link?.name || `Link #${link.id.slice(-5)}`,+ resourceName,+ resourceType,+ });+}diff --git a/app/api/views/route.ts b/app/api/views/route.tsindex 2ae77def..f30e7af1 100644--- a/app/api/views/route.ts+++ b/app/api/views/route.ts@@ -19,11 +19,12 @@ import { parseSheet } from "@/lib/sheet";import { recordLinkView } from "@/lib/tracking/record-link-view";import { CustomUser, WatermarkConfigSchema } from "@/lib/types";import { checkPassword, decryptEncrpytedPassword, log } from "@/lib/utils";-import { extractEmailDomain, isEmailMatched } from "@/lib/utils/email-domain";+import { isEmailMatched } from "@/lib/utils/email-domain";import { generateOTP } from "@/lib/utils/generate-otp";import { LOCALHOST_IP } from "@/lib/utils/geo";import { checkGlobalBlockList } from "@/lib/utils/global-block-list";import { validateEmail } from "@/lib/utils/validate-email";+import { notifyBlockedAttempt } from "../views-dataroom/route";export async function POST(request: NextRequest) {try {@@ -84,6 +85,9 @@ export async function POST(request: NextRequest) {id: linkId,},select: {+ id: true,+ name: true,+ documentId: true,emailProtected: true,enableNotification: true,emailAuthenticated: true,@@ -221,6 +225,11 @@ export async function POST(request: NextRequest) {);}if (globalBlockCheck.isBlocked) {+ try {+ await notifyBlockedAttempt(link, email);+ } catch (e) {+ console.error(e);+ }return NextResponse.json({ message: "Access denied" }, { status: 403 });}@@ -249,6 +258,11 @@ export async function POST(request: NextRequest) {// Deny access if the email is deniedif (isDenied) {+ try {+ await notifyBlockedAttempt(link, email);+ } catch (e) {+ console.error(e);+ }return NextResponse.json({ message: "Unauthorized access" },{ status: 403 },diff --git a/components/emails/blocked-email-attempt.tsx b/components/emails/blocked-email-attempt.tsxnew file mode 100644index 00000000..cfd84343--- /dev/null+++ b/components/emails/blocked-email-attempt.tsx@@ -0,0 +1,74 @@+import React from "react";++import {+ Body,+ Container,+ Head,+ Hr,+ Html,+ Preview,+ Section,+ Tailwind,+ Text,+} from "@react-email/components";++export default function BlockedEmailAttempt({+ blockedEmail,+ linkName,+ resourceName,+ resourceType = "document",+ locationString,+}: {+ blockedEmail: string;+ linkName: string;+ resourceName: string;+ resourceType?: "document" | "dataroom";+ locationString?: string;+}) {+ return (+ <Html>+ <Head />+ <Preview>Blocked email attempted to access your {resourceType}</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>+ <Text className="mx-0 my-7 p-0 text-center text-xl font-semibold text-black">+ Blocked Email Attempted Access+ </Text>+ <Text className="text-sm leading-6 text-black">+ The blocked email <span className="font-semibold">{blockedEmail}</span> just attempted to access your {resourceType} <span className="font-semibold">{resourceName}</span> from the link <span className="font-semibold">{linkName}</span>.+ {locationString ? (+ <span>+ {" "}+ in <span className="font-semibold">{locationString}</span>+ </span>+ ) : null}+ </Text>+ <Text className="text-sm leading-6 text-black">+ This email is on your block list and was denied access. No further action is required.+ </Text>+ <Hr />+ <Section className="mt-8 text-gray-400">+ <Text className="text-xs">+ © {new Date().getFullYear()} {" "}+ <a+ href="https://www.papermark.com"+ className="text-gray-400 no-underline hover:text-gray-400"+ target="_blank"+ >+ papermark.com+ </a>+ </Text>+ <Text className="text-xs">+ If you have any feedback or questions about this email, simply reply to it. I'd love to hear from you!+ </Text>+ </Section>+ </Container>+ </Body>+ </Tailwind>+ </Html>+ );+}\ No newline at end of filediff --git a/lib/emails/send-blocked-email-attempt.ts b/lib/emails/send-blocked-email-attempt.tsnew file mode 100644index 00000000..c4489a54--- /dev/null+++ b/lib/emails/send-blocked-email-attempt.ts@@ -0,0 +1,41 @@+import BlockedEmailAttempt from "@/components/emails/blocked-email-attempt";+import { sendEmail } from "@/lib/resend";++export const sendBlockedEmailAttemptNotification = async ({+ to,+ cc,+ blockedEmail,+ linkName,+ resourceName,+ resourceType = "document",+ locationString,+}: {+ to: string;+ cc?: string[];+ blockedEmail: string;+ linkName: string;+ resourceName: string;+ resourceType?: "document" | "dataroom";+ locationString?: string;+}) => {+ const emailTemplate = BlockedEmailAttempt({+ blockedEmail,+ linkName,+ resourceName,+ resourceType,+ locationString,+ });+ try {+ await sendEmail({+ to,+ cc,+ subject: `Blocked email attempted to access your ${resourceType}: ${resourceName}`,+ react: emailTemplate,+ system: true,+ test: process.env.NODE_ENV === "development",+ });+ return { success: true };+ } catch (error) {+ return { success: false, error };+ }+};\ No newline at end of filediff --git a/pages/api/links/[id]/documents/[documentId].ts b/pages/api/links/[id]/documents/[documentId].tsindex 31c9f8d8..09524242 100644--- a/pages/api/links/[id]/documents/[documentId].ts+++ b/pages/api/links/[id]/documents/[documentId].ts@@ -6,6 +6,7 @@ import { fetchDataroomDocumentLinkData } from "@/lib/api/links/link-data";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";import { checkGlobalBlockList } from "@/lib/utils/global-block-list";+import { sendBlockedEmailAttemptNotification } from "@/lib/emails/send-blocked-email-attempt";export default async function handle(req: NextApiRequest,@@ -27,6 +28,7 @@ export default async function handle(where: { id, linkType: "DATAROOM_LINK" },select: {id: true,+ name: true,expiresAt: true,emailProtected: true,emailAuthenticated: true,@@ -99,6 +101,36 @@ export default async function handle(return res.status(400).json({ message: globalBlockCheck.error });}if (globalBlockCheck.isBlocked) {+ try {+ const users = await prisma.userTeam.findMany({+ where: {+ role: { in: ["ADMIN", "MANAGER"] },+ status: "ACTIVE",+ teamId: link.teamId!,+ },+ select: {+ user: { select: { email: true } },+ },+ });+ const adminEmails = users.map((u) => u.user.email).filter((e): e is string => !!e);+ const to = adminEmails[0];+ const cc = adminEmails.slice(1);++ const dataroomDocument = await prisma.dataroomDocument.findUnique({+ where: { id: dataroomDocumentId },+ select: { document: { select: { name: true } } },+ });++ await sendBlockedEmailAttemptNotification({+ to,+ cc,+ blockedEmail: email!,+ linkName: link.name || `Link #${link.id.slice(-5)}`,+ resourceName: `dataroom document ${dataroomDocument?.document?.name}`,+ });+ } catch (e) {+ console.error(e);+ }return res.status(403).json({ message: "Access denied" });}diff --git a/pages/api/links/[id]/index.ts b/pages/api/links/[id]/index.tsindex 4eb7425b..308dacbc 100644--- a/pages/api/links/[id]/index.ts+++ b/pages/api/links/[id]/index.ts@@ -17,6 +17,7 @@ import { checkGlobalBlockList } from "@/lib/utils/global-block-list";import { DomainObject } from "..";import { authOptions } from "../../auth/[...nextauth]";+import { notifyBlockedAttempt } from "@/app/api/views-dataroom/route";export default async function handle(req: NextApiRequest,@@ -34,6 +35,7 @@ export default async function handle(},select: {id: true,+ name: true,expiresAt: true,emailProtected: true,emailAuthenticated: true,@@ -109,6 +111,9 @@ export default async function handle(return res.status(400).json({ message: globalBlockCheck.error });}if (globalBlockCheck.isBlocked) {+ try {+ await notifyBlockedAttempt(link, email!);+ } catch (e) { console.error(e); }return res.status(403).json({ message: "Access denied" });}diff --git a/pages/api/links/domains/[...domainSlug].ts b/pages/api/links/domains/[...domainSlug].tsindex 37a5310f..874f1226 100644--- a/pages/api/links/domains/[...domainSlug].ts+++ b/pages/api/links/domains/[...domainSlug].ts@@ -10,6 +10,7 @@ import {import prisma from "@/lib/prisma";import { log } from "@/lib/utils";import { checkGlobalBlockList } from "@/lib/utils/global-block-list";+import { notifyBlockedAttempt } from "@/app/api/views-dataroom/route";export default async function handle(req: NextApiRequest,@@ -44,6 +45,7 @@ export default async function handle(},select: {id: true,+ name: true,expiresAt: true,emailProtected: true,allowDownload: true,@@ -129,6 +131,9 @@ export default async function handle(return res.status(400).json({ message: globalBlockCheck.error });}if (globalBlockCheck.isBlocked) {+ try {+ await notifyBlockedAttempt(link, email!);+ } catch (e) { console.error(e); }return res.status(403).json({ message: "Access denied" });}