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 to login, added ChatGPT to list of bots

Steven Tey260657830a78
diff --git a/lib/constants/index.ts b/lib/constants/index.ts
index e10f0a1022..07eeb1550b 100644
--- a/lib/constants/index.ts
+++ b/lib/constants/index.ts
@@ -5,6 +5,7 @@ export const LOCALHOST_GEO_DATA = {
latitude: "37.7695",
longitude: "-122.385",
};
+export const LOCALHOST_IP = "63.141.56.109";
export const INTERVALS = [
{
diff --git a/lib/middleware/utils.ts b/lib/middleware/utils.ts
index 3748b4f35e..094259e2cf 100644
--- a/lib/middleware/utils.ts
+++ b/lib/middleware/utils.ts
@@ -17,11 +17,12 @@ export const detectBot = (req: NextRequest) => {
if (ua) {
/* Note:
* - bot is for most bots & crawlers
+ * - ChatGPT is for ChatGPT
* - facebookexternalhit is for Facebook crawler
* - WhatsApp is for WhatsApp crawler
* - MetaInspector is for https://metatags.io/
*/
- return /bot|facebookexternalhit|WhatsApp|google|baidu|bing|msn|duckduckbot|teoma|slurp|yandex|MetaInspector/i.test(
+ return /bot|chatgpt|facebookexternalhit|WhatsApp|google|baidu|bing|msn|duckduckbot|teoma|slurp|yandex|MetaInspector/i.test(
ua,
);
}
diff --git a/lib/upstash.ts b/lib/upstash.ts
index 38dc8db299..1aea3cf378 100644
--- a/lib/upstash.ts
+++ b/lib/upstash.ts
@@ -8,15 +8,25 @@ export const redis = new Redis({
token: process.env.UPSTASH_REDIS_REST_TOKEN || "",
});
-// Create a new ratelimiter, that allows 10 requests per 10 seconds
-export const ratelimit =
- process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN
+// Create a new ratelimiter, that allows 10 requests per 10 seconds by default
+export const ratelimit = (
+ requests: number = 10,
+ seconds:
+ | `${number} ms`
+ | `${number} s`
+ | `${number} m`
+ | `${number} h`
+ | `${number} d` = "10 s",
+) => {
+ return process.env.UPSTASH_REDIS_REST_URL &&
+ process.env.UPSTASH_REDIS_REST_TOKEN
? new Ratelimit({
redis: Redis.fromEnv(),
- limiter: Ratelimit.slidingWindow(10, "10 s"),
+ limiter: Ratelimit.slidingWindow(requests, seconds),
analytics: true,
})
: null;
+};
// only for dub.sh public demo
export async function setRandomKey(
diff --git a/package.json b/package.json
index e48e334a02..b0574565d6 100644
--- a/package.json
+++ b/package.json
@@ -29,6 +29,7 @@
"@upstash/ratelimit": "^0.3.6",
"@upstash/redis": "^1.18.0",
"@vercel/analytics": "^0.1.5",
+ "@vercel/edge": "^0.3.1",
"@vercel/edge-config": "^0.1.0-canary.15",
"@vercel/og": "^0.0.21",
"@visx/axis": "^2.14.0",
diff --git a/pages/api/auth/account-exists.ts b/pages/api/auth/account-exists.ts
index 53e8e9a1e5..1dc92f608f 100644
--- a/pages/api/auth/account-exists.ts
+++ b/pages/api/auth/account-exists.ts
@@ -1,22 +1,35 @@
-import { NextApiRequest, NextApiResponse } from "next";
-import prisma from "@/lib/prisma";
+import { NextRequest } from "next/server";
+import { ratelimit } from "@/lib/upstash";
+import { ipAddress } from "@vercel/edge";
+import { LOCALHOST_IP } from "@/lib/constants";
+import { conn } from "@/lib/planetscale";
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
+export const config = {
+ runtime: "edge",
+};
+
+export default async function handler(req: NextRequest) {
if (req.method === "POST") {
- const { email } = req.body;
- const user = await prisma.user.findUnique({
- where: { email },
- select: { email: true },
- });
+ const ip = ipAddress(req) || LOCALHOST_IP;
+ const { success } = await ratelimit(5, "1 m").limit(ip);
+ if (!success) {
+ return new Response("Don't DDoS me pls 🥺", { status: 429 });
+ }
+
+ const { email } = (await req.json()) as { email: string };
+
+ const user = await conn
+ .execute("SELECT email FROM User WHERE email = ?", [email])
+ .then((res) => res.rows[0]);
+
if (user) {
- return res.status(200).json({ exists: true });
+ return new Response(JSON.stringify({ exists: true }));
}
- return res.status(200).json({ exists: false });
+ return new Response(JSON.stringify({ exists: false }));
} else {
- res.setHeader("Allow", ["POST"]);
- return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
+ return new Response("Method not allowed", {
+ status: 405,
+ statusText: "Method not allowed",
+ });
}
}
diff --git a/pages/api/edge/metatags.ts b/pages/api/edge/metatags.ts
index 760111fbc0..d7b64da874 100644
--- a/pages/api/edge/metatags.ts
+++ b/pages/api/edge/metatags.ts
@@ -3,6 +3,8 @@ import { parse } from "node-html-parser";
import { isValidUrl } from "@/lib/utils";
import { ratelimit, recordMetatags } from "@/lib/upstash";
import { getToken } from "next-auth/jwt";
+import { ipAddress } from "@vercel/edge";
+import { LOCALHOST_IP } from "@/lib/constants";
export const config = {
runtime: "edge",
@@ -21,7 +23,8 @@ export default async function handler(req: NextRequest, ev: NextFetchEvent) {
secret: process.env.NEXTAUTH_SECRET,
});
if (!session?.email) {
- const { success } = await ratelimit.limit("metatags");
+ const ip = ipAddress(req) || LOCALHOST_IP;
+ const { success } = await ratelimit().limit(ip);
if (!success) {
return new Response("Don't DDoS me pls 🥺", { status: 429 });
}
diff --git a/pages/api/site/feedback.tsx b/pages/api/site/feedback.tsx
index b2fa784e5b..01bc98796a 100644
--- a/pages/api/site/feedback.tsx
+++ b/pages/api/site/feedback.tsx
@@ -8,7 +8,7 @@ export default async function handler(
res: NextApiResponse,
) {
if (req.method === "POST") {
- const { success } = await ratelimit.limit("feedback");
+ const { success } = await ratelimit().limit("feedback");
if (!success) {
res.status(429).json({ error: "Don't DDoS me pls 🥺" });
}
diff --git a/pages/app/login.tsx b/pages/app/login.tsx
index f03349cd86..ab7a8356b5 100644
--- a/pages/app/login.tsx
+++ b/pages/app/login.tsx
@@ -40,26 +40,31 @@ export default function Login() {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email }),
- }).then(async (res) => {
- const { exists } = await res.json();
- if (exists) {
- signIn("email", {
- email,
- redirect: false,
- }).then((res) => {
+ })
+ .then(async (res) => {
+ const { exists } = await res.json();
+ if (exists) {
+ signIn("email", {
+ email,
+ redirect: false,
+ }).then((res) => {
+ setSignInClicked(false);
+ if (res?.ok && !res?.error) {
+ setEmail("");
+ setButtonText("Email sent - check your inbox!");
+ } else {
+ setButtonText("Error sending email - try again?");
+ }
+ });
+ } else {
+ setNoSuchAccount(true);
setSignInClicked(false);
- if (res?.ok && !res?.error) {
- setEmail("");
- setButtonText("Email sent - check your inbox!");
- } else {
- setButtonText("Error sending email - try again?");
- }
- });
- } else {
- setNoSuchAccount(true);
+ }
+ })
+ .catch(() => {
setSignInClicked(false);
- }
- });
+ setButtonText("Error sending email - try again?");
+ });
}}
className="flex flex-col space-y-4 bg-gray-50 px-4 py-8 sm:px-16"
>
diff --git a/pages/app/register.tsx b/pages/app/register.tsx
index 9a1dd2c678..d1cc4540cc 100644
--- a/pages/app/register.tsx
+++ b/pages/app/register.tsx
@@ -38,27 +38,32 @@ export default function Login() {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email }),
- }).then(async (res) => {
- const { exists } = await res.json();
- if (!exists) {
- signIn("email", {
- email,
- redirect: false,
- callbackUrl: "/welcome",
- }).then((res) => {
+ })
+ .then(async (res) => {
+ const { exists } = await res.json();
+ if (!exists) {
+ signIn("email", {
+ email,
+ redirect: false,
+ callbackUrl: "/welcome",
+ }).then((res) => {
+ setSignInClicked(false);
+ if (res?.ok && !res?.error) {
+ setEmail("");
+ setButtonText("Email sent - check your inbox!");
+ } else {
+ setButtonText("Error sending email - try again?");
+ }
+ });
+ } else {
+ setAccountExists(true);
setSignInClicked(false);
- if (res?.ok && !res?.error) {
- setEmail("");
- setButtonText("Email sent - check your inbox!");
- } else {
- setButtonText("Error sending email - try again?");
- }
- });
- } else {
- setAccountExists(true);
+ }
+ })
+ .catch(() => {
setSignInClicked(false);
- }
- });
+ setButtonText("Error sending email - try again?");
+ });
}}
className="flex flex-col space-y-4 bg-gray-50 px-4 py-8 sm:px-16"
>
diff --git a/yarn.lock b/yarn.lock
index cbc4198869..417ff9a4f4 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1686,6 +1686,11 @@
resolved "https://registry.yarnpkg.com/@vercel/edge-config/-/edge-config-0.1.0-canary.15.tgz#eee68c1b1350dc6a987fb519e85241b4d9f67e64"
integrity sha512-CgafJ+qlF2XZU5z6YJ/Dc06A9z/3KHeuenQqZdQQNMEm1yYyZcKkL3i68qSXT/4h4axZ2oqzcdwHJA2A6Yqt9g==
+"@vercel/edge@^0.3.1":
+ version "0.3.1"
+ resolved "https://registry.yarnpkg.com/@vercel/edge/-/edge-0.3.1.tgz#6ee14551d109a1e06a7e25cab97df98dc5b5a58c"
+ integrity sha512-NdJxoaUI/AMvSu9dBM5MA1mxzk+Xo1sMrjyNRtNGsH5iKYyMdMWNUEvHdkyn1kN6opM03rQHYOYgXhBwNyIfdQ==
+
"@vercel/og@^0.0.21":
version "0.0.21"
resolved "https://registry.yarnpkg.com/@vercel/og/-/og-0.0.21.tgz#9d2421a241a0cfbdc3841b88bf323d980339da40"