Skip to content

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

feat: introduce ratelimiting to endpoint

Marc Seitz1193a585e65e
diff --git a/lib/swr/use-document.ts b/lib/swr/use-document.ts
index 170d5877..f3ab8ccd 100644
--- a/lib/swr/use-document.ts
+++ b/lib/swr/use-document.ts
@@ -2,10 +2,11 @@ import { useRouter } from "next/router";
import { useTeam } from "@/context/team-context";
import { View } from "@prisma/client";
+import { toast } from "sonner";
import useSWR from "swr";
+
import { DocumentWithVersion, LinkWithViews } from "@/lib/types";
import { fetcher } from "@/lib/utils";
-import { toast } from "sonner";
export function useDocument() {
const router = useRouter();
@@ -27,15 +28,20 @@ export function useDocument() {
)}`,
fetcher,
{
- dedupingInterval: 10000,
+ // Reduce background-driven revalidation to avoid excessive API traffic
+ dedupingInterval: 30000,
+ revalidateOnFocus: false,
+ revalidateOnReconnect: false,
+ revalidateIfStale: false,
onError: (err) => {
if (err.status === 404) {
toast.error("Document not found", {
- description: "The document you're looking for doesn't exist or has been moved.",
+ description:
+ "The document you're looking for doesn't exist or has been moved.",
});
router.replace("/documents");
}
- }
+ },
},
);
diff --git a/pages/api/teams/[teamId]/documents/[id]/index.ts b/pages/api/teams/[teamId]/documents/[id]/index.ts
index 06468cd2..b22d5a6d 100644
--- a/pages/api/teams/[teamId]/documents/[id]/index.ts
+++ b/pages/api/teams/[teamId]/documents/[id]/index.ts
@@ -5,6 +5,7 @@ import { getServerSession } from "next-auth/next";
import { TeamError, errorhandler } from "@/lib/errorHandler";
import { deleteFile } from "@/lib/files/delete-file-server";
import prisma from "@/lib/prisma";
+import { ratelimit } from "@/lib/redis";
import { getTeamWithUsersAndDocument } from "@/lib/team/helper";
import { CustomUser } from "@/lib/types";
import { serializeFileSize } from "@/lib/utils";
@@ -27,6 +28,20 @@ export default async function handle(
const userId = (session.user as CustomUser).id;
try {
+ // Per-user, per-document rate limit to prevent abuse
+ // Default: 120 requests per minute per user per document
+ const { success, limit, remaining, reset } = await ratelimit(
+ 120,
+ "1 m",
+ ).limit(`doc:${docId}:team:${teamId}:user:${userId}`);
+
+ res.setHeader("X-RateLimit-Limit", limit.toString());
+ res.setHeader("X-RateLimit-Remaining", remaining.toString());
+ res.setHeader("X-RateLimit-Reset", reset.toString());
+ if (!success) {
+ return res.status(429).json({ error: "Too many requests" });
+ }
+
const { document } = await getTeamWithUsersAndDocument({
teamId,
userId,