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.

use identity hash for rate limiting

Steven Tey549941c6caae
diff --git a/apps/web/app/api/analytics/edge/[endpoint]/route.ts b/apps/web/app/api/analytics/edge/[endpoint]/route.ts
index 43a5751654..b6781d171a 100644
--- a/apps/web/app/api/analytics/edge/[endpoint]/route.ts
+++ b/apps/web/app/api/analytics/edge/[endpoint]/route.ts
@@ -1,15 +1,10 @@
import { getAnalytics } from "@/lib/analytics";
import { exceededLimitError } from "@/lib/api/errors";
+import { getIdentityHash } from "@/lib/edge";
import { isBlacklistedReferrer } from "@/lib/edge-config";
import { getDomainOrLink, getProjectViaEdge } from "@/lib/planetscale";
import { ratelimit } from "@/lib/upstash";
-import {
- DEMO_LINK_ID,
- DUB_PROJECT_ID,
- LOCALHOST_IP,
- getSearchParams,
-} from "@dub/utils";
-import { ipAddress } from "@vercel/edge";
+import { DEMO_LINK_ID, DUB_PROJECT_ID, getSearchParams } from "@dub/utils";
import { NextResponse, type NextRequest } from "next/server";
export const runtime = "edge";
@@ -31,11 +26,11 @@ export const GET = async (
if (await isBlacklistedReferrer(req.headers.get("referer"))) {
return new Response("Don't DDoS me pls 🥺", { status: 429 });
}
- const ip = ipAddress(req) || LOCALHOST_IP;
+ const identity_hash = await getIdentityHash(req);
const { success } = await ratelimit(
15,
endpoint === "clicks" ? "10 s" : "1 h",
- ).limit(`${ip}:${domain}:${key}:${endpoint}`);
+ ).limit(`demo-analytics:${identity_hash}:${endpoint}`);
if (!success) {
return new Response("Don't DDoS me pls 🥺", { status: 429 });
diff --git a/apps/web/app/api/auth/account-exists/route.ts b/apps/web/app/api/auth/account-exists/route.ts
index 6bdefa12c7..cd3877bacd 100644
--- a/apps/web/app/api/auth/account-exists/route.ts
+++ b/apps/web/app/api/auth/account-exists/route.ts
@@ -1,15 +1,16 @@
+import { getIdentityHash } from "@/lib/edge";
import { isWhitelistedEmail } from "@/lib/edge-config";
import { conn } from "@/lib/planetscale";
import { ratelimit } from "@/lib/upstash";
-import { LOCALHOST_IP } from "@dub/utils";
-import { ipAddress } from "@vercel/edge";
import { NextRequest, NextResponse } from "next/server";
export const runtime = "edge";
export async function POST(req: NextRequest) {
- const ip = ipAddress(req) || LOCALHOST_IP;
- const { success } = await ratelimit(5, "1 m").limit(ip);
+ const identity_hash = await getIdentityHash(req);
+ const { success } = await ratelimit(5, "1 m").limit(
+ `account-exists:${identity_hash}`,
+ );
if (!success) {
return new Response("Don't DDoS me pls 🥺", { status: 429 });
}
diff --git a/apps/web/app/api/metatags/route.ts b/apps/web/app/api/metatags/route.ts
index b22fb83b92..33bd1a586a 100644
--- a/apps/web/app/api/metatags/route.ts
+++ b/apps/web/app/api/metatags/route.ts
@@ -1,9 +1,9 @@
import { ratelimit } from "@/lib/upstash";
-import { LOCALHOST_IP, isValidUrl } from "@dub/utils";
-import { ipAddress } from "@vercel/edge";
+import { isValidUrl } from "@dub/utils";
import { getToken } from "next-auth/jwt";
import { NextRequest } from "next/server";
import { getMetaTags } from "./utils";
+import { getIdentityHash } from "@/lib/edge";
export const runtime = "edge";
@@ -19,8 +19,8 @@ export async function GET(req: NextRequest) {
secret: process.env.NEXTAUTH_SECRET,
});
if (!session?.email) {
- const ip = ipAddress(req) || LOCALHOST_IP;
- const { success } = await ratelimit().limit(ip);
+ const identity_hash = await getIdentityHash(req);
+ const { success } = await ratelimit().limit(`metatags:${identity_hash}`);
if (!success) {
return new Response("Don't DDoS me pls 🥺", { status: 429 });
}
diff --git a/apps/web/app/api/providers/route.ts b/apps/web/app/api/providers/route.ts
new file mode 100644
index 0000000000..c3af32ad11
--- /dev/null
+++ b/apps/web/app/api/providers/route.ts
@@ -0,0 +1,86 @@
+import { getIdentityHash } from "@/lib/edge";
+import { ratelimit } from "@/lib/upstash";
+import { fetchWithTimeout, getUrlFromString } from "@dub/utils";
+import { getToken } from "next-auth/jwt";
+import { NextRequest, NextResponse } from "next/server";
+
+export const runtime = "edge";
+
+export async function GET(req: NextRequest) {
+ // Rate limit if user is not logged in
+ const session = await getToken({
+ req,
+ secret: process.env.NEXTAUTH_SECRET,
+ });
+ if (!session?.email) {
+ const identity_hash = await getIdentityHash(req);
+ const { success } = await ratelimit().limit(`providers:${identity_hash}`);
+ if (!success) {
+ return new Response("Don't DDoS me pls 🥺", { status: 429 });
+ }
+ }
+
+ const urlParam = req.nextUrl.searchParams.get("url");
+ const url = getUrlFromString(urlParam || "");
+ if (!url) {
+ return new Response("Invalid URL", { status: 400 });
+ }
+
+ const urlObject = new URL(url);
+
+ const domain = urlObject.hostname;
+ const dns = await fetchWithTimeout(
+ `https://dns.google/resolve?name=${domain}`,
+ )
+ .then((r) => r.json())
+ .catch(() => null);
+
+ if (
+ dns &&
+ dns.Answer &&
+ dns.Answer.length > 0 &&
+ dns.Answer.some(
+ (a: { data: string }) =>
+ a.data === "cname.bitly.com" ||
+ a.data === "67.199.248.12" ||
+ a.data === "67.199.248.13",
+ )
+ ) {
+ return NextResponse.json({
+ provider: "bitly",
+ });
+ }
+
+ urlObject.pathname = "/xyz";
+
+ const headers = await fetchWithTimeout(urlObject.toString(), {
+ redirect: "manual",
+ })
+ .then((r) => ({
+ engine: r.headers.get("engine"),
+ poweredBy: r.headers.get("x-powered-by"),
+ }))
+ .catch(() => null);
+
+ if (headers) {
+ if (headers.engine?.includes("Rebrandly")) {
+ return NextResponse.json({
+ provider: "rebrandly",
+ });
+ }
+ if (headers.poweredBy?.includes("Short.io")) {
+ return NextResponse.json({
+ provider: "short",
+ });
+ }
+ if (headers.poweredBy?.includes("Dub.co")) {
+ return NextResponse.json({
+ provider: "dub",
+ });
+ }
+ }
+
+ return NextResponse.json({
+ provider: "unknown",
+ });
+}
diff --git a/apps/web/app/api/qr/route.tsx b/apps/web/app/api/qr/route.tsx
index 08eea0b527..6e89877ebc 100644
--- a/apps/web/app/api/qr/route.tsx
+++ b/apps/web/app/api/qr/route.tsx
@@ -1,3 +1,4 @@
+import { getIdentityHash } from "@/lib/edge";
import {
DEFAULT_BGCOLOR,
DEFAULT_FGCOLOR,
@@ -7,8 +8,6 @@ import {
} from "@/lib/qr/constants";
import { QRCodeSVG } from "@/lib/qr/utils";
import { ratelimit } from "@/lib/upstash";
-import { LOCALHOST_IP } from "@dub/utils";
-import { ipAddress } from "@vercel/edge";
import { getToken } from "next-auth/jwt";
import { ImageResponse } from "next/og";
import { NextRequest } from "next/server";
@@ -22,8 +21,8 @@ export async function GET(req: NextRequest) {
secret: process.env.NEXTAUTH_SECRET,
});
if (!session?.email) {
- const ip = ipAddress(req) || LOCALHOST_IP;
- const { success } = await ratelimit().limit(ip);
+ const identity_hash = await getIdentityHash(req);
+ const { success } = await ratelimit().limit(`qr:${identity_hash}`);
if (!success) {
return new Response("Don't DDoS me pls 🥺", { status: 429 });
}
diff --git a/apps/web/app/api/unsplash/search/route.ts b/apps/web/app/api/unsplash/search/route.ts
index 900f007d65..ece28b4b95 100644
--- a/apps/web/app/api/unsplash/search/route.ts
+++ b/apps/web/app/api/unsplash/search/route.ts
@@ -1,8 +1,7 @@
import { ratelimit } from "@/lib/upstash";
-import { LOCALHOST_IP } from "@dub/utils";
-import { ipAddress } from "@vercel/edge";
import { NextResponse } from "next/server";
import { unsplash } from "../utils";
+import { getIdentityHash } from "@/lib/edge";
export const runtime = "edge";
@@ -18,8 +17,10 @@ export async function GET(req: Request) {
return new Response("Unsplash API key not found", { status: 400 });
}
- const ip = ipAddress(req) || LOCALHOST_IP;
- const { success } = await ratelimit(10, "10 s").limit(ip);
+ const identity_hash = await getIdentityHash(req);
+ const { success } = await ratelimit(10, "10 s").limit(
+ `unsplash:${identity_hash}`,
+ );
if (!success) {
return new Response("Don't DDoS me pls 🥺", { status: 429 });
}
diff --git a/apps/web/lib/edge.ts b/apps/web/lib/edge.ts
new file mode 100644
index 0000000000..551cd0f812
--- /dev/null
+++ b/apps/web/lib/edge.ts
@@ -0,0 +1,15 @@
+import { LOCALHOST_IP, hashStringSHA256 } from "@dub/utils";
+import { ipAddress } from "@vercel/edge";
+import { userAgent } from "next/server";
+
+/**
+ * Combine IP + UA to create a unique identifier for the user (for deduplication)
+ */
+export async function getIdentityHash(req: Request) {
+ const ip = ipAddress(req) || LOCALHOST_IP;
+ console.log(ip);
+ const ua = userAgent(req);
+ const hash = await hashStringSHA256(`${ip}-${ua.ua}`);
+ console.log(hash);
+ return hash;
+}
diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.ts
index 13e82ee7a0..978af31864 100644
--- a/apps/web/lib/middleware/link.ts
+++ b/apps/web/lib/middleware/link.ts
@@ -1,13 +1,7 @@
import { detectBot, getFinalUrl, parse } from "@/lib/middleware/utils";
import { recordClick } from "@/lib/tinybird";
import { formatRedisLink, ratelimit, redis } from "@/lib/upstash";
-import {
- DUB_HEADERS,
- LEGAL_PROJECT_ID,
- LOCALHOST_GEO_DATA,
- LOCALHOST_IP,
-} from "@dub/utils";
-import { ipAddress } from "@vercel/edge";
+import { DUB_HEADERS, LEGAL_PROJECT_ID, LOCALHOST_GEO_DATA } from "@dub/utils";
import {
NextFetchEvent,
NextRequest,
@@ -17,6 +11,7 @@ import {
import { isBlacklistedReferrer } from "../edge-config";
import { getLinkViaEdge } from "../planetscale";
import { RedisLinkProps } from "../types";
+import { getIdentityHash } from "../edge";
export default async function LinkMiddleware(
req: NextRequest,
@@ -39,9 +34,9 @@ export default async function LinkMiddleware(
if (await isBlacklistedReferrer(req.headers.get("referer"))) {
return new Response("Don't DDoS me pls 🥺", { status: 429 });
}
- const ip = ipAddress(req) || LOCALHOST_IP;
+ const identity_hash = await getIdentityHash(req);
const { success } = await ratelimit(10, "1 d").limit(
- `${ip}:${domain}:${key}`,
+ `demo-click:${identity_hash}`,
);
if (!success) {
diff --git a/apps/web/lib/tinybird.ts b/apps/web/lib/tinybird.ts
index 03fc4513ce..0461565a9f 100644
--- a/apps/web/lib/tinybird.ts
+++ b/apps/web/lib/tinybird.ts
@@ -1,17 +1,15 @@
import {
LOCALHOST_GEO_DATA,
- LOCALHOST_IP,
capitalize,
getDomainWithoutWWW,
- hashStringSHA256,
nanoid,
} from "@dub/utils";
-import { ipAddress } from "@vercel/edge";
import { NextRequest, userAgent } from "next/server";
import { detectBot } from "./middleware/utils";
import { conn } from "./planetscale";
import { LinkProps } from "./types";
import { ratelimit } from "./upstash";
+import { getIdentityHash } from "./edge";
/**
* Recording clicks with geo, ua, referer and timestamp data
@@ -34,9 +32,7 @@ export async function recordClick({
const geo = process.env.VERCEL === "1" ? req.geo : LOCALHOST_GEO_DATA;
const ua = userAgent(req);
const referer = req.headers.get("referer");
- const ip = ipAddress(req) || LOCALHOST_IP;
- // combine IP + UA to create a unique identifier for the user (for deduplication)
- const identity_hash = await hashStringSHA256(`${ip}-${ua.ua}`);
+ const identity_hash = await getIdentityHash(req);
// if in production / preview env, deduplicate clicks from the same IP & link ID – only record 1 click per hour
if (process.env.VERCEL === "1") {
const { success } = await ratelimit(2, "1 h").limit(