Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
fix: harden root domain redirects - validation, plan gating, cleanup
Cursor Agent7b927cf43b5d
diff --git a/components/domains/domain-card.tsx b/components/domains/domain-card.tsxindex 3b729eb4..56525095 100644--- a/components/domains/domain-card.tsx+++ b/components/domains/domain-card.tsx@@ -37,11 +37,13 @@ export default function DomainCard({domain,isDefault,redirectUrl: initialRedirectUrl,+ redirectsAllowed,onDelete,}: {domain: string;isDefault: boolean;redirectUrl?: string | null;+ redirectsAllowed: boolean;onDelete: (deletedDomain: string) => void;}) {const [showDetails, setShowDetails] = useState(false);@@ -274,28 +276,37 @@ export default function DomainCard({<ExternalLinkIcon className="h-4 w-4" />Root Domain Redirect</div>- <p className="mt-1 text-xs text-muted-foreground">- Redirect visitors who land on{" "}- <span className="font-medium">{domain}</span> to a specific URL.- Leave empty to redirect to papermark.com.- </p>- <div className="mt-3 flex items-center gap-2">- <Input- type="url"- placeholder="https://example.com"- value={redirectUrl}- onChange={(e) => setRedirectUrl(e.target.value)}- className="h-9 flex-1"- />- <Button- size="sm"- onClick={handleSaveRedirectUrl}- disabled={savingRedirect}- className="h-9 shrink-0"- >- {savingRedirect ? "Saving..." : "Save"}- </Button>- </div>+ {redirectsAllowed ? (+ <>+ <p className="mt-1 text-xs text-muted-foreground">+ Redirect visitors who land on{" "}+ <span className="font-medium">{domain}</span> to a specific+ URL. Leave empty to redirect to papermark.com.+ </p>+ <div className="mt-3 flex items-center gap-2">+ <Input+ type="url"+ placeholder="https://example.com"+ value={redirectUrl}+ onChange={(e) => setRedirectUrl(e.target.value)}+ className="h-9 flex-1"+ />+ <Button+ size="sm"+ onClick={handleSaveRedirectUrl}+ disabled={savingRedirect}+ className="h-9 shrink-0"+ >+ {savingRedirect ? "Saving..." : "Save"}+ </Button>+ </div>+ </>+ ) : (+ <p className="mt-1 text-xs text-muted-foreground">+ Root domain redirects require a{" "}+ <span className="font-semibold">Business</span> plan or higher.+ </p>+ )}</div></motion.div></div>diff --git a/ee/stripe/webhooks/customer-subscription-deleted.ts b/ee/stripe/webhooks/customer-subscription-deleted.tsindex 3316631b..8763d2c8 100644--- a/ee/stripe/webhooks/customer-subscription-deleted.ts+++ b/ee/stripe/webhooks/customer-subscription-deleted.ts@@ -4,6 +4,7 @@ import { FREE_PLAN_LIMITS } from "@/ee/limits/constants";import { Prisma } from "@prisma/client";import Stripe from "stripe";+import { clearTeamDomainRedirects } from "@/lib/api/domains/clear-team-redirects";import prisma from "@/lib/prisma";import { log } from "@/lib/utils";@@ -32,7 +33,6 @@ export async function customerSubscriptionDeleted(endsAt: null,startsAt: null,limits: freePlanLimits,- // Clear cancellation and pause state when downgrading to freecancelledAt: null,pausedAt: null,pauseStartsAt: null,@@ -41,6 +41,8 @@ export async function customerSubscriptionDeleted(select: { id: true },});+ await clearTeamDomainRedirects(team.id);+await log({message: ":cry: Team *`" + team.id + "`* deleted their subscription",type: "info",diff --git a/ee/stripe/webhooks/customer-subscription-updated.ts b/ee/stripe/webhooks/customer-subscription-updated.tsindex 2a86200d..9f8d4fac 100644--- a/ee/stripe/webhooks/customer-subscription-updated.ts+++ b/ee/stripe/webhooks/customer-subscription-updated.ts@@ -9,6 +9,8 @@ import {} from "@/ee/limits/constants";import Stripe from "stripe";+import { clearTeamDomainRedirects } from "@/lib/api/domains/clear-team-redirects";+import { planSupportsRedirects } from "@/lib/api/domains/redis";import prisma from "@/lib/prisma";import { log } from "@/lib/utils";@@ -98,6 +100,10 @@ export async function customerSubsciptionUpdated(limits: planLimits,},});++ if (!planSupportsRedirects(newPlan)) {+ await clearTeamDomainRedirects(team.id);+ }}// If new account, and the plan is the same, but the quantity is different, update the quantitydiff --git a/lib/api/domains/clear-team-redirects.ts b/lib/api/domains/clear-team-redirects.tsnew file mode 100644index 00000000..982ca3e5--- /dev/null+++ b/lib/api/domains/clear-team-redirects.ts@@ -0,0 +1,27 @@+import prisma from "@/lib/prisma";+import { redis } from "@/lib/redis";++import { getRedisKey } from "./redis";++/**+ * Clears all redirect URLs for every domain belonging to a team,+ * removing them from both Postgres and Redis.+ */+export async function clearTeamDomainRedirects(+ teamId: string,+): Promise<void> {+ const domains = await prisma.domain.findMany({+ where: { teamId, redirectUrl: { not: null } },+ select: { slug: true },+ });++ if (domains.length === 0) return;++ await Promise.all([+ prisma.domain.updateMany({+ where: { teamId, redirectUrl: { not: null } },+ data: { redirectUrl: null },+ }),+ ...domains.map((d) => redis.del(getRedisKey(d.slug))),+ ]);+}diff --git a/lib/api/domains/redis.ts b/lib/api/domains/redis.tsindex a770cc2e..1abf4128 100644--- a/lib/api/domains/redis.ts+++ b/lib/api/domains/redis.ts@@ -2,7 +2,19 @@ import { redis } from "@/lib/redis";const DOMAIN_REDIRECT_PREFIX = "domain:redirect";-function getRedisKey(domain: string): string {+const PLANS_WITH_REDIRECTS = new Set([+ "business",+ "datarooms",+ "datarooms-plus",+ "datarooms-premium",+]);++export function planSupportsRedirects(plan: string): boolean {+ const normalized = plan.replace("+old", "");+ return PLANS_WITH_REDIRECTS.has(normalized);+}++export function getRedisKey(domain: string): string {return `${DOMAIN_REDIRECT_PREFIX}:${domain.toLowerCase()}`;}diff --git a/lib/api/domains/validate-redirect-url.ts b/lib/api/domains/validate-redirect-url.tsnew file mode 100644index 00000000..aa2aee37--- /dev/null+++ b/lib/api/domains/validate-redirect-url.ts@@ -0,0 +1,64 @@+import { get } from "@vercel/edge-config";++import { isTrustedTeam } from "@/lib/edge-config/trusted-teams";+import { log } from "@/lib/utils";+import { validateUrlSecurity } from "@/lib/zod/url-validation";++type ValidationResult =+ | { valid: true; url: string }+ | { valid: false; message: string };++export async function validateRedirectUrl(+ redirectUrl: string,+ teamId: string,+): Promise<ValidationResult> {+ const trimmed = redirectUrl.trim();++ if (!trimmed) {+ return { valid: true, url: "" };+ }++ let parsed: URL;+ try {+ parsed = new URL(trimmed);+ } catch {+ return { valid: false, message: "Invalid redirect URL" };+ }++ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {+ return { valid: false, message: "Redirect URL must use HTTP or HTTPS" };+ }++ if (!validateUrlSecurity(trimmed)) {+ return {+ valid: false,+ message: "Redirect URL targets a disallowed resource",+ };+ }++ const trusted = await isTrustedTeam(teamId);+ if (!trusted) {+ try {+ const keywords = await get("keywords");+ if (Array.isArray(keywords) && keywords.length > 0) {+ const matchedKeyword = keywords.find(+ (keyword) => typeof keyword === "string" && trimmed.includes(keyword),+ );++ if (matchedKeyword) {+ log({+ message: `Redirect URL blocked: ${matchedKeyword} \n\n \`Metadata: {teamId: ${teamId}, url: ${trimmed}}\``,+ type: "error",+ mention: true,+ });+ return { valid: false, message: "This URL is not allowed" };+ }+ }+ } catch {+ // Edge config unavailable; allow the URL through+ }+ }++ // Return the sanitized URL (trimmed, with resolved origin)+ return { valid: true, url: parsed.toString() };+}diff --git a/lib/middleware/domain.ts b/lib/middleware/domain.tsindex c420813d..c2434070 100644--- a/lib/middleware/domain.ts+++ b/lib/middleware/domain.ts@@ -12,8 +12,9 @@ export default async function DomainMiddleware(req: NextRequest) {if (host) {const redirectUrl = await getDomainRedirectUrl(host);if (redirectUrl) {+ // 302: intentionally non-permanent since the target is user-configurablereturn NextResponse.redirect(new URL(redirectUrl, req.url), {- status: 301,+ status: 302,});}}diff --git a/pages/api/cron/domains/sync-redirects.ts b/pages/api/cron/domains/sync-redirects.tsdeleted file mode 100644index e120d99e..00000000--- a/pages/api/cron/domains/sync-redirects.ts+++ /dev/null@@ -1,45 +0,0 @@-import { NextApiRequest, NextApiResponse } from "next";--import { setDomainRedirectUrl } from "@/lib/api/domains/redis";-import prisma from "@/lib/prisma";--export default async function handle(- req: NextApiRequest,- res: NextApiResponse,-) {- if (req.method !== "POST") {- res.setHeader("Allow", ["POST"]);- return res.status(405).end(`Method ${req.method} Not Allowed`);- }-- const authHeader = req.headers.authorization;- if (authHeader !== `Bearer ${process.env.CRON_SECRET}`) {- return res.status(401).json({ error: "Unauthorized" });- }-- try {- const domains = await prisma.domain.findMany({- where: {- redirectUrl: { not: null },- },- select: {- slug: true,- redirectUrl: true,- },- });-- await Promise.all(- domains.map((domain) =>- setDomainRedirectUrl(domain.slug, domain.redirectUrl),- ),- );-- return res.status(200).json({- message: `Synced ${domains.length} domain redirect(s) to Redis`,- domains: domains.map((d) => d.slug),- });- } catch (error) {- console.error("Failed to sync domain redirects:", error);- return res.status(500).json({ error: "Failed to sync domain redirects" });- }-}diff --git a/pages/api/teams/[teamId]/domains/[domain]/index.ts b/pages/api/teams/[teamId]/domains/[domain]/index.tsindex 77b820ef..1ca6689b 100644--- a/pages/api/teams/[teamId]/domains/[domain]/index.ts+++ b/pages/api/teams/[teamId]/domains/[domain]/index.ts@@ -5,8 +5,10 @@ import { getServerSession } from "next-auth/next";import {deleteDomainRedirectUrl,+ planSupportsRedirects,setDomainRedirectUrl,} from "@/lib/api/domains/redis";+import { validateRedirectUrl } from "@/lib/api/domains/validate-redirect-url";import { getApexDomain, removeDomainFromVercel } from "@/lib/domains";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";@@ -152,7 +154,7 @@ export default async function handle(}try {- const { domain: domainToBeUpdated } = await getTeamWithDomain({+ const { team, domain: domainToBeUpdated } = await getTeamWithDomain({teamId,userId,domain,@@ -164,15 +166,21 @@ export default async function handle(const { redirectUrl } = req.body as { redirectUrl: string | null };- if (redirectUrl !== null && redirectUrl !== undefined && redirectUrl !== "") {- try {- new URL(redirectUrl);- } catch {- return res.status(422).json({ message: "Invalid redirect URL" });- }+ if (redirectUrl && !planSupportsRedirects(team.plan)) {+ return res.status(403).json({+ message:+ "Root domain redirects require a Business plan or higher",+ });}- const normalizedUrl = redirectUrl || null;+ let normalizedUrl: string | null = null;+ if (redirectUrl) {+ const result = await validateRedirectUrl(redirectUrl, teamId);+ if (!result.valid) {+ return res.status(422).json({ message: result.message });+ }+ normalizedUrl = result.url || null;+ }const updatedDomain = await prisma.domain.update({where: {diff --git a/pages/api/teams/[teamId]/domains/index.ts b/pages/api/teams/[teamId]/domains/index.tsindex dcc0ae3a..14924cab 100644--- a/pages/api/teams/[teamId]/domains/index.ts+++ b/pages/api/teams/[teamId]/domains/index.ts@@ -2,7 +2,11 @@ import { NextApiRequest, NextApiResponse } from "next";import { getServerSession } from "next-auth/next";-import { setDomainRedirectUrl } from "@/lib/api/domains/redis";+import {+ planSupportsRedirects,+ setDomainRedirectUrl,+} from "@/lib/api/domains/redis";+import { validateRedirectUrl } from "@/lib/api/domains/validate-redirect-url";import { addDomainToVercel, validDomainRegex } from "@/lib/domains";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";@@ -65,7 +69,7 @@ export default async function handle(}try {- await getTeamWithDomain({+ const { team } = await getTeamWithDomain({teamId,userId,});@@ -105,18 +109,33 @@ export default async function handle(.json({ message: "Unable to add this domain. Please try a different one." });}+ let validatedRedirectUrl: string | undefined;+ if (redirectUrl) {+ if (!planSupportsRedirects(team.plan)) {+ return res.status(403).json({+ message:+ "Root domain redirects require a Business plan or higher",+ });+ }+ const result = await validateRedirectUrl(redirectUrl, teamId);+ if (!result.valid) {+ return res.status(422).json({ message: result.message });+ }+ validatedRedirectUrl = result.url || undefined;+ }+const response = await prisma.domain.create({data: {slug: sanitizedDomain,userId,teamId,- ...(redirectUrl && { redirectUrl }),+ ...(validatedRedirectUrl && { redirectUrl: validatedRedirectUrl }),},});await addDomainToVercel(sanitizedDomain);- if (redirectUrl) {- await setDomainRedirectUrl(sanitizedDomain, redirectUrl);+ if (validatedRedirectUrl) {+ await setDomainRedirectUrl(sanitizedDomain, validatedRedirectUrl);}return res.status(201).json(response);diff --git a/pages/api/teams/[teamId]/index.ts b/pages/api/teams/[teamId]/index.tsindex 44f1f41c..4eaeb0aa 100644--- a/pages/api/teams/[teamId]/index.ts+++ b/pages/api/teams/[teamId]/index.ts@@ -5,6 +5,7 @@ import { isOldAccount } from "@/ee/stripe/utils";import { DocumentStorageType } from "@prisma/client";import { getServerSession } from "next-auth";+import { deleteDomainRedirectUrl } from "@/lib/api/domains/redis";import { removeDomainFromVercelProject } from "@/lib/domains";import { errorhandler } from "@/lib/errorHandler";import { deleteFiles } from "@/lib/files/delete-team-files-server";@@ -204,12 +205,13 @@ export default async function handle(},});- // prepare a list of promises to delete domains- let domainPromises: void[] = [];+ // prepare a list of promises to delete domains and their Redis redirect entries+ let domainPromises: Promise<unknown>[] = [];if (team.domains) {- domainPromises = team.domains.map((domain) => {- removeDomainFromVercelProject(domain.slug);- });+ domainPromises = team.domains.flatMap((domain) => [+ removeDomainFromVercelProject(domain.slug),+ deleteDomainRedirectUrl(domain.slug),+ ]);}await Promise.all([diff --git a/pages/settings/domains.tsx b/pages/settings/domains.tsxindex 7c42d286..3ee8885c 100644--- a/pages/settings/domains.tsx+++ b/pages/settings/domains.tsx@@ -4,6 +4,7 @@ import { useTeam } from "@/context/team-context";import { CircleHelpIcon } from "lucide-react";import { mutate } from "swr";+import { usePlan } from "@/lib/swr/use-billing";import { useDomains } from "@/lib/swr/use-domains";import { AddDomainModal } from "@/components/domains/add-domain-modal";@@ -16,6 +17,7 @@ import { BadgeTooltip } from "@/components/ui/tooltip";export default function Domains() {const { domains } = useDomains({ enabled: true });const teamInfo = useTeam();+ const { isBusiness, isDatarooms } = usePlan();const [open, setOpen] = useState<boolean>(false);@@ -76,6 +78,7 @@ export default function Domains() {domain={domain.slug}isDefault={domain.isDefault}redirectUrl={domain.redirectUrl}+ redirectsAllowed={isBusiness || isDatarooms}onDelete={handleDomainDeletion}/></li>diff --git a/prisma/migrations/20260220000000_add_redirect_url_to_domain/migration.sql b/prisma/migrations/20260220000000_add_redirect_url_to_domain/migration.sqlindex 5805f249..9144e8b0 100644--- a/prisma/migrations/20260220000000_add_redirect_url_to_domain/migration.sql+++ b/prisma/migrations/20260220000000_add_redirect_url_to_domain/migration.sql@@ -1,9 +1,2 @@-- AlterTableALTER TABLE "Domain" ADD COLUMN "redirectUrl" TEXT;---- Backfill existing hardcoded root domain redirects-UPDATE "Domain" SET "redirectUrl" = 'https://guide.permithealth.com/faq' WHERE "slug" = 'guide.permithealth.com';-UPDATE "Domain" SET "redirectUrl" = 'https://tradeair.in/sv-fm-inbound' WHERE "slug" = 'fund.tradeair.in';-UPDATE "Domain" SET "redirectUrl" = 'https://www.pashupaticapital.com/' WHERE "slug" = 'docs.pashupaticapital.com';-UPDATE "Domain" SET "redirectUrl" = 'https://partners.braxtech.net/investors' WHERE "slug" = 'partners.braxtech.net';-UPDATE "Domain" SET "redirectUrl" = 'https://research.elazaradvisors.com/root' WHERE "slug" = 'research.elazaradvisors.com';