Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
Add custom privacy policy URL feature for teams on custom domains
Iuliia Shnaia7926ed697cf
diff --git a/components/view/access-form/index.tsx b/components/view/access-form/index.tsxindex 030a33cf..fd26878f 100644--- a/components/view/access-form/index.tsx+++ b/components/view/access-form/index.tsx@@ -93,6 +93,13 @@ export default function AccessForm({const { t } = useTranslation("access-form");const resolvedBrandLogo = resolveBrandLogo(brand);+ // The server only leaves this set when the override actually applies.+ const customPrivacyPolicyUrl =+ brand && "privacyPolicyUrl" in brand ? brand.privacyPolicyUrl : null;+ const privacyPolicyUrl =+ customPrivacyPolicyUrl ||+ `${process.env.NEXT_PUBLIC_MARKETING_URL}/privacy`;+const isSigningAgreement =signingProvider === "DOCUMENSO" || agreementContentType === "SIGNING";const isAgreementLocked = Boolean(@@ -297,7 +304,7 @@ export default function AccessForm({>{t("footer.seeHowWeProtect", "See how we protect your data in our")}{" "}<a- href={`${process.env.NEXT_PUBLIC_MARKETING_URL}/privacy`}+ href={privacyPolicyUrl}target="_blank"rel="noopener noreferrer"className="inline-flex items-center gap-0.5"diff --git a/lib/api/links/link-data.ts b/lib/api/links/link-data.tsindex edeb15bf..57d99dbe 100644--- a/lib/api/links/link-data.ts+++ b/lib/api/links/link-data.ts@@ -353,6 +353,7 @@ export async function fetchDataroomLinkData({viewerHeaderStyle: true,hideFolderIconsInMain: true,defaultLanguage: true,+ privacyPolicyUrl: true,},});@@ -399,6 +400,8 @@ export async function fetchDataroomLinkData({(dataroomBrand as any)?.defaultLanguage ??(teamBrand as any)?.defaultLanguage ??"en",+ // Team-level only; `processLinkData` strips it again when it doesn't apply.+ privacyPolicyUrl: (teamBrand as any)?.privacyPolicyUrl ?? null,};// Extract access controls from either ViewerGroup or PermissionGroup@@ -565,6 +568,7 @@ export async function fetchDataroomDocumentLinkData({viewerHeaderStyle: true,hideFolderIconsInMain: true,defaultLanguage: true,+ privacyPolicyUrl: true,},});@@ -607,6 +611,8 @@ export async function fetchDataroomDocumentLinkData({(dataroomBrand as any)?.defaultLanguage ??(teamBrand as any)?.defaultLanguage ??"en",+ // Team-level only; `processLinkData` strips it again when it doesn't apply.+ privacyPolicyUrl: (teamBrand as any)?.privacyPolicyUrl ?? null,};return { linkData, brand };@@ -666,6 +672,7 @@ export async function fetchDocumentLinkData({ctaLabel: true,ctaUrl: true,defaultLanguage: true,+ privacyPolicyUrl: true,},});@@ -677,6 +684,27 @@ export async function fetchDocumentLinkData({// Avoids internal HTTP fetch which can be blocked by Vercel edge (403 errors)// ============================================================================+// Strip the URL unless the override applies, so the viewer can treat a present+// value as "use it".+async function applyPrivacyPolicyUrlVisibility<+ T extends Record<string, any> | null,+>(+ brand: T,+ {+ teamId,+ isCustomDomain,+ }: { teamId?: string | null; isCustomDomain?: boolean },+): Promise<T> {+ if (!brand || !brand.privacyPolicyUrl) return brand;++ if (isCustomDomain && teamId) {+ const featureFlags = await getFeatureFlags({ teamId });+ if (featureFlags.customPrivacyUrl) return brand;+ }++ return { ...brand, privacyPolicyUrl: null };+}+/*** Core function to process link data after fetching the link record.* Handles all link types: DOCUMENT_LINK, DATAROOM_LINK, WORKFLOW_LINK@@ -709,9 +737,13 @@ async function processLinkData(brandColor: true,accentColor: true,defaultLanguage: true,+ privacyPolicyUrl: true,},});- brand = teamBrand;+ brand = await applyPrivacyPolicyUrlVisibility(teamBrand, {+ teamId: link.teamId,+ isCustomDomain,+ });}// For workflow links, return the link with minimal processing@@ -938,17 +970,21 @@ async function processLinkData(});}- let dataroomIndexEnabledForViewer: boolean | undefined;- if (linkType === "DATAROOM_LINK" && link.teamId) {- dataroomIndexEnabledForViewer = await resolveDataroomIndexEnabledForViewer({+ const [dataroomIndexEnabledForViewer, visibleBrand] = await Promise.all([+ linkType === "DATAROOM_LINK" && link.teamId+ ? resolveDataroomIndexEnabledForViewer({ teamId: link.teamId, teamPlan })+ : Promise.resolve(undefined),+ applyPrivacyPolicyUrlVisibility(brand, {teamId: link.teamId,- teamPlan,- });- }+ isCustomDomain,+ }),+ ]);// Serialize to convert Date objects to strings (required for Next.js getStaticProps)const serializedLink = JSON.parse(JSON.stringify(returnLink));- const serializedBrand = brand ? JSON.parse(JSON.stringify(brand)) : null;+ const serializedBrand = visibleBrand+ ? JSON.parse(JSON.stringify(visibleBrand))+ : null;return {status: "ok",diff --git a/lib/featureFlags/index.ts b/lib/featureFlags/index.tsindex eabb8aa4..c3055200 100644--- a/lib/featureFlags/index.ts+++ b/lib/featureFlags/index.ts@@ -22,10 +22,55 @@ export type BetaFeatures =| "requestList"| "logoOnAccessForm"| "htmlDocuments"- | "hideFooterOnAccessForm";+ | "hideFooterOnAccessForm"+ | "customPrivacyUrl";type BetaFeaturesRecord = Record<BetaFeatures, string[]>;+const BETA_FEATURES_TTL_MS = 10_000;++// On Vercel an Edge Config read hits a local filesystem replica, but everywhere+// else (localhost, CI) it is an HTTPS round trip, and a single page render can+// resolve flags three or four times. One cache entry covers every team because+// they all read the same `betaFeatures` payload.+let cachedBetaFeatures:+ | { value: BetaFeaturesRecord | undefined; expiresAt: number }+ | undefined;+let inFlightBetaFeatures: Promise<BetaFeaturesRecord | undefined> | undefined;++async function fetchBetaFeatures(): Promise<BetaFeaturesRecord | undefined> {+ try {+ return await get<BetaFeaturesRecord>("betaFeatures");+ } catch (e) {+ const msg = e instanceof Error ? e.message : String(e);+ // Invalid or local EDGE_CONFIG tokens surface as Unauthorized; flags stay off.+ if (msg.includes("Unauthorized") || msg.includes("403")) {+ console.warn(+ "[featureFlags] Edge Config unavailable; beta flags default to off. Fix EDGE_CONFIG or unset it for local dev.",+ );+ } else {+ console.error(`Error getting beta features: ${e}`);+ }+ return undefined;+ }+}++// Failures are cached too, so a broken Edge Config degrades to "all flags off"+// instead of one failed round trip per call.+async function readBetaFeatures(): Promise<BetaFeaturesRecord | undefined> {+ if (cachedBetaFeatures && cachedBetaFeatures.expiresAt > Date.now()) {+ return cachedBetaFeatures.value;+ }++ inFlightBetaFeatures ??= fetchBetaFeatures().then((value) => {+ cachedBetaFeatures = { value, expiresAt: Date.now() + BETA_FEATURES_TTL_MS };+ inFlightBetaFeatures = undefined;+ return value;+ });++ return inFlightBetaFeatures;+}+export const getFeatureFlags = async ({ teamId }: { teamId?: string }) => {const teamFeatures: Record<BetaFeatures, boolean> = {tokens: false,@@ -50,6 +95,7 @@ export const getFeatureFlags = async ({ teamId }: { teamId?: string }) => {logoOnAccessForm: false,htmlDocuments: false,hideFooterOnAccessForm: false,+ customPrivacyUrl: false,};// Return all features as false if edge config is not available@@ -61,21 +107,7 @@ export const getFeatureFlags = async ({ teamId }: { teamId?: string }) => {return teamFeatures;}- let betaFeatures: BetaFeaturesRecord | undefined = undefined;-- try {- betaFeatures = await get("betaFeatures");- } catch (e) {- const msg = e instanceof Error ? e.message : String(e);- // Invalid or local EDGE_CONFIG tokens surface as Unauthorized; flags stay off.- if (msg.includes("Unauthorized") || msg.includes("403")) {- console.warn(- "[featureFlags] Edge Config unavailable; beta flags default to off. Fix EDGE_CONFIG or unset it for local dev.",- );- } else {- console.error(`Error getting beta features: ${e}`);- }- }+ const betaFeatures = await readBetaFeatures();if (betaFeatures) {for (const [featureFlag, teamIds] of Object.entries(betaFeatures)) {diff --git a/pages/api/teams/[teamId]/branding.ts b/pages/api/teams/[teamId]/branding.tsindex 6dcb6e7b..960f3651 100644--- a/pages/api/teams/[teamId]/branding.ts+++ b/pages/api/teams/[teamId]/branding.ts@@ -18,6 +18,7 @@ import {} from "@/lib/billing/team-plan-custom-messaging";import { validateRedirectUrl } from "@/lib/api/domains/validate-redirect-url";import { errorhandler } from "@/lib/errorHandler";+import { getFeatureFlags } from "@/lib/featureFlags";import prisma from "@/lib/prisma";import {clearCachedBrandLogo,@@ -43,6 +44,7 @@ const updateBrandingSchema = z.object({linkPreviewFavicon: z.string().nullable().optional(),ctaLabel: z.string().nullable().optional(),ctaUrl: z.string().nullable().optional(),+ privacyPolicyUrl: z.string().nullable().optional(),cardLayout: DataroomCardLayoutSchema.optional(),showFolderTree: z.boolean().optional(),viewerLayoutPreset: DataroomViewerLayoutPresetSchema.optional(),@@ -94,6 +96,34 @@ function sanitizeLayoutPayload(input: LayoutPayload): LayoutPayload {return out;}+// Returns `undefined` to leave the stored value untouched (Prisma skips it).+async function resolvePrivacyPolicyUrl(+ teamId: string,+ value: string | null | undefined,+): Promise<+ { ok: true; url: string | null | undefined } | { ok: false; message: string }+> {+ const featureFlags = await getFeatureFlags({ teamId });+ if (!featureFlags.customPrivacyUrl || value === undefined) {+ return { ok: true, url: undefined };+ }++ const trimmed = value?.trim() ?? "";+ if (!trimmed) {+ return { ok: true, url: null };+ }++ const validation = await validateRedirectUrl(trimmed, teamId);+ if (!validation.valid) {+ return {+ ok: false,+ message: validation.message.replace("Redirect URL", "Privacy policy URL"),+ };+ }++ return { ok: true, url: validation.url || null };+}+function maybeDeleteBlobAsset(url: string | null | undefined): Promise<void> {if (!url || url === "no-banner") return Promise.resolve();if (url.startsWith("/") || url.startsWith("data:")) return Promise.resolve();@@ -196,6 +226,14 @@ export default async function handle(validatedCtaUrl = ctaValidation.url;}+ const privacyPolicy = await resolvePrivacyPolicyUrl(+ teamId,+ body.privacyPolicyUrl,+ );+ if (!privacyPolicy.ok) {+ return res.status(400).json({ message: privacyPolicy.message });+ }+// Use upsert so POST is idempotent: clients can hit POST even when a// Brand row already exists (e.g. SWR cache is stale and `brand` is// falsy on the client) without tripping the unique-teamId constraint.@@ -228,6 +266,7 @@ export default async function handle(: undefined,ctaLabel: messagingAllowed ? body.ctaLabel ?? undefined : undefined,ctaUrl: messagingAllowed ? validatedCtaUrl ?? undefined : undefined,+ privacyPolicyUrl: privacyPolicy.url ?? undefined,...layoutData,teamId: teamId,},@@ -241,6 +280,7 @@ export default async function handle(applyAccentColorToDataroomView:body.applyAccentColorToDataroomView ?? false,welcomeMessage: messagingAllowed ? body.welcomeMessage ?? null : undefined,+ privacyPolicyUrl: privacyPolicy.url,customLinkPreviewEnabled: messagingAllowed? body.customLinkPreviewEnabled: undefined,@@ -300,6 +340,14 @@ export default async function handle(validatedCtaUrl = ctaValidation.url;}+ const privacyPolicy = await resolvePrivacyPolicyUrl(+ teamId,+ body.privacyPolicyUrl,+ );+ if (!privacyPolicy.ok) {+ return res.status(400).json({ message: privacyPolicy.message });+ }+const resolvedWelcome = messagingAllowed? body.welcomeMessage ?? null: (existingBrand?.welcomeMessage ?? null);@@ -350,6 +398,7 @@ export default async function handle(: undefined,ctaLabel: messagingAllowed ? body.ctaLabel ?? undefined : undefined,ctaUrl: messagingAllowed ? validatedCtaUrl ?? undefined : undefined,+ privacyPolicyUrl: privacyPolicy.url ?? undefined,...layoutData,teamId: teamId,},@@ -362,6 +411,7 @@ export default async function handle(accentButtonColor: body.accentButtonColor ?? null,applyAccentColorToDataroomView: !!body.applyAccentColorToDataroomView,welcomeMessage: resolvedWelcome,+ privacyPolicyUrl: privacyPolicy.url,// Preserve stored link-preview settings on partial PUTs: only write// these fields when they're explicitly present in the payload.// Prisma skips updates for `undefined` values. Plans without messagingdiff --git a/pages/branding.tsx b/pages/branding.tsxindex 92f2d496..fa0f2f1f 100644--- a/pages/branding.tsx+++ b/pages/branding.tsx@@ -29,6 +29,7 @@ import { toast } from "sonner";import { mutate } from "swr";import { useDebounce } from "use-debounce";+import { useFeatureFlags } from "@/lib/hooks/use-feature-flags";import { usePlan } from "@/lib/swr/use-billing";import { useBrand } from "@/lib/swr/use-brand";import { cn, convertDataUrlToFile, uploadImage } from "@/lib/utils";@@ -59,6 +60,8 @@ export default function Branding() {const teamInfo = useTeam();const { brand } = useBrand();const { plan, isTrial, isBusiness, isDatarooms, isDataroomsPlus } = usePlan();+ const { isFeatureEnabled } = useFeatureFlags();+ const customPrivacyUrlEnabled = isFeatureEnabled("customPrivacyUrl");const [brandColor, setBrandColor] = useState<string>("#000000");const [accentColor, setAccentColor] = useState<string>("#030712");@@ -105,6 +108,13 @@ export default function Branding() {null,);+ const [privacyPolicyEnabled, setPrivacyPolicyEnabled] =+ useState<boolean>(false);+ const [privacyPolicyUrl, setPrivacyPolicyUrl] = useState<string>("");+ const [privacyPolicyUrlError, setPrivacyPolicyUrlError] = useState<+ string | null+ >(null);+// Auto-fill from website (brand lookup)const [autoFillUrl, setAutoFillUrl] = useState<string>("");const [autoFillLoading, setAutoFillLoading] = useState<boolean>(false);@@ -368,6 +378,10 @@ export default function Branding() {setCtaLabel(initialCtaLabel);setCtaUrl(initialCtaUrl);setCtaEnabled(!!(initialCtaLabel || initialCtaUrl));+ const initialPrivacyPolicyUrl = (brand as any)?.privacyPolicyUrl ?? "";+ setPrivacyPolicyUrl(initialPrivacyPolicyUrl);+ setPrivacyPolicyEnabled(!!initialPrivacyPolicyUrl);+ setPrivacyPolicyUrlError(null);const savedMessage = brand.welcomeMessage ?? null;const message = savedMessage || DEFAULT_WELCOME_MESSAGE;setWelcomeMessage(message);@@ -414,6 +428,9 @@ export default function Branding() {setCtaEnabled(false);setCtaLabel("");setCtaUrl("");+ setPrivacyPolicyEnabled(false);+ setPrivacyPolicyUrl("");+ setPrivacyPolicyUrlError(null);setWelcomeMessage(DEFAULT_WELCOME_MESSAGE);setWelcomeEnabled(false);setWelcomeMessageError(null);@@ -434,6 +451,32 @@ export default function Branding() {};}, [brand]);+ // Mirrors the server-side check in `validateRedirectUrl`: HTTPS only.+ const validatePrivacyPolicyUrl = (url: string): string | null => {+ const trimmed = url.trim();+ if (!trimmed) return "Privacy policy URL cannot be empty";++ let parsed: URL;+ try {+ parsed = new URL(trimmed);+ } catch {+ return "Enter a valid URL, e.g. https://example.com/privacy";+ }++ if (parsed.protocol !== "https:") {+ return "Privacy policy URL must use HTTPS";+ }++ return null;+ };++ const handlePrivacyPolicyUrlChange = (value: string) => {+ setPrivacyPolicyUrl(value);+ setPrivacyPolicyUrlError(+ value.trim() ? validatePrivacyPolicyUrl(value) : null,+ );+ };+// Handle welcome message change with validationconst handleWelcomeMessageChange = (value: string) => {setWelcomeMessage(value);@@ -462,6 +505,15 @@ export default function Branding() {}}+ if (customPrivacyUrlEnabled && privacyPolicyEnabled) {+ const privacyError = validatePrivacyPolicyUrl(privacyPolicyUrl);+ if (privacyError) {+ setPrivacyPolicyUrlError(privacyError);+ toast.error("Please fix the validation errors before saving");+ return;+ }+ }+setIsLoading(true);let logoBlobUrl: string | null =logo && logo.startsWith("data:") ? null : logo;@@ -528,6 +580,11 @@ export default function Branding() {? ctaUrl.trim() || null: null: ((brand as any)?.ctaUrl ?? null),+ ...(customPrivacyUrlEnabled && {+ privacyPolicyUrl: privacyPolicyEnabled+ ? privacyPolicyUrl.trim() || null+ : null,+ }),// Custom Link Preview — only writable when the team plan grants the// Business messaging tier. Otherwise we mirror back what's already// persisted so the API doesn't clear it out from a lower tier.@@ -624,6 +681,9 @@ export default function Branding() {setCtaEnabled(false);setCtaLabel("");setCtaUrl("");+ setPrivacyPolicyEnabled(false);+ setPrivacyPolicyUrl("");+ setPrivacyPolicyUrlError(null);setApplyAccentColorToDataroomView(false);setWelcomeMessage(DEFAULT_WELCOME_MESSAGE);setWelcomeEnabled(false);@@ -1482,6 +1542,74 @@ export default function Branding() {)}</CardContent></Card>++ {customPrivacyUrlEnabled && (+ <Card>+ <CardContent className="pt-6">+ <div className="space-y-3">+ <div className="flex items-center justify-between">+ <div className="flex flex-col">+ <Label htmlFor="privacy-policy-enabled">+ Custom Privacy Policy+ </Label>+ <p className="mt-1 text-xs text-muted-foreground">+ Link visitors to your own privacy policy at+ the bottom of the access screen instead of+ Papermark's.+ </p>+ </div>+ <Switch+ id="privacy-policy-enabled"+ checked={privacyPolicyEnabled}+ onCheckedChange={(checked) => {+ setPrivacyPolicyEnabled(checked);+ if (!checked) {+ setPrivacyPolicyUrlError(null);+ }+ }}+ />+ </div>+ {privacyPolicyEnabled && (+ <div className="space-y-2 border-t pt-4">+ <Label htmlFor="privacy-policy-url">+ Privacy policy URL+ </Label>+ <Input+ id="privacy-policy-url"+ placeholder="https://example.com/privacy"+ value={privacyPolicyUrl}+ onChange={(e) =>+ handlePrivacyPolicyUrlChange(+ e.target.value,+ )+ }+ className={cn(+ privacyPolicyUrlError &&+ "border-red-500 focus:border-red-500 focus:ring-red-500",+ )}+ />+ {privacyPolicyUrlError && (+ <p className="text-xs text-red-500">+ {privacyPolicyUrlError}+ </p>+ )}+ <p className="text-xs text-muted-foreground">+ Only applies to links shared on a{" "}+ <Link+ href="/settings/domains"+ className="underline underline-offset-4"+ >+ custom domain+ </Link>+ . Links on papermark.com keep the default+ privacy policy.+ </p>+ </div>+ )}+ </div>+ </CardContent>+ </Card>+ )}</div></CollapsibleBrandingSection></FadeScrollArea>@@ -1601,7 +1729,12 @@ export default function Branding() {<ButtononClick={saveBranding}loading={isLoading}- disabled={hasBusinessMessagingAccess && !!welcomeMessageError}+ disabled={+ (hasBusinessMessagingAccess && !!welcomeMessageError) ||+ (customPrivacyUrlEnabled &&+ privacyPolicyEnabled &&+ !!privacyPolicyUrlError)+ }className="bg-black text-white hover:bg-gray-800">Save changesdiff --git a/prisma/migrations/20260802000000_add_brand_privacy_policy_url/migration.sql b/prisma/migrations/20260802000000_add_brand_privacy_policy_url/migration.sqlnew file mode 100644index 00000000..bbcf92b2--- /dev/null+++ b/prisma/migrations/20260802000000_add_brand_privacy_policy_url/migration.sql@@ -0,0 +1,2 @@+-- AlterTable+ALTER TABLE "Brand" ADD COLUMN "privacyPolicyUrl" TEXT;diff --git a/prisma/schema/schema.prisma b/prisma/schema/schema.prismaindex 41fd3e36..386df8d8 100644--- a/prisma/schema/schema.prisma+++ b/prisma/schema/schema.prisma@@ -97,6 +97,7 @@ model Brand {welcomeMessage String? // This should be a reference to the welcome messagectaLabel String? // Default CTA button label (inherited by datarooms unless overridden)ctaUrl String? // Default CTA button URL (inherited by datarooms unless overridden)+ privacyPolicyUrl String? // Access screen privacy link, custom domains onlycardLayout String @default("LIST")showFolderTree Boolean @default(true)