Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
chore: remove deprecated public-blob document storage and link GETs
Iuliia Shnaifb072af954fd
diff --git a/lib/files/put-file-server.ts b/lib/files/put-file-server.tsindex 86bc3d4f..b6dea846 100644--- a/lib/files/put-file-server.ts+++ b/lib/files/put-file-server.ts@@ -1,16 +1,15 @@import { PutObjectCommand } from "@aws-sdk/client-s3";import { Upload } from "@aws-sdk/lib-storage";import { DocumentStorageType } from "@prisma/client";-import { put } from "@vercel/blob";import { createReadStream } from "node:fs";import path from "node:path";-import { match } from "ts-pattern";import { newId } from "@/lib/id-helper";import { buildContentDisposition, safeSlugify } from "@/lib/utils";import { SUPPORTED_DOCUMENT_MIME_TYPES } from "../constants";import { getTeamS3ClientAndConfig } from "./aws-client";+import { assertS3Transport } from "./transport";// `File` is a web API type and not available server-side, so we need to define our own typetype File = {@@ -32,36 +31,17 @@ export const putFileServer = async ({restricted?: boolean;subfolder?: string;}) => {- const NEXT_PUBLIC_UPLOAD_TRANSPORT = process.env.NEXT_PUBLIC_UPLOAD_TRANSPORT;-- const { type, data } = await match(NEXT_PUBLIC_UPLOAD_TRANSPORT)- .with("s3", async () =>- putFileInS3Server({ file, teamId, docId, restricted, subfolder }),- )- .with("vercel", async () => putFileInVercelServer(file))- .otherwise(() => {- return {- type: null,- data: null,- numPages: undefined,- };- });-- return { type, data };-};--const putFileInVercelServer = async (file: File) => {- const contents = file.buffer;-- const blob = await put(file.name, contents, {- access: "public",- addRandomSuffix: true,+ assertS3Transport();++ const { type, data } = await putFileInS3Server({+ file,+ teamId,+ docId,+ restricted,+ subfolder,});- return {- type: DocumentStorageType.VERCEL_BLOB,- data: blob.url,- };+ return { type, data };};const putFileInS3Server = async ({@@ -137,8 +117,8 @@ type StreamFile = {/*** Streaming counterpart to {@link putFileServer}. Reads the file from disk as a- * stream and uploads it without buffering the whole payload in memory (S3 uses- * multipart via lib-storage; Vercel Blob uses multipart streaming).+ * stream and uploads it without buffering the whole payload in memory (via+ * multipart S3 upload through lib-storage).*/export const putFileServerStream = async ({file,@@ -153,32 +133,17 @@ export const putFileServerStream = async ({restricted?: boolean;subfolder?: string;}) => {- const NEXT_PUBLIC_UPLOAD_TRANSPORT = process.env.NEXT_PUBLIC_UPLOAD_TRANSPORT;-- const { type, data } = await match(NEXT_PUBLIC_UPLOAD_TRANSPORT)- .with("s3", async () =>- putFileStreamInS3Server({ file, teamId, docId, restricted, subfolder }),- )- .with("vercel", async () => putFileStreamInVercelServer(file))- .otherwise(() => {- return { type: null, data: null };- });-- return { type, data };-};--const putFileStreamInVercelServer = async (file: StreamFile) => {- const blob = await put(file.name, createReadStream(file.path), {- access: "public",- addRandomSuffix: true,- multipart: true,- contentType: file.type,+ assertS3Transport();++ const { type, data } = await putFileStreamInS3Server({+ file,+ teamId,+ docId,+ restricted,+ subfolder,});- return {- type: DocumentStorageType.VERCEL_BLOB,- data: blob.url,- };+ return { type, data };};const putFileStreamInS3Server = async ({diff --git a/lib/files/put-file.ts b/lib/files/put-file.tsindex ef63fb51..063e0219 100644--- a/lib/files/put-file.ts+++ b/lib/files/put-file.ts@@ -1,6 +1,4 @@import { DocumentStorageType } from "@prisma/client";-import { upload } from "@vercel/blob/client";-import { match } from "ts-pattern";import { newId } from "@/lib/id-helper";import { getPagesCount } from "@/lib/utils/get-page-number-count";@@ -11,9 +9,10 @@ import type {} from "@/lib/zod/schemas/multipart";import { SUPPORTED_DOCUMENT_MIME_TYPES } from "../constants";+import { assertS3Transport } from "./transport";/**- * Uploads a file to the configured storage backend (S3 or Vercel).+ * Uploads a file to S3.** For S3 uploads:* - Files larger than 10MB automatically use multipart upload with pre-signed URLs@@ -24,7 +23,7 @@ import { SUPPORTED_DOCUMENT_MIME_TYPES } from "../constants";* @param file - The file to upload* @param teamId - The team ID for storage configuration* @param docId - Optional document ID (generated if not provided)- * @returns Upload result with storage type, key/URL, page count, and file size+ * @returns Upload result with storage type, key, page count, and file size*/export const putFile = async ({file,@@ -40,44 +39,9 @@ export const putFile = async ({numPages: number | undefined;fileSize: number | undefined;}> => {- const NEXT_PUBLIC_UPLOAD_TRANSPORT = process.env.NEXT_PUBLIC_UPLOAD_TRANSPORT;-- const { type, data, numPages, fileSize } = await match(- NEXT_PUBLIC_UPLOAD_TRANSPORT,- )- .with("s3", async () => putFileInS3({ file, teamId, docId }))- .with("vercel", async () => putFileInVercel(file))- .otherwise(() => {- return {- type: null,- data: null,- numPages: undefined,- fileSize: undefined,- };- });-- return { type, data, numPages, fileSize };-};--const putFileInVercel = async (file: File) => {- const newBlob = await upload(file.name, file, {- access: "public",- handleUploadUrl: "/api/file/browser-upload",- });-- let numPages: number = 1;- // get page count for pdf files- if (file.type === "application/pdf") {- const body = await file.arrayBuffer();- numPages = await getPagesCount(body);- }+ assertS3Transport();- return {- type: DocumentStorageType.VERCEL_BLOB,- data: newBlob.url,- numPages: numPages,- fileSize: file.size,- };+ return putFileInS3({ file, teamId, docId });};// Multipart upload threshold: 10MBdiff --git a/lib/files/transport.ts b/lib/files/transport.tsnew file mode 100644index 00000000..0fdcacd2--- /dev/null+++ b/lib/files/transport.ts@@ -0,0 +1,15 @@+/**+ * Document content is stored in S3 as a private object key. Reads still support+ * `VERCEL_BLOB` for documents stored before the migration, and public assets+ * (brand logos, banners, link preview images) still use Vercel Blob directly.+ */+export const isS3Transport = () =>+ process.env.NEXT_PUBLIC_UPLOAD_TRANSPORT === "s3";++export const assertS3Transport = () => {+ if (!isS3Transport()) {+ throw new Error(+ 'Unsupported upload transport: document uploads require NEXT_PUBLIC_UPLOAD_TRANSPORT="s3".',+ );+ }+};diff --git a/lib/signing/mirror.ts b/lib/signing/mirror.tsindex 94e3fbc1..7430d301 100644--- a/lib/signing/mirror.ts+++ b/lib/signing/mirror.ts@@ -1,8 +1,8 @@import { PutObjectCommand } from "@aws-sdk/client-s3";import { DocumentStorageType } from "@prisma/client";-import { put as putBlob } from "@vercel/blob";import { getTeamS3ClientAndConfig } from "@/lib/files/aws-client";+import { assertS3Transport } from "@/lib/files/transport";import prisma from "@/lib/prisma";import { buildContentDisposition, safeSlugify } from "@/lib/utils";@@ -124,18 +124,7 @@ const uploadToS3 = async ({return { storageType: DocumentStorageType.S3_PATH, fileKey: key };};-const uploadToBlob = async ({ key, body }: { key: string; body: Buffer }) => {- // `addRandomSuffix` makes the public blob URL unguessable; persist the returned URL (not the deterministic key) so `getFile` resolves the real object.- const blob = await putBlob(key, body, {- access: "public",- addRandomSuffix: true,- contentType: "application/pdf",- });-- return { storageType: DocumentStorageType.VERCEL_BLOB, fileKey: blob.url };-};--/** Mirror a signed Documenso PDF into team storage (S3/Blob); idempotent and non-fatal — downloads fall back to a direct Documenso call when the mirror is missing. */+/** Mirror a signed Documenso PDF into team S3 storage; idempotent and non-fatal — downloads fall back to a direct Documenso call when the mirror is missing. */export const mirrorSignedAgreementToStorage = async ({agreementResponseId,}: {@@ -190,21 +179,14 @@ export const mirrorSignedAgreementToStorage = async ({agreementResponseId: response.id,});- const transport = process.env.NEXT_PUBLIC_UPLOAD_TRANSPORT;-- // Persist whatever the uploader returns as `fileKey`: S3 needs the key, VERCEL_BLOB needs the returned (random-suffixed) URL.- const { storageType, fileKey } =- transport === "s3"- ? await uploadToS3({- teamId,- key: signedFileKey,- contentDisposition: buildContentDisposition(- signedFileName,- signedFileName,- ),- body,- })- : await uploadToBlob({ key: signedFileKey, body });+ assertS3Transport();++ const { storageType, fileKey } = await uploadToS3({+ teamId,+ key: signedFileKey,+ contentDisposition: buildContentDisposition(signedFileName, signedFileName),+ body,+ });await prisma.agreementResponse.update({where: { id: response.id },diff --git a/lib/swr/use-link.ts b/lib/swr/use-link.tsindex 143ef6f9..620421d5 100644--- a/lib/swr/use-link.ts+++ b/lib/swr/use-link.ts@@ -1,63 +1,9 @@-import { useRouter } from "next/router";-import { useTeam } from "@/context/team-context";import { View } from "@prisma/client";import useSWR from "swr";import { fetcher } from "@/lib/utils";-import { LinkWithDocument } from "../types";--export function useLink() {- const router = useRouter();-- const { linkId } = router.query as {- linkId: string;- };-- // only fetch data once when linkId is present- const { data: link, error } = useSWR<LinkWithDocument>(- linkId && `/api/links/${encodeURIComponent(linkId)}`,- fetcher,- {- dedupingInterval: 10000,- },- );-- return {- link,- loading: !error && !link,- error,- };-}--export function useDomainLink() {- const router = useRouter();-- const { domain, slug } = router.query as {- domain: string;- slug: string;- };-- const { data: link, error } = useSWR<LinkWithDocument>(- domain &&- slug &&- `/api/links/domains/${encodeURIComponent(domain)}/${encodeURIComponent(- slug,- )}`,- fetcher,- {- dedupingInterval: 10000,- },- );-- return {- link,- loading: !error && !link,- error,- };-}-interface ViewWithDuration extends View {duration: {data: { pageNumber: string; sum_duration: number }[];diff --git a/pages/api/file/browser-upload.ts b/pages/api/file/browser-upload.tsdeleted file mode 100644index 07b252e2..00000000--- a/pages/api/file/browser-upload.ts+++ /dev/null@@ -1,87 +0,0 @@-import type { NextApiRequest, NextApiResponse } from "next";--import { type HandleUploadBody, handleUpload } from "@vercel/blob/client";-import { getServerSession } from "next-auth/next";--import prisma from "@/lib/prisma";-import { CustomUser } from "@/lib/types";--import { authOptions } from "../auth/[...nextauth]";--export default async function handler(- req: NextApiRequest,- res: NextApiResponse,-) {- const body = req.body as HandleUploadBody;-- try {- const jsonResponse = await handleUpload({- body,- request: req,- onBeforeGenerateToken: async (pathname: string) => {- // Generate a client token for the browser to upload the file-- const session = await getServerSession(req, res, authOptions);- if (!session) {- res.status(401).end("Unauthorized");- throw new Error("Unauthorized");- }-- const userId = (session.user as CustomUser).id;- const team = await prisma.team.findFirst({- where: {- users: {- some: {- userId,- },- },- },- select: {- plan: true,- },- });-- let maxSize = 30 * 1024 * 1024; // 30 MB- const stripedTeamPlan = team?.plan.replace("+old", "");- if (- stripedTeamPlan &&- ["business", "datarooms", "datarooms-plus", "datarooms-premium", "datarooms-unlimited"].includes(stripedTeamPlan)- ) {- maxSize = 100 * 1024 * 1024; // 100 MB- }-- return {- addRandomSuffix: true,- allowedContentTypes: [- "application/pdf",- "application/vnd.ms-excel",- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",- ],- maximumSizeInBytes: maxSize, // 30 MB- metadata: JSON.stringify({- // optional, sent to your server on upload completion- userId: (session.user as CustomUser).id,- }),- };- },- onUploadCompleted: async ({ blob, tokenPayload }) => {- // Get notified of browser upload completion- // ⚠️ This will not work on `localhost` websites,- // Use ngrok or similar to get the full upload flow-- try {- // Run any logic after the file upload completed- // const { userId } = JSON.parse(tokenPayload);- // await db.update({ avatar: blob.url, userId });- } catch (error) {- // throw new Error("Could not update user");- }- },- });-- return res.status(200).json(jsonResponse);- } catch (error) {- // The webhook will retry 5 times waiting for a 200- return res.status(400).json({ error: (error as Error).message });- }-}diff --git a/pages/api/links/[id]/index.ts b/pages/api/links/[id]/index.tsindex 3bee5cbc..274eb788 100644--- a/pages/api/links/[id]/index.ts+++ b/pages/api/links/[id]/index.ts@@ -1,13 +1,9 @@import { NextApiRequest, NextApiResponse } from "next";-import { Brand, DataroomBrand, LinkAudienceType } from "@prisma/client";+import { LinkAudienceType } from "@prisma/client";import { customAlphabet } from "nanoid";import { getServerSession } from "next-auth/next";-import {- fetchDataroomLinkData,- fetchDocumentLinkData,-} from "@/lib/api/links/link-data";import { enforceLinkMemberScope } from "@/lib/api/rbac/guard";import prisma from "@/lib/prisma";import { CustomUser, WatermarkConfigSchema } from "@/lib/types";@@ -15,7 +11,6 @@ import {decryptEncrpytedPassword,generateEncrpytedPassword,} from "@/lib/utils";-import { checkGlobalBlockList } from "@/lib/utils/global-block-list";import { DomainObject } from "..";import { authOptions } from "../../auth/[...nextauth]";@@ -44,178 +39,7 @@ export default async function handle(req: NextApiRequest,res: NextApiResponse,) {- if (req.method === "GET") {- // GET /api/links/:id- const { id } = req.query as { id: string };-- try {- console.time("get-link");- const link = await prisma.link.findUnique({- where: {- id: id,- },- select: {- id: true,- expiresAt: true,- emailProtected: true,- emailAuthenticated: true,- allowDownload: true,- enableFeedback: true,- enableScreenshotProtection: true,- enableConfidentialView: true,- password: true,- isArchived: true,- deletedAt: true,- enableIndexFile: true,- enableCustomMetatag: true,- metaTitle: true,- metaDescription: true,- metaImage: true,- metaFavicon: true,- welcomeMessage: true,- enableQuestion: true,- linkType: true,- feedback: {- select: {- id: true,- data: true,- },- },- enableAgreement: true,- agreement: true,- showBanner: true,- enableWatermark: true,- watermarkConfig: true,- groupId: true,- permissionGroupId: true,- audienceType: true,- dataroomId: true,- teamId: true,- team: {- select: {- plan: true,- globalBlockList: true,- },- },- customFields: {- select: {- id: true,- type: true,- identifier: true,- label: true,- placeholder: true,- required: true,- disabled: true,- orderIndex: true,- },- orderBy: {- orderIndex: "asc",- },- },- },- });-- console.timeEnd("get-link");-- if (!link) {- return res.status(404).json({ error: "Link not found" });- }-- if (link.deletedAt) {- return res.status(404).json({ error: "Link has been deleted" });- }-- if (link.isArchived) {- return res.status(404).json({ error: "Link is archived" });- }-- const { email } = req.query as { email?: string };- const globalBlockCheck = checkGlobalBlockList(- email,- link.team?.globalBlockList,- );- if (globalBlockCheck.error) {- return res.status(400).json({ message: globalBlockCheck.error });- }- if (globalBlockCheck.isBlocked) {- return res.status(403).json({ message: "Access denied" });- }-- const linkType = link.linkType;-- // Handle workflow links separately- if (linkType === "WORKFLOW_LINK") {- // For workflow links, fetch brand if available- let brand: Partial<Brand> | null = null;- if (link.teamId) {- const teamBrand = await prisma.brand.findUnique({- where: { teamId: link.teamId },- select: {- logo: true,- brandColor: true,- accentColor: true,- },- });- brand = teamBrand;- }-- return res.status(200).json({ linkType, brand });- }-- let brand: Partial<Brand> | Partial<DataroomBrand> | null = null;- let linkData: any;-- if (linkType === "DOCUMENT_LINK") {- console.time("get-document-link-data");- const data = await fetchDocumentLinkData({- linkId: id,- teamId: link.teamId!,- });- linkData = data.linkData;- brand = data.brand;- console.timeEnd("get-document-link-data");- } else if (linkType === "DATAROOM_LINK") {- console.time("get-dataroom-link-data");- const data = await fetchDataroomLinkData({- linkId: id,- dataroomId: link.dataroomId,- teamId: link.teamId!,- permissionGroupId: link.permissionGroupId || undefined,- ...(link.audienceType === LinkAudienceType.GROUP &&- link.groupId && {- groupId: link.groupId,- }),- });- linkData = data.linkData;- brand = data.brand;- // Include access controls in the link data for the frontend- linkData.accessControls = data.accessControls;- console.timeEnd("get-dataroom-link-data");- }-- const teamPlan = link.team?.plan || "free";-- const returnLink = {- ...link,- ...linkData,- dataroomId: undefined,- ...(teamPlan === "free" && {- customFields: [], // reset custom fields for free plan- enableAgreement: false,- enableWatermark: false,- permissionGroupId: null,- }),- };-- return res.status(200).json({ linkType, link: returnLink, brand });- } catch (error) {- console.error("Error fetching link data:", error);- return res.status(500).json({- message: "Internal Server Error",- error: (error as Error).message,- });- }- } else if (req.method === "PUT") {+ if (req.method === "PUT") {// PUT /api/links/:idconst session = await getServerSession(req, res, authOptions);if (!session) {@@ -672,12 +496,10 @@ export default async function handle(// Create new associationsif (linkData.visitorGroupIds?.length > 0) {await tx.linkVisitorGroup.createMany({- data: linkData.visitorGroupIds.map(- (visitorGroupId: string) => ({- linkId: id,- visitorGroupId,- }),- ),+ data: linkData.visitorGroupIds.map((visitorGroupId: string) => ({+ linkId: id,+ visitorGroupId,+ })),skipDuplicates: true,});}@@ -867,7 +689,7 @@ export default async function handle(}}- // We only allow GET and PUT requests- res.setHeader("Allow", ["GET", "PUT", "DELETE"]);+ // We only allow PUT and DELETE requests+ res.setHeader("Allow", ["PUT", "DELETE"]);return res.status(405).end(`Method ${req.method} Not Allowed`);}diff --git a/pages/api/links/domains/[...domainSlug].ts b/pages/api/links/domains/[...domainSlug].tsdeleted file mode 100644index 24e4f137..00000000--- a/pages/api/links/domains/[...domainSlug].ts+++ /dev/null@@ -1,266 +0,0 @@-import { NextApiRequest, NextApiResponse } from "next";--import { Brand, DataroomBrand, LinkAudienceType } from "@prisma/client";--import { fetchDataroomDocumentLinkData } from "@/lib/api/links/link-data";-import {- fetchDataroomLinkData,- fetchDocumentLinkData,-} from "@/lib/api/links/link-data";-import prisma from "@/lib/prisma";-import { log } from "@/lib/utils";-import { checkGlobalBlockList } from "@/lib/utils/global-block-list";--export default async function handle(- req: NextApiRequest,- res: NextApiResponse,-) {- // Immediately set the Cache-Control header to prevent any form of caching- // res.setHeader("Cache-Control", "no-store, max-age=0, must-revalidate");-- if (req.method === "GET") {- // GET /api/links/domains/:domain/:slug- const { domainSlug } = req.query as { domainSlug: string[] };-- const domain = domainSlug[0];- const slug = domainSlug[1];- const documentId = domainSlug[3];-- if (slug === "404") {- return res.status(404).json({- error: "Link not found",- message: "link not found",- });- }-- try {- console.time("get-link");- const link = await prisma.link.findUnique({- where: {- domainSlug_slug: {- slug: slug,- domainSlug: domain,- },- },- select: {- id: true,- expiresAt: true,- emailProtected: true,- allowDownload: true,- password: true,- isArchived: true,- deletedAt: true,- enableCustomMetatag: true,- enableFeedback: true,- enableScreenshotProtection: true,- enableConfidentialView: true,- enableIndexFile: true,- metaTitle: true,- metaDescription: true,- metaImage: true,- metaFavicon: true,- welcomeMessage: true,- enableQuestion: true,- dataroomId: true,- linkType: true,- feedback: {- select: {- id: true,- data: true,- },- },- enableAgreement: true,- agreement: true,- showBanner: true,- enableWatermark: true,- watermarkConfig: true,- groupId: true,- permissionGroupId: true,- audienceType: true,- teamId: true,- team: {- select: {- plan: true,- globalBlockList: true,- },- },- customFields: {- select: {- id: true,- type: true,- identifier: true,- label: true,- placeholder: true,- required: true,- disabled: true,- orderIndex: true,- },- orderBy: {- orderIndex: "asc",- },- },- },- });- console.timeEnd("get-link");-- // if link not found, return 404- if (!link) {- log({- message: `Link not found for custom domain _${domain}/${slug}_`,- type: "error",- mention: true,- });- return res.status(404).json({- error: "Link not found",- message: "No link found",- });- }-- if (link.isArchived) {- return res.status(404).json({- error: "Link is archived",- message: "link is archived",- });- }-- if (link.deletedAt) {- return res.status(404).json({- error: "Link has been deleted",- message: "This link has been deleted",- });- }-- const { email } = req.query as { email?: string };- const globalBlockCheck = checkGlobalBlockList(- email,- link.team?.globalBlockList,- );- if (globalBlockCheck.error) {- return res.status(400).json({ message: globalBlockCheck.error });- }- if (globalBlockCheck.isBlocked) {- return res.status(403).json({ message: "Access denied" });- }-- const teamPlan = link.team?.plan || "free";- const teamId = link.teamId;- // if owner of document is on free plan, return 404- if (teamPlan.includes("free")) {- log({- message: `Link is from a free team _${teamId}_ for custom domain _${domain}/${slug}_`,- type: "info",- mention: true,- });- return res.status(404).json({- error: "Link not found",- message: `link found, team ${teamPlan}`,- });- }-- const linkType = link.linkType;-- // Handle workflow links separately- if (linkType === "WORKFLOW_LINK") {- // For workflow links, fetch brand if available- let brand: Partial<Brand> | null = null;- if (link.teamId) {- const teamBrand = await prisma.brand.findUnique({- where: { teamId: link.teamId },- select: {- logo: true,- brandColor: true,- accentColor: true,- },- });- brand = teamBrand;- }-- return res.status(200).json({ linkType, brand, linkId: link.id });- }-- let brand: Partial<Brand> | Partial<DataroomBrand> | null = null;- let linkData: any;-- if (linkType === "DOCUMENT_LINK") {- console.time("get-document-link-data");- const data = await fetchDocumentLinkData({- linkId: link.id,- teamId: link.teamId!,- });- linkData = data.linkData;- brand = data.brand;- console.timeEnd("get-document-link-data");- } else if (linkType === "DATAROOM_LINK") {- console.time("get-dataroom-link-data");- if (documentId) {- const data = await fetchDataroomDocumentLinkData({- linkId: link.id,- teamId: link.teamId!,- dataroomDocumentId: documentId,- permissionGroupId: link.permissionGroupId || undefined,- ...(link.audienceType === LinkAudienceType.GROUP &&- link.groupId && {- groupId: link.groupId,- }),- });- linkData = data.linkData;- brand = data.brand;- } else {- const data = await fetchDataroomLinkData({- linkId: link.id,- dataroomId: link.dataroomId,- teamId: link.teamId!,- permissionGroupId: link.permissionGroupId || undefined,- ...(link.audienceType === LinkAudienceType.GROUP &&- link.groupId && {- groupId: link.groupId,- }),- });- linkData = data.linkData;- brand = data.brand;- // Include access controls in the link data for the frontend- linkData.accessControls = data.accessControls;- }- console.timeEnd("get-dataroom-link-data");- }-- // remove document and domain from link- const sanitizedLink = {- ...link,- teamId: undefined,- team: undefined,- document: undefined,- dataroom: undefined,- ...(teamPlan === "free" && {- customFields: [], // reset custom fields for free plan- enableAgreement: false,- enableWatermark: false,- permissionGroupId: null,- }),- };-- // clean up the link return object- const returnLink = {- ...sanitizedLink,- ...linkData,- dataroomDocument: linkData.dataroom?.documents[0] || undefined,- };-- res.status(200).json({ linkType, link: returnLink, brand });- } catch (error) {- log({- message: `Cannot get link for custom domain _${domainSlug}_ \n\n${error}`,- type: "error",- mention: true,- });- return res.status(500).json({- message: "Internal Server Error",- error: (error as Error).message,- });- }- } else {- // We only allow GET requests- res.setHeader("Allow", ["GET"]);- return res.status(405).end(`Method ${req.method} Not Allowed`);- }-}