Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

refactor: add clientside protection

Marc Seitz325a52fcfa6e
diff --git a/lib/files/get-file.ts b/lib/files/get-file.ts
index 44fd71aa..17ce2f3b 100644
--- a/lib/files/get-file.ts
+++ b/lib/files/get-file.ts
@@ -27,7 +27,6 @@ export const getFile = async ({
return url;
};
-
const fetchPresignedUrl = async (
endpoint: string,
headers: Record<string, string>,
@@ -46,14 +45,17 @@ const fetchPresignedUrl = async (
if (contentType && contentType.includes("application/json")) {
try {
const error = await response.json();
- errorMessage = error.message || `Request failed with status ${response.status}`;
+ errorMessage =
+ error.message || `Request failed with status ${response.status}`;
} catch (parseError) {
const textError = await response.text();
- errorMessage = textError || `Request failed with status ${response.status}`;
+ errorMessage =
+ textError || `Request failed with status ${response.status}`;
}
} else {
const textError = await response.text();
- errorMessage = textError || `Request failed with status ${response.status}`;
+ errorMessage =
+ textError || `Request failed with status ${response.status}`;
}
throw new Error(errorMessage);
@@ -64,7 +66,8 @@ const fetchPresignedUrl = async (
};
const getFileFromS3 = async (key: string) => {
- const isServer = typeof window === 'undefined' && !!process.env.INTERNAL_API_KEY;
+ const isServer =
+ typeof window === "undefined" && !!process.env.INTERNAL_API_KEY;
if (isServer) {
return fetchPresignedUrl(
diff --git a/lib/swr/use-document-preview.ts b/lib/swr/use-document-preview.ts
index f192fb21..ea3001f9 100644
--- a/lib/swr/use-document-preview.ts
+++ b/lib/swr/use-document-preview.ts
@@ -1,15 +1,20 @@
+import { useTeam } from "@/context/team-context";
import useSWRImmutable from "swr/immutable";
import { DocumentPreviewData } from "@/lib/types/document-preview";
import { fetcher } from "@/lib/utils";
export function useDocumentPreview(documentId: string, isOpen: boolean) {
+ const { currentTeamId } = useTeam();
+
const {
data: document,
error,
mutate,
} = useSWRImmutable<DocumentPreviewData>(
- isOpen && documentId ? `/api/documents/${documentId}/preview-data` : null,
+ isOpen && currentTeamId && documentId
+ ? `/api/teams/${currentTeamId}/documents/${documentId}/preview-data`
+ : null,
fetcher,
{
dedupingInterval: 10000,
diff --git a/pages/api/file/s3/get-presigned-get-url-proxy.ts b/pages/api/file/s3/get-presigned-get-url-proxy.ts
index e5509483..b32e6834 100644
--- a/pages/api/file/s3/get-presigned-get-url-proxy.ts
+++ b/pages/api/file/s3/get-presigned-get-url-proxy.ts
@@ -3,60 +3,98 @@ import { NextApiRequest, NextApiResponse } from "next";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import { getServerSession } from "next-auth/next";
+import { errorhandler } from "@/lib/errorHandler";
+import prisma from "@/lib/prisma";
+import { CustomUser } from "@/lib/types";
+
export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
+ req: NextApiRequest,
+ res: NextApiResponse,
) {
- if (req.method !== "POST") {
- return res.status(405).end("Method Not Allowed");
- }
+ if (req.method !== "POST") {
+ return res.status(405).end("Method Not Allowed");
+ }
- const session = await getServerSession(req, res, authOptions);
- if (!session) {
- return res.status(401).json({ message: "Unauthorized" });
- }
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).json({ message: "Unauthorized" });
+ }
+
+ const { key } = req.body as { key: string };
+
+ if (!key) {
+ return res.status(400).json({ message: "Key is required" });
+ }
- const { key } = req.body as { key: string };
+ // Extract teamId from key (format: teamId/docId/filename)
+ const teamId = key.split("/")[0];
+ if (!teamId) {
+ return res.status(400).json({ message: "Invalid key format" });
+ }
- if (!key) {
- return res.status(400).json({ message: "Key is required" });
+ // Check if user belongs to the team that owns the file
+ try {
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ users: {
+ some: {
+ userId: (session.user as CustomUser).id,
+ },
+ },
+ },
+ });
+
+ if (!team) {
+ return res
+ .status(403)
+ .json({ message: "Forbidden: You are not a member of this team" });
}
+ } catch (error) {
+ return errorhandler(error, res);
+ }
+
+ try {
+ const response = await fetch(
+ `${process.env.NEXTAUTH_URL}/api/file/s3/get-presigned-get-url`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ Authorization: `Bearer ${process.env.INTERNAL_API_KEY}`,
+ },
+ body: JSON.stringify({ key: key }),
+ },
+ );
- try {
- const response = await fetch(
- `${process.env.NEXTAUTH_URL}/api/file/s3/get-presigned-get-url`,
- {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- Authorization: `Bearer ${process.env.INTERNAL_API_KEY}`,
- },
- body: JSON.stringify({ key: key }),
- },
- );
-
- if (!response.ok) {
- const contentType = response.headers.get("content-type");
- let error: any;
-
- if (contentType && contentType.includes("application/json")) {
- try {
- error = await response.json();
- } catch (parseError) {
- error = { message: await response.text() || `Request failed with status ${response.status}` };
- }
- } else {
- const textError = await response.text();
- error = { message: textError || `Request failed with status ${response.status}` };
- }
-
- return res.status(response.status).json(error);
+ if (!response.ok) {
+ const contentType = response.headers.get("content-type");
+ let error: any;
+
+ if (contentType && contentType.includes("application/json")) {
+ try {
+ error = await response.json();
+ } catch (parseError) {
+ error = {
+ message:
+ (await response.text()) ||
+ `Request failed with status ${response.status}`,
+ };
}
+ } else {
+ const textError = await response.text();
+ error = {
+ message: textError || `Request failed with status ${response.status}`,
+ };
+ }
- const data = await response.json();
- return res.status(200).json(data);
- } catch (error) {
- console.error("Proxy error:", error);
- return res.status(500).json({ message: "Internal server error" });
+ return res.status(response.status).json(error);
}
+
+ const data = await response.json();
+ return res.status(200).json(data);
+ } catch (error) {
+ console.error("Proxy error:", error);
+ return res.status(500).json({ message: "Internal server error" });
+ }
}
diff --git a/pages/api/documents/[id]/preview-data.ts b/pages/api/teams/[teamId]/documents/[id]/preview-data.ts
similarity index 91%
rename from pages/api/documents/[id]/preview-data.ts
rename to pages/api/teams/[teamId]/documents/[id]/preview-data.ts
index 24be708f..e645b359 100644
--- a/pages/api/documents/[id]/preview-data.ts
+++ b/pages/api/teams/[teamId]/documents/[id]/preview-data.ts
@@ -7,7 +7,7 @@ import prisma from "@/lib/prisma";
import { CustomUser } from "@/lib/types";
import { log } from "@/lib/utils";
-import { authOptions } from "../../auth/[...nextauth]";
+import { authOptions } from "../../../../auth/[...nextauth]";
export default async function handle(
req: NextApiRequest,
@@ -23,10 +23,26 @@ export default async function handle(
return res.status(401).json({ message: "Unauthorized" });
}
- const { id: documentId } = req.query as { id: string };
+ const { id: documentId, teamId } = req.query as {
+ id: string;
+ teamId: string;
+ };
const userId = (session.user as CustomUser).id;
try {
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ users: {
+ some: { userId },
+ },
+ },
+ });
+
+ if (!team) {
+ return res.status(403).json({ message: "Access denied" });
+ }
+
// Fetch document and verify team membership
const document = await prisma.document.findUnique({
where: { id: documentId },