Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat: Added a global list of domains to ignore notification

Ashish Viradiya863146a2a7a5
diff --git a/components/links/link-sheet/allow-list-section.tsx b/components/links/link-sheet/allow-list-section.tsx
index 15cf5031..307e38c3 100644
--- a/components/links/link-sheet/allow-list-section.tsx
+++ b/components/links/link-sheet/allow-list-section.tsx
@@ -4,7 +4,7 @@ import { LinkPreset } from "@prisma/client";
import { motion } from "motion/react";
import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";
-import { sanitizeAllowDenyList } from "@/lib/utils";
+import { sanitizeList } from "@/lib/utils";
import { Textarea } from "@/components/ui/textarea";
@@ -42,7 +42,7 @@ export default function AllowListSection({
useEffect(() => {
// Update the allowList in the data state when their inputs change
- const newAllowList = sanitizeAllowDenyList(allowListInput);
+ const newAllowList = sanitizeList(allowListInput);
setEnabled((prevEnabled) => prevEnabled && emailProtected);
setData((prevData) => ({
...prevData,
@@ -64,7 +64,7 @@ export default function AllowListSection({
if (updatedEnabled) {
setData((prevData) => ({
...prevData,
- allowList: updatedEnabled ? sanitizeAllowDenyList(allowListInput) : [],
+ allowList: updatedEnabled ? sanitizeList(allowListInput) : [],
emailAuthenticated: true, // Turn on email authentication
emailProtected: true, // Turn on email protection
}));
diff --git a/components/links/link-sheet/deny-list-section.tsx b/components/links/link-sheet/deny-list-section.tsx
index 1be96c12..05d83c14 100644
--- a/components/links/link-sheet/deny-list-section.tsx
+++ b/components/links/link-sheet/deny-list-section.tsx
@@ -4,7 +4,7 @@ import { LinkPreset } from "@prisma/client";
import { motion } from "motion/react";
import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";
-import { sanitizeAllowDenyList } from "@/lib/utils";
+import { sanitizeList } from "@/lib/utils";
import { Textarea } from "@/components/ui/textarea";
@@ -41,7 +41,7 @@ export default function DenyListSection({
useEffect(() => {
// Update the denyList in the data state when their inputs change
- const newDenyList = sanitizeAllowDenyList(denyListInput);
+ const newDenyList = sanitizeList(denyListInput);
setEnabled((prevEnabled) => prevEnabled && emailProtected);
setData((prevData) => ({
...prevData,
@@ -63,7 +63,7 @@ export default function DenyListSection({
if (updatedEnabled) {
setData((prevData) => ({
...prevData,
- denyList: updatedEnabled ? sanitizeAllowDenyList(denyListInput) : [],
+ denyList: updatedEnabled ? sanitizeList(denyListInput) : [],
emailAuthenticated: true, // Turn on email authentication
emailProtected: true, // Turn on email protection
}));
diff --git a/components/settings/ignored-domains-form.tsx b/components/settings/ignored-domains-form.tsx
new file mode 100644
index 00000000..303fe8e5
--- /dev/null
+++ b/components/settings/ignored-domains-form.tsx
@@ -0,0 +1,126 @@
+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 IgnoredDomainsForm() {
+ const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
+
+ const { data: ignoredDomains, mutate } = useSWR<string[]>(
+ teamId ? `/api/teams/${teamId}/ignored-domains` : null,
+ fetcher,
+ );
+
+ const [domainsInput, setDomainsInput] = useState("");
+ const [initialDomainsInput, setInitialDomainsInput] = useState("");
+ const [isSaving, setIsSaving] = useState(false);
+
+ useEffect(() => {
+ if (ignoredDomains) {
+ const val = ignoredDomains.join("\n");
+ setDomainsInput(val);
+ setInitialDomainsInput(val);
+ }
+ }, [ignoredDomains]);
+
+ const allEnteredDomains = domainsInput
+ .split("\n")
+ .map((d) => d.trim())
+ .filter(Boolean);
+ const validDomains = sanitizeList(domainsInput, "domain");
+ const invalidDomains = allEnteredDomains.filter(
+ (d) => !validDomains.includes(d.toLowerCase()),
+ );
+
+ const saveDisabled = useMemo(() => {
+ return (
+ isSaving ||
+ domainsInput === initialDomainsInput ||
+ invalidDomains.length > 0
+ );
+ }, [isSaving, domainsInput, initialDomainsInput, invalidDomains]);
+
+ const handleSave = async () => {
+ setIsSaving(true);
+ const domains = sanitizeList(domainsInput, "domain");
+
+ const promise = fetch(`/api/teams/${teamId}/ignored-domains`, {
+ method: "PUT",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ domains }),
+ }).then(async (res) => {
+ if (!res.ok) {
+ const { error } = await res.json();
+ throw new Error(error.message || "Failed to update ignored domains.");
+ }
+ await mutate();
+ return res.json();
+ });
+
+ toast.promise(promise, {
+ loading: "Saving ignored domains...",
+ success: "Ignored domains saved!",
+ error: (err) => err.message,
+ });
+
+ try {
+ await promise;
+ } finally {
+ setIsSaving(false);
+ }
+ };
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Ignored Domains for Notifications</CardTitle>
+ <CardDescription>
+ No one on the team will be notified when a visitor from these domains
+ views a link.
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <Textarea
+ className="focus:ring-inset"
+ rows={5}
+ placeholder={`Enter one domain per line, e.g.
+ value={domainsInput}
+ onChange={(e) => setDomainsInput(e.target.value)}
+ />
+ {invalidDomains.length > 0 && (
+ <p className="mt-2 text-sm text-destructive">
+ The following entries are not valid domains and will be ignored:{" "}
+ {invalidDomains.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 domains to prevent notifications from internal views.
+ </p>
+ <Button onClick={handleSave} loading={isSaving} disabled={saveDisabled}>
+ Save Changes
+ </Button>
+ </CardFooter>
+ </Card>
+ );
+}
diff --git a/lib/utils.ts b/lib/utils.ts
index 5b0767e5..2725c57f 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -568,15 +568,21 @@ export function decryptEncrpytedPassword(password: string): string {
return decrypted;
}
-export const sanitizeAllowDenyList = (list: string): string[] => {
+type FilterMode = "email" | "domain" | "both";
+
+export const sanitizeList = (list: string, mode: FilterMode = "both"): string[] => {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const domainRegex = /^@[^\s@]+\.[^\s@]+$/;
return list
.split("\n")
- .map((item) => item.trim().replace(/,$/, "").toLowerCase()) // Trim whitespace and remove trailing commas and lowercase
- .filter((item) => item !== "") // Remove empty items
- .filter((item) => emailRegex.test(item) || domainRegex.test(item)); // Remove items that don't match email or domain regex
+ .map((item) => item.trim().replace(/,$/, "").toLowerCase())
+ .filter((item) => item !== "")
+ .filter((item) => {
+ if (mode === "email") return emailRegex.test(item);
+ if (mode === "domain") return domainRegex.test(item);
+ return emailRegex.test(item) || domainRegex.test(item);
+ });
};
export function hexToRgb(hex: string) {
diff --git a/pages/api/jobs/send-notification.ts b/pages/api/jobs/send-notification.ts
index 30e7a9dc..9cc9ec89 100644
--- a/pages/api/jobs/send-notification.ts
+++ b/pages/api/jobs/send-notification.ts
@@ -117,6 +117,28 @@ export default async function handle(
? view.document!.teamId!
: view.dataroom!.teamId!;
+ if (view.viewerEmail) {
+ const viewerDomain = view.viewerEmail.split('@').pop();
+ if (viewerDomain) {
+ const ignoredDomainRecord = await prisma.ignoredDomain.findFirst({
+ where: {
+ teamId,
+ },
+ select: {
+ domains: true,
+ },
+ });
+
+ if (ignoredDomainRecord?.domains) {
+ const ignoredDomainList = ignoredDomainRecord.domains.map(d => d.startsWith('@') ? d.substring(1) : d);
+
+ if (ignoredDomainList.includes(viewerDomain)) {
+ return res.status(200).json({ message: "Notification skipped for ignored domain.", viewId });
+ }
+ }
+ }
+ }
+
// Get all active team members who are admins or managers to be notified
const users = await prisma.userTeam.findMany({
where: {
diff --git a/pages/api/teams/[teamId]/ignored-domains.ts b/pages/api/teams/[teamId]/ignored-domains.ts
new file mode 100644
index 00000000..7ee0251a
--- /dev/null
+++ b/pages/api/teams/[teamId]/ignored-domains.ts
@@ -0,0 +1,99 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { getServerSession } from "next-auth";
+
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+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") {
+ try {
+ const ignoredDomainRecord = await prisma.ignoredDomain.findFirst({
+ where: {
+ teamId,
+ },
+ });
+ return res.status(200).json(ignoredDomainRecord?.domains || []);
+ } catch (error) {
+ console.error(error);
+ return res.status(500).json({ error: "Internal server error" });
+ }
+ }
+
+ if (req.method === "PUT") {
+ try {
+ const { domains } = req.body;
+
+ if (!Array.isArray(domains)) {
+ return res.status(400).json({ error: "Invalid domains list" });
+ }
+
+ const uniqueDomains: string[] = [
+ ...new Set(
+ domains
+ .map((d: any) => (typeof d === "string" ? d.trim() : ""))
+ .filter(Boolean),
+ ),
+ ];
+
+ await prisma.$transaction([
+ prisma.ignoredDomain.deleteMany({ where: { teamId } }),
+ prisma.ignoredDomain.create({
+ data: {
+ teamId,
+ domains: uniqueDomains,
+ },
+ }),
+ ]);
+
+ return res.status(200).json({ message: "Ignored domains 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 ${req.method} not allowed` });
+}
+
+export default handler;
\ No newline at end of file
diff --git a/pages/settings/general.tsx b/pages/settings/general.tsx
index 2d7d0144..08d4b3dc 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 IgnoredDomainsForm from "@/components/settings/ignored-domains-form";
import { SettingsHeader } from "@/components/settings/settings-header";
import { Form } from "@/components/ui/form";
@@ -145,6 +146,7 @@ export default function General() {
handleSubmit={handleExcelAdvancedModeChange}
plan={(isFree && !isTrial) || isPro ? "Business" : undefined}
/>
+ <IgnoredDomainsForm />
<DeleteTeam />
</div>
diff --git a/prisma/migrations/20250709184916_add_ignored_domain_table/migration.sql b/prisma/migrations/20250709184916_add_ignored_domain_table/migration.sql
new file mode 100644
index 00000000..b515870c
--- /dev/null
+++ b/prisma/migrations/20250709184916_add_ignored_domain_table/migration.sql
@@ -0,0 +1,19 @@
+-- DropIndex
+DROP INDEX "Viewer_teamId_createdAt_idx";
+
+-- CreateTable
+CREATE TABLE "IgnoredDomain" (
+ "id" TEXT NOT NULL,
+ "domains" TEXT[] DEFAULT ARRAY[]::TEXT[],
+ "teamId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "IgnoredDomain_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE INDEX "IgnoredDomain_teamId_idx" ON "IgnoredDomain"("teamId");
+
+-- AddForeignKey
+ALTER TABLE "IgnoredDomain" ADD CONSTRAINT "IgnoredDomain_teamId_fkey" FOREIGN KEY ("teamId") REFERENCES "Team"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/prisma/schema/schema.prisma b/prisma/schema/schema.prisma
index 8a8242c1..dd6ae5ed 100644
--- a/prisma/schema/schema.prisma
+++ b/prisma/schema/schema.prisma
@@ -108,6 +108,20 @@ model Team {
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
Tag Tag[]
+
+ ignoredDomains IgnoredDomain[]
+}
+
+model IgnoredDomain {
+ id String @id @default(cuid())
+ domains String[] @default([])
+ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
+ teamId String
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([teamId])
}
model Brand {