Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

added ratelimit

Steven Tey6f6b61aca7af
diff --git a/lib/auth.ts b/lib/auth.ts
index 4ff5ab35ce..224a1886da 100644
--- a/lib/auth.ts
+++ b/lib/auth.ts
@@ -5,6 +5,7 @@ import { type Link as LinkProps } from "@prisma/client";
import { PlanProps, ProjectProps, UserProps } from "#/lib/types";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import { createHash } from "crypto";
+import { ratelimit } from "./upstash";
export interface Session {
user: {
@@ -254,6 +255,18 @@ const withLinksAuth =
if (!user) {
return res.status(401).end("Unauthorized: Invalid API key.");
}
+ const { success, limit, reset, remaining } = await ratelimit(
+ 10,
+ "1 s",
+ ).limit(apiKey);
+ res.setHeader("X-RateLimit-Limit", limit.toString());
+ res.setHeader("X-RateLimit-Remaining", remaining.toString());
+ res.setHeader("X-RateLimit-Reset", reset.toString());
+ res.setHeader("Retry-After", reset.toString());
+
+ if (!success) {
+ return res.status(429).end("Too many requests.");
+ }
session = {
user: {
id: user.id,
diff --git a/lib/upstash.ts b/lib/upstash.ts
index ba875c6a5b..a14c8c0ec3 100644
--- a/lib/upstash.ts
+++ b/lib/upstash.ts
@@ -28,7 +28,13 @@ export const ratelimit = (
: // if Redis is not configured, return a dummy ratelimiter
// with the function limit() that always returns true
{
- limit: () => ({ success: true }),
+ limit: () => ({
+ success: true,
+ limit: 10,
+ remaining: 10,
+ reset: 0,
+ retryAfter: 0,
+ }),
};
};