Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add allowlist and denylist to links
Marc Seitzb5e0ebde7ffa
diff --git a/components/links/link-sheet/allow-list-section.tsx b/components/links/link-sheet/allow-list-section.tsxnew file mode 100644index 00000000..3d8c2459--- /dev/null+++ b/components/links/link-sheet/allow-list-section.tsx@@ -0,0 +1,88 @@+import { Dispatch, SetStateAction, useState, useEffect, ChangeEvent } from "react";+import { Switch } from "@/components/ui/switch";+import { motion } from "framer-motion";+import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";+import { cn, sanitizeAllowDenyList } from "@/lib/utils";+import { DEFAULT_LINK_TYPE } from ".";++export default function AllowListSection({+ data,+ setData,+}: {+ data: DEFAULT_LINK_TYPE;+ setData: Dispatch<SetStateAction<DEFAULT_LINK_TYPE>>;+}) {+ const { emailAuthenticated, allowList } = data;+ // Initialize enabled state based on whether allowList is not null and not empty+ const [enabled, setEnabled] = useState<boolean>(!!allowList && allowList.length > 0);+ const [allowListInput, setAllowListInput] = useState<string>(allowList?.join("\n") || "");++ useEffect(() => {+ // Update the allowList in the data state when their inputs change+ const newAllowList = sanitizeAllowDenyList(allowListInput);+ setEnabled((prevEnabled) => prevEnabled && emailAuthenticated);+ setData((prevData) => ({+ ...prevData,+ allowList: emailAuthenticated && enabled ? newAllowList : [],+ }));+ }, [allowListInput, enabled, emailAuthenticated, setData]);++ const handleEnableAllowList = () => {+ const updatedEnabled = !enabled;+ setEnabled(updatedEnabled);++ if (updatedEnabled) {+ setData((prevData) => ({+ ...prevData,+ allowList: updatedEnabled ? sanitizeAllowDenyList(allowListInput) : [],+ emailAuthenticated: true, // Turn on email authentication+ emailProtected: true // Turn on email protection+ }));+ } else {+ setData((prevData) => ({+ ...prevData,+ allowList: [],+ }));+ }+ };++ const handleAllowListChange = (event: ChangeEvent<HTMLTextAreaElement>) => {+ setAllowListInput(event.target.value);+ };+++ return (+ <div className="pb-5">+ <div className="flex flex-col space-y-4">+ <div className="flex items-center justify-between">+ <h2+ className={cn(+ "text-sm font-medium leading-6",+ enabled ? "text-foreground" : "text-muted-foreground",+ )}+ >+ Allow specified viewers+ </h2>+ <Switch+ checked={enabled}+ onCheckedChange={handleEnableAllowList}+ />+ </div>+ {enabled && (+ <motion.div+ className="mt-1 block w-full"+ {...FADE_IN_ANIMATION_SETTINGS}+ >+ <textarea+ className="form-textarea w-full rounded-md border-0 py-1.5 text-foreground bg-background shadow-sm ring-1 ring-inset ring-input placeholder:text-muted-foreground focus:ring-2 focus:ring-inset focus:ring-gray-400 text-sm leading-6"+ rows={5}+ placeholder="Enter allowed emails/domains, one per line, e.g. [email protected] @example.org"+ value={allowListInput}+ onChange={handleAllowListChange}+ />+ </motion.div>+ )}+ </div>+ </div>+ );+}diff --git a/components/links/link-sheet/deny-list-section.tsx b/components/links/link-sheet/deny-list-section.tsxnew file mode 100644index 00000000..d296cdd3--- /dev/null+++ b/components/links/link-sheet/deny-list-section.tsx@@ -0,0 +1,89 @@+import { Dispatch, SetStateAction, useState, useEffect, ChangeEvent } from "react";+import { Switch } from "@/components/ui/switch";+import { motion } from "framer-motion";+import { FADE_IN_ANIMATION_SETTINGS } from "@/lib/constants";+import { cn, sanitizeAllowDenyList } from "@/lib/utils";+import { DEFAULT_LINK_TYPE } from ".";++export default function DenyListSection({+ data,+ setData,+}: {+ data: DEFAULT_LINK_TYPE;+ setData: Dispatch<SetStateAction<DEFAULT_LINK_TYPE>>;+}) {+ const { emailAuthenticated, denyList } = data;+ // Initialize enabled state based on whether denyList is not null and not empty+ const [enabled, setEnabled] = useState<boolean>(!!denyList && denyList.length > 0);+ const [denyListInput, setDenyListInput] = useState<string>(denyList?.join("\n") || "");+++ useEffect(() => {+ // Update the denyList in the data state when their inputs change+ const newDenyList = sanitizeAllowDenyList(denyListInput);+ setEnabled((prevEnabled) => prevEnabled && emailAuthenticated);+ setData((prevData) => ({+ ...prevData,+ denyList: emailAuthenticated && enabled ? newDenyList : [],+ }));+ }, [denyListInput, enabled, emailAuthenticated, setData]);++ const handleEnableDenyList = () => {+ const updatedEnabled = !enabled;+ setEnabled(updatedEnabled);++ if (updatedEnabled) {+ setData((prevData) => ({+ ...prevData,+ denyList: updatedEnabled ? sanitizeAllowDenyList(denyListInput) : [],+ emailAuthenticated: true, // Turn on email authentication+ emailProtected: true // Turn on email protection+ }));+ } else {+ setData((prevData) => ({+ ...prevData,+ denyList: [],+ }));+ }+ };++ const handleDenyListChange = (event: ChangeEvent<HTMLTextAreaElement>) => {+ setDenyListInput(event.target.value);+ };+++ return (+ <div className="pb-5">+ <div className="flex flex-col space-y-4">+ <div className="flex items-center justify-between">+ <h2+ className={cn(+ "text-sm font-medium leading-6",+ enabled ? "text-foreground" : "text-muted-foreground",+ )}+ >+ Block specified viewers+ </h2>+ <Switch+ checked={enabled}+ onCheckedChange={handleEnableDenyList}+ />+ </div>+ {enabled && (+ <motion.div+ className="mt-1 block w-full"+ {...FADE_IN_ANIMATION_SETTINGS}+ >+ <textarea+ className="form-textarea w-full rounded-md border-0 py-1.5 text-foreground bg-background shadow-sm ring-1 ring-inset ring-input placeholder:text-muted-foreground focus:ring-2 focus:ring-inset focus:ring-gray-400 text-sm leading-6"+ rows={5}+ placeholder="Enter blocked emails/domains, one per line, e.g. [email protected] @example.org"+ value={denyListInput}+ onChange={handleDenyListChange}+ />+ </motion.div>+ )}+ </div>+ </div>+ );+}diff --git a/components/links/link-sheet/email-authentication-section.tsx b/components/links/link-sheet/email-authentication-section.tsxindex 080e93e6..ebe90ff3 100644--- a/components/links/link-sheet/email-authentication-section.tsx+++ b/components/links/link-sheet/email-authentication-section.tsx@@ -23,6 +23,8 @@ export default function EmailAuthenticationSection({...data,emailProtected: updatedEmailAuthentication ? true : emailProtected,emailAuthenticated: updatedEmailAuthentication,+ allowList: updatedEmailAuthentication ? data.allowList : [],+ denyList: updatedEmailAuthentication ? data.denyList : [],});setEnabled(updatedEmailAuthentication);};diff --git a/components/links/link-sheet/index.tsx b/components/links/link-sheet/index.tsxindex 63cee112..0fe0cffc 100644--- a/components/links/link-sheet/index.tsx+++ b/components/links/link-sheet/index.tsx@@ -27,6 +27,8 @@ import AllowNotificationSection from "./allow-notification-section";import FeedbackSection from "./feedback-section";import OGSection from "./og-section";import { ScrollArea } from "@/components/ui/scroll-area";+import AllowListSection from "./allow-list-section";+import DenyListSection from "./deny-list-section";export const DEFAULT_LINK_PROPS = {id: null,@@ -38,6 +40,8 @@ export const DEFAULT_LINK_PROPS = {emailProtected: true,emailAuthenticated: false,allowDownload: false,+ allowList: [],+ denyList: [],enableNotification: true,enableFeedback: true,enableCustomMetatag: false,@@ -56,6 +60,8 @@ export type DEFAULT_LINK_TYPE = {emailProtected: boolean;emailAuthenticated: boolean;allowDownload: boolean;+ allowList: string[];+ denyList: string[];enableNotification: boolean;enableFeedback: boolean;enableCustomMetatag: boolean; // metatags@@ -217,6 +223,8 @@ export default function LinkSheet({<div><EmailProtectionSection {...{ data, setData }} /><EmailAuthenticationSection {...{ data, setData }} />+ <AllowListSection {...{ data, setData }} />+ <DenyListSection {...{ data, setData }} /><AllowDownloadSection {...{ data, setData }} /><PasswordSection {...{ data, setData }} /><ExpirationSection {...{ data, setData }} />diff --git a/components/links/links-table.tsx b/components/links/links-table.tsxindex 4f3a0942..fb3c9985 100644--- a/components/links/links-table.tsx+++ b/components/links/links-table.tsx@@ -71,6 +71,8 @@ export default function LinksTable({emailProtected: link.emailProtected,emailAuthenticated: link.emailAuthenticated,allowDownload: link.allowDownload ? link.allowDownload : false,+ allowList: link.allowList,+ denyList: link.denyList,enableNotification: link.enableNotification? link.enableNotification: false,diff --git a/lib/utils.ts b/lib/utils.tsindex 268d3643..5d693749 100644--- a/lib/utils.ts+++ b/lib/utils.ts@@ -401,3 +401,14 @@ export const generateGravatarHash = (email: string | null): string => {return hash;};++export const sanitizeAllowDenyList = (list: string): string[] => {+ const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;+ const domainRegex = /^@[^\s@]+\.[^\s@]+$/;++ return list+ .split("\n")+ .map(item => item.trim().replace(/,$/, '')) // Trim whitespace and remove trailing commas+ .filter(item => item !== "") // Remove empty items+ .filter(item => emailRegex.test(item) || domainRegex.test(item)); // Remove items that don't match email or domain regex+ };\ No newline at end of filediff --git a/pages/api/links/[id]/index.ts b/pages/api/links/[id]/index.tsindex d383dbf4..e5baaea4 100644--- a/pages/api/links/[id]/index.ts+++ b/pages/api/links/[id]/index.ts@@ -153,6 +153,8 @@ export default async function handle(emailProtected: linkData.emailProtected,emailAuthenticated: linkData.emailAuthenticated,allowDownload: linkData.allowDownload,+ allowList: linkData.allowList,+ denyList: linkData.denyList,expiresAt: exat,domainId: domainObj?.id || null,domainSlug: domain || null,diff --git a/pages/api/links/index.ts b/pages/api/links/index.tsindex 8546dec6..ef375eae 100644--- a/pages/api/links/index.ts+++ b/pages/api/links/index.ts@@ -103,6 +103,8 @@ export default async function handler(metaTitle: linkData.metaTitle || null,metaDescription: linkData.metaDescription || null,metaImage: linkData.metaImage || null,+ allowList: linkData.allowList,+ denyList: linkData.denyList,},});diff --git a/pages/api/views.ts b/pages/api/views.tsindex 64531dae..baad69ed 100644--- a/pages/api/views.ts+++ b/pages/api/views.ts@@ -49,6 +49,8 @@ export default async function handle(password: true,domainSlug: true,slug: true,+ allowList: true,+ denyList: true,},});@@ -63,8 +65,6 @@ export default async function handle(res.status(400).json({ message: "Email is required." });return;}-- // You can implement more thorough email validation if required}// Check if password is required for visiting the link@@ -81,6 +81,40 @@ export default async function handle(}}+ // Check if email is allowed to visit the link+ if (link.allowList && link.allowList.length > 0) {+ // Extract the domain from the email address+ const emailDomain = email.substring(email.lastIndexOf("@"));++ // Determine if the email or its domain is allowed+ const isAllowed = link.allowList.some((allowed) => {+ return allowed === email || (allowed.startsWith("@") && emailDomain === allowed);+ });++ // Deny access if the email is not allowed+ if (!isAllowed) {+ res.status(403).json({ message: "Unauthorized access" });+ return;+ }+ }++ // Check if email is denied to visit the link+ if (link.denyList && link.denyList.length > 0) {+ // Extract the domain from the email address+ const emailDomain = email.substring(email.lastIndexOf("@"));++ // Determine if the email or its domain is denied+ const isDenied = link.denyList.some((denied) => {+ return denied === email || (denied.startsWith("@") && emailDomain === denied);+ });++ // Deny access if the email is denied+ if (isDenied) {+ res.status(403).json({ message: "Unauthorized access" });+ return;+ }+ }+// Check if email verification is required for visiting the linkif (link.emailAuthenticated && !token) {const token = newId("email");diff --git a/prisma/migrations/20240215035046_add_allow_deny_list_to_links/migration.sql b/prisma/migrations/20240215035046_add_allow_deny_list_to_links/migration.sqlnew file mode 100644index 00000000..258d0e60--- /dev/null+++ b/prisma/migrations/20240215035046_add_allow_deny_list_to_links/migration.sql@@ -0,0 +1,10 @@+/*+ Warnings:++ - You are about to drop the column `allowedEmails` on the `Link` table. All the data in the column will be lost.++*/+-- AlterTable+ALTER TABLE "Link" DROP COLUMN "allowedEmails",+ADD COLUMN "allowList" TEXT[],+ADD COLUMN "denyList" TEXT[];diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 793c7430..c78005d8 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -176,7 +176,8 @@ model Link {slug String? // Link slug for pretty URLsexpiresAt DateTime? // Optional expiration datepassword String? // Optional password for link protection- allowedEmails String[] // Array of emails allowed to view the document+ allowList String[] // Array of emails and domains allowed to view the document+ denyList String[] // Array of emails and domains denied to view the documentemailProtected Boolean @default(true) // Optional email protectionemailAuthenticated Boolean @default(false) // Optional email authentication flagallowDownload Boolean? @default(false) // Optional give user a option to allow to download the document