Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: Added global email block list for teams
Ashish Viradiya2a318d631731
diff --git a/app/api/views-dataroom/route.ts b/app/api/views-dataroom/route.tsindex 64225063..9304be48 100644--- a/app/api/views-dataroom/route.ts+++ b/app/api/views-dataroom/route.ts@@ -121,6 +121,7 @@ export async function POST(request: NextRequest) {team: {select: {plan: true,+ globalBlockList: true,},},customFields: {@@ -315,6 +316,22 @@ export async function POST(request: NextRequest) {}}+ if (link.team?.globalBlockList && link.team.globalBlockList.length > 0) {+ const emailDomain = email.substring(email.lastIndexOf("@"));+ const isGloballyBlocked = link.team.globalBlockList.some((blocked) => {+ return (+ blocked === email ||+ (blocked.startsWith("@") && emailDomain === blocked)+ );+ });+ if (isGloballyBlocked) {+ return NextResponse.json(+ { message: "Access denied" },+ { status: 403 },+ );+ }+ }+// Check if group is allowed to visit the linkif (link.audienceType === LinkAudienceType.GROUP && link.groupId) {const group = await prisma.viewerGroup.findUnique({@@ -587,28 +604,28 @@ export async function POST(request: NextRequest) {...(link.enableAgreement &&link.agreementId &&hasConfirmedAgreement && {- agreementResponse: {- create: {- agreementId: link.agreementId,- },+ agreementResponse: {+ create: {+ agreementId: link.agreementId,},- }),+ },+ }),...(link.audienceType === LinkAudienceType.GROUP &&link.groupId && {- groupId: link.groupId,- }),+ groupId: link.groupId,+ }),...(customFields &&link.customFields.length > 0 && {- customFieldResponse: {- create: {- data: link.customFields.map((field) => ({- identifier: field.identifier,- label: field.label,- response: customFields[field.identifier] || "",- })),- },+ customFieldResponse: {+ create: {+ data: link.customFields.map((field) => ({+ identifier: field.identifier,+ label: field.label,+ response: customFields[field.identifier] || "",+ })),},- }),+ },+ }),};// ** DATAROOM_VIEW **@@ -912,15 +929,15 @@ export async function POST(request: NextRequest) {documentVersion.type === "image" ||documentVersion.type === "zip" ||documentVersion.type === "video")) ||- (documentVersion && useAdvancedExcelViewer)+ (documentVersion && useAdvancedExcelViewer)? documentVersion.file: undefined,pages: documentPages ? documentPages : undefined,notionData: undefined,sheetData:documentVersion &&- documentVersion.type === "sheet" &&- !useAdvancedExcelViewer+ documentVersion.type === "sheet" &&+ !useAdvancedExcelViewer? sheetData: undefined,fileType: documentVersion@@ -934,16 +951,16 @@ export async function POST(request: NextRequest) {viewerEmail: viewer?.email ?? email ?? verifiedEmail ?? null,ipAddress:link.enableWatermark &&- link.watermarkConfig &&- WatermarkConfigSchema.parse(link.watermarkConfig).text.includes(- "{{ipAddress}}",- )+ link.watermarkConfig &&+ WatermarkConfigSchema.parse(link.watermarkConfig).text.includes(+ "{{ipAddress}}",+ )? (ipAddress(request) ?? LOCALHOST_IP): undefined,useAdvancedExcelViewer:documentVersion &&- documentVersion.type === "sheet" &&- useAdvancedExcelViewer+ documentVersion.type === "sheet" &&+ useAdvancedExcelViewer? useAdvancedExcelViewer: undefined,canDownload: canDownload,diff --git a/app/api/views/route.ts b/app/api/views/route.tsindex a1b2b21e..40d326d0 100644--- a/app/api/views/route.ts+++ b/app/api/views/route.ts@@ -100,6 +100,7 @@ export async function POST(request: NextRequest) {team: {select: {plan: true,+ globalBlockList: true,},},customFields: {@@ -251,6 +252,22 @@ export async function POST(request: NextRequest) {}}+ if (link.team?.globalBlockList && link.team.globalBlockList.length > 0) {+ const emailDomain = email.substring(email.lastIndexOf("@"));+ const isGloballyBlocked = link.team.globalBlockList.some((blocked) => {+ return (+ blocked === email ||+ (blocked.startsWith("@") && emailDomain === blocked)+ );+ });+ if (isGloballyBlocked) {+ return NextResponse.json(+ { message: "Access denied" },+ { status: 403 },+ );+ }+ }+// Request OTP Code for email verification if// 1) email verification is required and// 2) code is not provided or token not provideddiff --git a/components/settings/global-block-list-form.tsx b/components/settings/global-block-list-form.tsxnew file mode 100644index 00000000..b2e4b4aa--- /dev/null+++ b/components/settings/global-block-list-form.tsx@@ -0,0 +1,125 @@+import { useEffect, useMemo, useState } from "react";++import { useTeam } from "@/context/team-context";+import { toast } from "sonner";+import useSWR from "swr";++import { fetcher, sanitizeList } from "@/lib/utils";++import { Button } from "@/components/ui/button";+import {+ Card,+ CardContent,+ CardDescription,+ CardFooter,+ CardHeader,+ CardTitle,+} from "@/components/ui/card";+import { Textarea } from "@/components/ui/textarea";++export default function GlobalBlockListForm() {+ const teamInfo = useTeam();+ const teamId = teamInfo?.currentTeam?.id;++ const { data: blockList, mutate } = useSWR<string[]>(+ teamId ? `/api/teams/${teamId}/global-block-list` : null,+ fetcher,+ );++ const [blockListInput, setBlockListInput] = useState("");+ const [initialBlockListInput, setInitialBlockListInput] = useState("");+ const [isSaving, setIsSaving] = useState(false);++ useEffect(() => {+ if (blockList) {+ const val = blockList.join("\n");+ setBlockListInput(val);+ setInitialBlockListInput(val);+ }+ }, [blockList]);++ const allEntered = blockListInput+ .split("\n")+ .map((d) => d.trim())+ .filter(Boolean);+ const validEntries = sanitizeList(blockListInput, "both");+ const invalidEntries = allEntered.filter(+ (d) => !validEntries.includes(d.toLowerCase()),+ );++ const saveDisabled = useMemo(() => {+ return (+ isSaving ||+ blockListInput === initialBlockListInput ||+ invalidEntries.length > 0+ );+ }, [isSaving, blockListInput, initialBlockListInput, invalidEntries]);++ const handleSave = async () => {+ setIsSaving(true);+ const entries = sanitizeList(blockListInput, "both");++ const promise = fetch(`/api/teams/${teamId}/global-block-list`, {+ method: "PUT",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ blockList: entries }),+ }).then(async (res) => {+ if (!res.ok) {+ const { error } = await res.json();+ throw new Error(error?.message || "Failed to update block list.");+ }+ await mutate();+ return res.json();+ });++ toast.promise(promise, {+ loading: "Saving block list...",+ success: "Block list saved!",+ error: (err) => err.message,+ });++ try {+ await promise;+ } finally {+ setIsSaving(false);+ }+ };++ return (+ <Card>+ <CardHeader>+ <CardTitle>Global Block List</CardTitle>+ <CardDescription>+ Visitors with these emails or domains will be{" "}+ <b>blocked from all links</b> in your team. Use{" "}+ <code>@domain.com</code> for domains or full email addresses.+ </CardDescription>+ </CardHeader>+ <CardContent>+ <Textarea+ className="focus:ring-inset"+ rows={5}+ placeholder={`Enter one email or domain per line, e.g.\[email protected]\[email protected]`}+ value={blockListInput}+ onChange={(e) => setBlockListInput(e.target.value)}+ />+ {invalidEntries.length > 0 && (+ <p className="mt-2 text-sm text-destructive">+ The following entries are not valid and will be ignored:{" "}+ {invalidEntries.join(", ")}+ </p>+ )}+ </CardContent>+ <CardFooter className="flex items-center justify-between rounded-b-lg border-t bg-muted px-6 py-3">+ <p className="text-sm text-muted-foreground transition-colors">+ Add emails or domains to block access to all links.+ </p>+ <Button onClick={handleSave} loading={isSaving} disabled={saveDisabled}>+ Save Changes+ </Button>+ </CardFooter>+ </Card>+ );+}diff --git a/pages/api/links/[id]/documents/[documentId].ts b/pages/api/links/[id]/documents/[documentId].tsindex 14e87c29..be5e145a 100644--- a/pages/api/links/[id]/documents/[documentId].ts+++ b/pages/api/links/[id]/documents/[documentId].ts@@ -60,6 +60,7 @@ export default async function handle(team: {select: {plan: true,+ globalBlockList: true,},},customFields: {@@ -88,6 +89,24 @@ export default async function handle(return res.status(404).json({ error: "Link is archived" });}+ const { email } = req.query as { email?: string };+ if (email && link.team?.globalBlockList && link.team.globalBlockList.length > 0) {+ const emailDomain = email.substring(email.lastIndexOf("@"));++ const isBlocked = link.team.globalBlockList.some((blocked) => {+ return (+ blocked === email ||+ (blocked.startsWith("@") && emailDomain === blocked)+ );+ });++ if (isBlocked) {+ return res.status(403).json(+ { message: "Access denied" },+ );+ }+ }+let brand: Partial<DataroomBrand> | null = null;let linkData: any;diff --git a/pages/api/links/domains/[...domainSlug].ts b/pages/api/links/domains/[...domainSlug].tsindex 483e8526..2dbec274 100644--- a/pages/api/links/domains/[...domainSlug].ts+++ b/pages/api/links/domains/[...domainSlug].ts@@ -77,6 +77,7 @@ export default async function handle(team: {select: {plan: true,+ globalBlockList: true,},},customFields: {@@ -118,6 +119,22 @@ export default async function handle(});}+ const { email } = req.query as { email?: string };+ if (email && link.team?.globalBlockList && link.team.globalBlockList.length > 0) {+ const emailDomain = email.substring(email.lastIndexOf("@"));+ const isBlocked = link.team.globalBlockList.some((blocked) => {+ return (+ blocked === email ||+ (blocked.startsWith("@") && emailDomain === blocked)+ );+ });+ if (isBlocked) {+ return res.status(403).json(+ { message: "Access denied" },+ );+ }+ }+const teamPlan = link.team?.plan || "free";const teamId = link.teamId;// if owner of document is on free plan, return 404diff --git a/pages/api/teams/[teamId]/global-block-list.ts b/pages/api/teams/[teamId]/global-block-list.tsnew file mode 100644index 00000000..d5b8adef--- /dev/null+++ b/pages/api/teams/[teamId]/global-block-list.ts@@ -0,0 +1,84 @@+import { NextApiRequest, NextApiResponse } from "next";++import { getServerSession } from "next-auth";++import prisma from "@/lib/prisma";+import { CustomUser } from "@/lib/types";+import { sanitizeList } from "@/lib/utils";++import { authOptions } from "../../auth/[...nextauth]";++async function handler(req: NextApiRequest, res: NextApiResponse) {+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).json({ error: "Unauthorized" });+ }++ const { teamId } = req.query;++ if (typeof teamId !== "string") {+ return res.status(400).json({ error: "Invalid teamId" });+ }++ const team = await prisma.team.findFirst({+ where: {+ id: teamId,+ users: {+ some: {+ userId: (session.user as CustomUser).id,+ },+ },+ },+ include: {+ users: true,+ },+ });++ if (!team) {+ return res.status(404).json({ error: "Team not found" });+ }++ const isUserAdmin = team.users.some(+ (user) =>+ user.role === "ADMIN" && user.userId === (session.user as CustomUser).id,+ );++ if (!isUserAdmin) {+ return res.status(403).json({ error: "Forbidden" });+ }++ if (req.method === "GET") {+ return res.status(200).json(team.globalBlockList || []);+ }++ if (req.method === "PUT") {+ try {+ const { blockList } = req.body;++ if (!Array.isArray(blockList)) {+ return res.status(400).json({ error: "Invalid block list" });+ }++ const uniqueBlockList = sanitizeList(blockList.join("\n"), "both");++ await prisma.team.update({+ where: {+ id: teamId,+ },+ data: {+ globalBlockList: uniqueBlockList,+ },+ });++ return res.status(200).json({ message: "Global block list updated" });+ } catch (error) {+ console.error(error);+ return res.status(500).json({ error: "Internal server error" });+ }+ }++ res.setHeader("Allow", ["GET", "PUT"]);+ return res.status(405).json({ error: "Method not allowed" });+}++export default handler;\ No newline at end of filediff --git a/pages/settings/general.tsx b/pages/settings/general.tsxindex 08d4b3dc..f0aa1487 100644--- a/pages/settings/general.tsx+++ b/pages/settings/general.tsx@@ -11,6 +11,7 @@ import { usePlan } from "@/lib/swr/use-billing";import { UpgradePlanModal } from "@/components/billing/upgrade-plan-modal";import AppLayout from "@/components/layouts/app";import DeleteTeam from "@/components/settings/delete-team";+import GlobalBlockListForm from "@/components/settings/global-block-list-form";import IgnoredDomainsForm from "@/components/settings/ignored-domains-form";import { SettingsHeader } from "@/components/settings/settings-header";import { Form } from "@/components/ui/form";@@ -147,6 +148,7 @@ export default function General() {plan={(isFree && !isTrial) || isPro ? "Business" : undefined}/><IgnoredDomainsForm />+ <GlobalBlockListForm /><DeleteTeam /></div>@@ -162,4 +164,4 @@ export default function General() {</main></AppLayout>);-}+}\ No newline at end of filediff --git a/prisma/migrations/20250715042921_add_global_block_list_to_team/migration.sql b/prisma/migrations/20250715042921_add_global_block_list_to_team/migration.sqlnew file mode 100644index 00000000..54d17721--- /dev/null+++ b/prisma/migrations/20250715042921_add_global_block_list_to_team/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "Team" ADD COLUMN "globalBlockList" TEXT[];diff --git a/prisma/schema/schema.prisma b/prisma/schema/schema.prismaindex a1953c22..ee594ee7 100644--- a/prisma/schema/schema.prisma+++ b/prisma/schema/schema.prisma@@ -110,6 +110,7 @@ model Team {Tag Tag[]ignoredDomains String[] // Domains that are ignored for the team+ globalBlockList String[]}