Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
Let per-link allow lists override the global block list
Marc Seitzb1e949427164
diff --git a/app/api/views-dataroom/route.ts b/app/api/views-dataroom/route.tsindex 4d6d98fb..b4e2dfef 100644--- a/app/api/views-dataroom/route.ts+++ b/app/api/views-dataroom/route.ts@@ -43,12 +43,11 @@ import { CustomUser, WatermarkConfigSchema } from "@/lib/types";import { checkPassword, decryptEncrpytedPassword, log } from "@/lib/utils";import {extractEmailDomain,- isEmailMatched,normalizeGroupDomain,} 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 { checkViewerEmailAccess } from "@/lib/utils/global-block-list";import { resolveHtmlContentForRender } from "@/lib/utils/html-document";import { validateEmail } from "@/lib/utils/validate-email";@@ -159,6 +158,13 @@ export async function POST(request: NextRequest) {enableWatermark: true,watermarkConfig: true,groupId: true,+ group: {+ select: {+ members: { include: { viewer: { select: { email: true } } } },+ domains: true,+ allowAll: true,+ },+ },permissionGroupId: true,audienceType: true,allowDownload: true,@@ -442,66 +448,80 @@ export async function POST(request: NextRequest) {}}- // Check global block list first - this overrides all other access controls- const globalBlockCheck = checkGlobalBlockList(- effectiveEmail ?? undefined,- link.team?.globalBlockList,- );- if (globalBlockCheck.error) {+ // Allow list and viewer-group audience override the team-wide global+ // block list. Per-link deny list still applies after.+ const isGroupAudience =+ link.audienceType === LinkAudienceType.GROUP && !!link.groupId;+ if (isGroupAudience && !link.group) {return NextResponse.json(- { message: globalBlockCheck.error },- { status: 400 },- );- }- if (globalBlockCheck.isBlocked) {- waitUntil(- reportDeniedAccessAttempt(link, effectiveEmail ?? "", "global"),+ { message: "Group not found." },+ { status: 404 },);-- return NextResponse.json({ message: "Access denied" }, { status: 403 });}- // Build combined allow list from individual emails + visitor groups+ const viewerGroup = isGroupAudience ? link.group : null;const visitorGroupEmails =link.visitorGroups?.flatMap((vg) => vg.visitorGroup.emails) || [];- const combinedAllowList = [- ...(link.allowList || []),- ...visitorGroupEmails,- ];-- // Check if email is allowed to visit the link- if (combinedAllowList.length > 0) {- // Determine if the email or its domain is allowed- const isAllowed = combinedAllowList.some((allowed) =>- isEmailMatched(effectiveEmail ?? "", allowed),- );-- // Deny access if the email is not allowed- if (!isAllowed) {- waitUntil(- reportDeniedAccessAttempt(link, effectiveEmail ?? "", "allow"),- );-+ const viewerGroupAllowEntries =+ viewerGroup && !viewerGroup.allowAll+ ? [+ ...viewerGroup.members.map((member) => member.viewer.email),+ ...viewerGroup.domains,+ ]+ : [];+ const emailAccess = checkViewerEmailAccess({+ email: effectiveEmail ?? undefined,+ allowList: [+ ...(link.allowList || []),+ ...visitorGroupEmails,+ ...viewerGroupAllowEntries,+ ],+ denyList: link.denyList,+ globalBlockList: link.team?.globalBlockList,+ });+ if (emailAccess.denied) {+ if (emailAccess.error) {return NextResponse.json(- { message: "Unauthorized access" },- { status: 403 },+ { message: emailAccess.error },+ { status: 400 },);}++ waitUntil(+ reportDeniedAccessAttempt(+ link,+ effectiveEmail ?? "",+ emailAccess.reason,+ ),+ );++ return NextResponse.json(+ {+ message:+ emailAccess.reason === "global"+ ? "Access denied"+ : "Unauthorized access",+ },+ { status: 403 },+ );}- // Check if email is denied to visit the link- if (link.denyList && link.denyList.length > 0) {- // Determine if the email or its domain is denied- const isDenied = link.denyList.some((denied) =>- isEmailMatched(effectiveEmail ?? "", denied),+ if (viewerGroup && !viewerGroup.allowAll) {+ const isMember = viewerGroup.members.some(+ (member) => member.viewer.email === effectiveEmail,);- // Deny access if the email is denied- if (isDenied) {+ const emailDomain = extractEmailDomain(effectiveEmail ?? "");+ const hasDomainAccess = emailDomain+ ? viewerGroup.domains.some(+ (domain) => normalizeGroupDomain(domain) === emailDomain,+ )+ : false;++ if (!isMember && !hasDomainAccess) {waitUntil(- reportDeniedAccessAttempt(link, effectiveEmail ?? "", "deny"),+ reportDeniedAccessAttempt(link, effectiveEmail ?? "", "allow"),);-return NextResponse.json({ message: "Unauthorized access" },{ status: 403 },@@ -509,55 +529,6 @@ export async function POST(request: NextRequest) {}}- // Check if group is allowed to visit the link- if (link.audienceType === LinkAudienceType.GROUP && link.groupId) {- const group = await prisma.viewerGroup.findUnique({- where: { id: link.groupId },- select: {- members: { include: { viewer: { select: { email: true } } } },- domains: true,- allowAll: true,- },- });-- if (!group) {- return NextResponse.json(- { message: "Group not found." },- { status: 404 },- );- }-- // Check if all emails are allowed- if (group.allowAll) {- // Allow access- } else {- // Check individual membership- const isMember = group.members.some(- (member) => member.viewer.email === effectiveEmail,- );-- // Extract domain from email (canonical "@acme.com" form)- const emailDomain = extractEmailDomain(effectiveEmail ?? "");- // Check domain access. Normalize each stored domain so bare-domain- // rows (e.g. created before domain normalization) still match.- const hasDomainAccess = emailDomain- ? group.domains.some(- (domain) => normalizeGroupDomain(domain) === emailDomain,- )- : false;-- if (!isMember && !hasDomainAccess) {- waitUntil(- reportDeniedAccessAttempt(link, effectiveEmail ?? "", "allow"),- );- return NextResponse.json(- { message: "Unauthorized access" },- { 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/app/api/views/route.ts b/app/api/views/route.tsindex 3356c9ef..172125fc 100644--- a/app/api/views/route.ts+++ b/app/api/views/route.ts@@ -39,10 +39,9 @@ import {import { recordLinkView } from "@/lib/tracking/record-link-view";import { CustomUser, WatermarkConfigSchema } from "@/lib/types";import { checkPassword, decryptEncrpytedPassword, log } from "@/lib/utils";-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 { checkViewerEmailAccess } from "@/lib/utils/global-block-list";import { resolveHtmlContentForRender } from "@/lib/utils/html-document";import { validateEmail } from "@/lib/utils/validate-email";@@ -399,71 +398,41 @@ export async function POST(request: NextRequest) {}}- // Check global block list first - this overrides all other access controls- const globalBlockCheck = checkGlobalBlockList(- effectiveEmail ?? undefined,- link.team?.globalBlockList,- );- if (globalBlockCheck.error) {- return NextResponse.json(- { message: globalBlockCheck.error },- { status: 400 },- );- }- if (globalBlockCheck.isBlocked) {- waitUntil(- reportDeniedAccessAttempt(link, effectiveEmail ?? "", "global"),- );-- return NextResponse.json({ message: "Access denied" }, { status: 403 });- }-- // Build combined allow list from individual emails + visitor groups+ // Allow list is checked first so a per-link allow can override the+ // team-wide global block list. Per-link deny list still applies after.const visitorGroupEmails =link.visitorGroups?.flatMap((vg) => vg.visitorGroup.emails) || [];- const combinedAllowList = [- ...(link.allowList || []),- ...visitorGroupEmails,- ];-- // Check if email is allowed to visit the link- if (combinedAllowList.length > 0) {- // Determine if the email or its domain is allowed- const isAllowed = combinedAllowList.some((allowed) =>- isEmailMatched(effectiveEmail ?? "", allowed),- );-- // Deny access if the email is not allowed- if (!isAllowed) {- waitUntil(- reportDeniedAccessAttempt(link, effectiveEmail ?? "", "allow"),- );-+ const emailAccess = checkViewerEmailAccess({+ email: effectiveEmail ?? undefined,+ allowList: [...(link.allowList || []), ...visitorGroupEmails],+ denyList: link.denyList,+ globalBlockList: link.team?.globalBlockList,+ });+ if (emailAccess.denied) {+ if (emailAccess.error) {return NextResponse.json(- { message: "Unauthorized access" },- { status: 403 },+ { message: emailAccess.error },+ { status: 400 },);}- }- // Check if email is denied to visit the link- if (link.denyList && link.denyList.length > 0) {- // Determine if the email or its domain is denied- const isDenied = link.denyList.some((denied) =>- isEmailMatched(effectiveEmail ?? "", denied),+ waitUntil(+ reportDeniedAccessAttempt(+ link,+ effectiveEmail ?? "",+ emailAccess.reason,+ ),);- // Deny access if the email is denied- if (isDenied) {- waitUntil(- reportDeniedAccessAttempt(link, effectiveEmail ?? "", "deny"),- );-- return NextResponse.json(- { message: "Unauthorized access" },- { status: 403 },- );- }+ return NextResponse.json(+ {+ message:+ emailAccess.reason === "global"+ ? "Access denied"+ : "Unauthorized access",+ },+ { status: 403 },+ );}// Request OTP Code for email verification ifdiff --git a/components/settings/global-block-list-form.tsx b/components/settings/global-block-list-form.tsxindex d82f2c87..713bbf55 100644--- a/components/settings/global-block-list-form.tsx+++ b/components/settings/global-block-list-form.tsx@@ -86,8 +86,9 @@ export default function GlobalBlockListForm() {<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.+ <b>blocked from all links</b> in your team, unless a link's allow+ list explicitly includes them. Use <code>@domain.com</code> for+ domains or full email addresses.</CardDescription></CardHeader><CardContent>diff --git a/lib/api/visitors/get-visitors.ts b/lib/api/visitors/get-visitors.tsindex af3cb2c8..cbea60b1 100644--- a/lib/api/visitors/get-visitors.ts+++ b/lib/api/visitors/get-visitors.ts@@ -66,7 +66,6 @@ type RawVisitorRow = {invitedAt: Date | null;invitationStatus: string | null;accessSources: VisitorAccessSource[] | null;- globallyBlocked: boolean | null;createdAt: Date | null;updatedAt: Date | null;totalCount: number;@@ -165,7 +164,6 @@ export async function getVisitors({email,status,pauseStartsAt,- globalBlockList,}: {teamId: string;dataroomId?: string;@@ -178,7 +176,6 @@ export async function getVisitors({email?: string;status?: string;pauseStartsAt?: Date | null;- globalBlockList?: string[];}) {const currentPage = Math.max(page, 1);const limit = Math.min(Math.max(pageSize, 1), 100);@@ -224,22 +221,6 @@ export async function getVisitors({NULL::text AS source_id, NULL::text AS source_dataroom_idWHERE FALSE`;- // The team-wide block list applies everywhere, so it only ever flags people- // who already surfaced through another source — it never adds rows of its own.- const blockEntries = Array.from(- new Set(- (globalBlockList ?? [])- .map((entry) => entry.trim().toLowerCase())- .filter(Boolean),- ),- );- const globalBlockFilter = blockEntries.length- ? Prisma.sql`EXISTS (- SELECT 1 FROM UNNEST(ARRAY[${Prisma.join(blockEntries)}]::text[]) AS b- WHERE p.email_key = b OR (b LIKE '@%' AND p.email_key LIKE '%' || b)- )`- : Prisma.sql`FALSE`;-// Views the stats are built from. Dataroom scope counts room sessions and// in-room document views; team scope keeps the historical document-view// definition of "total views" so existing numbers do not shift.@@ -467,14 +448,13 @@ export async function getVisitors({ln."viewerName" AS "viewerName",COALESCE(v.verified, false) AS verified,CASE- WHEN COALESCE(aa.has_deny, false) OR ${globalBlockFilter} THEN 'BLOCKED'+ WHEN COALESCE(aa.has_deny, false) THEN 'BLOCKED'WHEN COALESCE(vs."allViews", 0) > 0 THEN 'VISITED'WHEN ia.email_key IS NOT NULL ${invitedFallback} THEN 'INVITED'WHEN COALESCE(aa.has_access, false) THEN 'ALLOWED'WHEN COALESCE(aa.has_assignment, false) THEN 'ASSIGNED'ELSE 'NONE'END AS status,- ${globalBlockFilter} AS "globallyBlocked",COALESCE(vs."totalVisits", 0) AS "totalVisits",COALESCE(vs."documentViews", 0) AS "documentViews",COALESCE(vs."downloads", 0) AS "downloads",@@ -601,22 +581,12 @@ export async function getVisitors({lastViewed: row.lastViewed,invitedAt: row.invitedAt,invitationStatus: row.invitationStatus,- accessSources: [- ...(row.accessSources ?? []).map((source) => ({- type: source.type as VisitorAccessSource["type"],- name: source.name,- id: source.id ?? null,- dataroomId: source.dataroomId ?? null,- })),- ...(row.globallyBlocked- ? [- {- type: "BLOCK_LIST" as const,- name: "Team block list",- },- ]- : []),- ],+ accessSources: (row.accessSources ?? []).map((source) => ({+ type: source.type as VisitorAccessSource["type"],+ name: source.name,+ id: source.id ?? null,+ dataroomId: source.dataroomId ?? null,+ })),createdAt: row.createdAt,updatedAt: row.updatedAt,}));diff --git a/lib/utils/global-block-list.ts b/lib/utils/global-block-list.tsindex 0a948444..afe11129 100644--- a/lib/utils/global-block-list.ts+++ b/lib/utils/global-block-list.ts@@ -22,3 +22,57 @@ export function checkGlobalBlockList(return { isBlocked };}++export type EmailAccessDenial = "allow" | "global" | "deny";++export type EmailAccessResult =+ | { denied: false }+ | { denied: true; reason: EmailAccessDenial; error?: string };++/**+ * Allow list is evaluated first and overrides the team-wide global block list,+ * so an explicit per-link allow (e.g. [email protected]) can admit a visitor even+ * when their domain is blocked globally (e.g. @gmail.com). Per-link deny list+ * still applies after that.+ */+export function checkViewerEmailAccess({+ email,+ allowList,+ denyList,+ globalBlockList,+}: {+ email: string | undefined;+ allowList?: string[];+ denyList?: string[];+ globalBlockList?: string[];+}): EmailAccessResult {+ const combinedAllowList = allowList ?? [];+ const isOnAllowList =+ combinedAllowList.length > 0 &&+ combinedAllowList.some((entry) => isEmailMatched(email ?? "", entry));++ if (combinedAllowList.length > 0 && !isOnAllowList) {+ return { denied: true, reason: "allow" };+ }++ if (!isOnAllowList) {+ const globalBlockCheck = checkGlobalBlockList(email, globalBlockList);+ if (globalBlockCheck.error) {+ return { denied: true, reason: "global", error: globalBlockCheck.error };+ }+ if (globalBlockCheck.isBlocked) {+ return { denied: true, reason: "global" };+ }+ }++ if (denyList && denyList.length > 0) {+ const isDenied = denyList.some((denied) =>+ isEmailMatched(email ?? "", denied),+ );+ if (isDenied) {+ return { denied: true, reason: "deny" };+ }+ }++ return { denied: false };+}diff --git a/pages/api/teams/[teamId]/datarooms/[id]/visitors/index.ts b/pages/api/teams/[teamId]/datarooms/[id]/visitors/index.tsindex 47a4751b..d4ca0656 100644--- a/pages/api/teams/[teamId]/datarooms/[id]/visitors/index.ts+++ b/pages/api/teams/[teamId]/datarooms/[id]/visitors/index.ts@@ -55,7 +55,7 @@ export default async function handle(some: { userId },},},- select: { id: true, pauseStartsAt: true, globalBlockList: true },+ select: { id: true, pauseStartsAt: true },});if (!team) {@@ -81,7 +81,6 @@ export default async function handle(query,status,pauseStartsAt: team.pauseStartsAt,- globalBlockList: team.globalBlockList,});const viewerIds = visitorsdiff --git a/pages/api/teams/[teamId]/viewers/index.ts b/pages/api/teams/[teamId]/viewers/index.tsindex 93f26b72..f58f2095 100644--- a/pages/api/teams/[teamId]/viewers/index.ts+++ b/pages/api/teams/[teamId]/viewers/index.ts@@ -43,7 +43,7 @@ export default async function handle(},},},- select: { id: true, plan: true, globalBlockList: true },+ select: { id: true, plan: true },});if (!team || team.plan === "free") {@@ -58,7 +58,6 @@ export default async function handle(sortOrder,query,status,- globalBlockList: team.globalBlockList,});// Per-team data behind auth: never let shared/CDN caches store it, or a