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 rate limiting

Steven Tey5306d5184bcd
diff --git a/lib/constants.ts b/lib/constants.ts
index 0532e6c551..6cac766793 100644
--- a/lib/constants.ts
+++ b/lib/constants.ts
@@ -13,7 +13,7 @@ export const FRAMER_MOTION_LIST_ITEM_VARIANTS = {
show: { scale: 1, opacity: 1, transition: { type: "spring" } },
};
-export const RESERVED_KEYS = ["pricing", "about", "stats"];
+export const RESERVED_KEYS = ["pricing", "about", "stats", "placeholder"];
export const COUNTRIES: { [key: string]: string } = {
AF: "Afghanistan",
diff --git a/lib/middleware/link.ts b/lib/middleware/link.ts
index 3519bddea8..12af3945eb 100644
--- a/lib/middleware/link.ts
+++ b/lib/middleware/link.ts
@@ -2,29 +2,53 @@ import { NextRequest, NextFetchEvent, NextResponse } from "next/server";
import { redis, recordClick } from "@/lib/upstash";
import { parse } from "@/lib/middleware/utils";
import { LinkProps } from "../types";
+import { Ratelimit } from "@upstash/ratelimit";
+import { Redis } from "@upstash/redis";
+
+const ratelimit = new Ratelimit({
+ redis: Redis.fromEnv(),
+ limiter: Ratelimit.slidingWindow(10, "10 s"),
+});
export default async function LinkMiddleware(
req: NextRequest,
ev: NextFetchEvent
) {
+ const url = req.nextUrl.clone();
const { hostname, key } = parse(req);
if (!hostname || !key) {
return NextResponse.next();
}
- const response = await redis.hget<Omit<LinkProps, "key">>(
- `${hostname}:links`,
- key
+ const ip = req.ip ?? "127.0.0.1";
+ const { success, limit, reset, remaining } = await ratelimit.limit(
+ `dub_${ip}`
);
- const target = response?.url;
- if (target) {
- ev.waitUntil(recordClick(hostname, key, req)); // increment click count
- return NextResponse.redirect(target);
+ let res;
+
+ if (success) {
+ // if ratelimit is not exceeded
+ const response = await redis.hget<Omit<LinkProps, "key">>(
+ `${hostname}:links`,
+ key
+ );
+ const target = response?.url;
+
+ if (target) {
+ ev.waitUntil(recordClick(hostname, key, req)); // increment click count
+ res = NextResponse.redirect(target);
+ } else {
+ url.pathname = "/";
+ res = NextResponse.redirect(url);
+ }
} else {
- const url = req.nextUrl.clone();
url.pathname = "/";
- return NextResponse.redirect(url);
+ res = NextResponse.redirect(url); // TODO: add a rate limit page
+ res.headers.set("X-RateLimit-Limit", limit.toString());
+ res.headers.set("X-RateLimit-Remaining", remaining.toString());
+ res.headers.set("X-RateLimit-Reset", reset.toString());
}
+ return res;
}
diff --git a/package-lock.json b/package-lock.json
index 4b58463e35..0cbed3193b 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -10,6 +10,7 @@
"@prisma/client": "^4.3.1",
"@radix-ui/react-tooltip": "^1.0.0",
"@tailwindcss/forms": "^0.5.3",
+ "@upstash/ratelimit": "^0.1.5",
"@upstash/redis": "^1.12.0",
"@visx/axis": "^2.12.2",
"@visx/event": "^2.6.0",
@@ -869,6 +870,14 @@
"@types/geojson": "*"
}
},
+ "node_modules/@upstash/ratelimit": {
+ "version": "0.1.5",
+ "resolved": "https://registry.npmjs.org/@upstash/ratelimit/-/ratelimit-0.1.5.tgz",
+ "integrity": "sha512-v0zq3Xpq42HQBvXDvm0C4djYvKC5TjHG29uCpbIQcOw0znJNroHewI8y4Yk4tBeEF1rvj2RjDkFihjCp6uTExQ==",
+ "peerDependencies": {
+ "@upstash/redis": "^1.4.0"
+ }
+ },
"node_modules/@upstash/redis": {
"version": "1.12.0",
"resolved": "https://registry.npmjs.org/@upstash/redis/-/redis-1.12.0.tgz",
@@ -5748,6 +5757,12 @@
"@types/geojson": "*"
}
},
+ "@upstash/ratelimit": {
+ "version": "0.1.5",
+ "resolved": "https://registry.npmjs.org/@upstash/ratelimit/-/ratelimit-0.1.5.tgz",
+ "integrity": "sha512-v0zq3Xpq42HQBvXDvm0C4djYvKC5TjHG29uCpbIQcOw0znJNroHewI8y4Yk4tBeEF1rvj2RjDkFihjCp6uTExQ==",
+ "requires": {}
+ },
"@upstash/redis": {
"version": "1.12.0",
"resolved": "https://registry.npmjs.org/@upstash/redis/-/redis-1.12.0.tgz",
diff --git a/package.json b/package.json
index 7801a7c93b..22093d592e 100644
--- a/package.json
+++ b/package.json
@@ -11,6 +11,7 @@
"@prisma/client": "^4.3.1",
"@radix-ui/react-tooltip": "^1.0.0",
"@tailwindcss/forms": "^0.5.3",
+ "@upstash/ratelimit": "^0.1.5",
"@upstash/redis": "^1.12.0",
"@visx/axis": "^2.12.2",
"@visx/event": "^2.6.0",
diff --git a/pages/api/projects/[slug]/domains/[domain]/verify.ts b/pages/api/projects/[slug]/domains/[domain]/verify.ts
index 3fef1c38c7..f9c6258d22 100644
--- a/pages/api/projects/[slug]/domains/[domain]/verify.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/verify.ts
@@ -1,10 +1,11 @@
import { withProjectAuth } from "@/lib/auth";
import { NextApiRequest, NextApiResponse } from "next";
import { DomainVerificationStatusProps } from "@/lib/types";
+import prisma from "@/lib/prisma";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
- const { domain } = req.query as { domain: string };
+ const { slug, domain } = req.query as { slug: string; domain: string };
let status: DomainVerificationStatusProps = "Valid Configuration";
const [domainResponse, configResponse] = await Promise.all([
@@ -67,15 +68,39 @@ export default withProjectAuth(
return res.status(200).json({
status,
- response: { configJson, domainJson, verificationResponse },
+ response: {
+ configJson,
+ domainJson,
+ verificationResponse,
+ },
});
}
- status = configJson.misconfigured ? "Invalid Configuration" : status;
+ let prismaResponse = null;
+ if (!configJson.misconfigured) {
+ prismaResponse = await prisma.project.update({
+ where: {
+ slug,
+ },
+ data: {
+ domainVerified: true,
+ },
+ });
+ } else {
+ status = "Invalid Configuration";
+ prismaResponse = await prisma.project.update({
+ where: {
+ slug,
+ },
+ data: {
+ domainVerified: false,
+ },
+ });
+ }
return res.status(200).json({
status,
- response: { configJson, domainJson },
+ response: { configJson, domainJson, prismaResponse },
});
}
);
diff --git a/pages/index.tsx b/pages/index.tsx
index c0d668685b..72e7e80c88 100644
--- a/pages/index.tsx
+++ b/pages/index.tsx
@@ -7,6 +7,7 @@ import PlaceholderCard from "@/components/home/placeholder-card";
import { LoadingDots } from "@/components/shared/icons";
import { motion } from "framer-motion";
import { LinkProps } from "@/lib/types";
+import Globe from "@/components/home/about/globe";
export default function Home() {
const [saving, setSaving] = useState(false);
@@ -17,20 +18,12 @@ export default function Home() {
<HomeLayout>
<main className="my-36 max-w-md mx-auto sm:px-0 px-2.5">
<div className="my-5 text-center">
- <h1 className="text-6xl font-bold text-black dark:text-white">Dub</h1>
+ <h1 className="text-6xl font-display font-bold text-black dark:text-white">
+ Dub
+ </h1>
<p className="text-gray-600 dark:text-white text-xl mt-5">
- An open-source link shortener built with <br />
- <VercelEdgeFunctions /> and{" "}
- <a
- className="text-transparent bg-clip-text bg-gradient-to-r from-green-400 to-green-700
-"
- href="https://upstash.com/redis"
- target="_blank"
- rel="noreferrer"
- >
- Upstash Redis
- </a>
- .
+ An open-source link shortener with built-in analytics and free
+ custom domains.
</p>
</div>
<form
@@ -103,6 +96,7 @@ export default function Home() {
))}
</motion.ul>
</main>
+ <Globe />
</HomeLayout>
);
}
diff --git a/pages/placeholder.tsx b/pages/placeholder.tsx
new file mode 100644
index 0000000000..5415104496
--- /dev/null
+++ b/pages/placeholder.tsx
@@ -0,0 +1,18 @@
+import HomeLayout from "@/components/layout/home";
+import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
+import Globe from "@/components/home/about/globe";
+
+export default function Placeholder() {
+ return (
+ <HomeLayout>
+ <MaxWidthWrapper>
+ <div className="mt-36 text-center">
+ <h1 className="font-display font-semibold text-3xl text-gray-700">
+ This is a custom domain from Dub.sh
+ </h1>
+ </div>
+ </MaxWidthWrapper>
+ <Globe />
+ </HomeLayout>
+ );
+}
diff --git a/tsconfig.json b/tsconfig.json
index e503e9f72c..48a716700e 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,15 +1,27 @@
{
"compilerOptions": {
"target": "es5",
- "lib": ["dom", "dom.iterable", "esnext"],
+ "lib": [
+ "dom",
+ "dom.iterable",
+ "esnext"
+ ],
"allowJs": true,
"skipLibCheck": true,
"baseUrl": ".",
"paths": {
- "@/components/*": ["components/*"],
- "@/pages/*": ["pages/*"],
- "@/lib/*": ["lib/*"],
- "@/styles/*": ["styles/*"]
+ "@/components/*": [
+ "components/*"
+ ],
+ "@/pages/*": [
+ "pages/*"
+ ],
+ "@/lib/*": [
+ "lib/*"
+ ],
+ "@/styles/*": [
+ "styles/*"
+ ]
},
"forceConsistentCasingInFileNames": true,
"noEmit": true,
@@ -19,8 +31,15 @@
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
- "incremental": true
+ "incremental": true,
+ "strict": false
},
- "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
- "exclude": ["node_modules"]
+ "include": [
+ "next-env.d.ts",
+ "**/*.ts",
+ "**/*.tsx"
+ ],
+ "exclude": [
+ "node_modules"
+ ]
}
diff --git a/yarn.lock b/yarn.lock
index f613ebeebd..8f948118d6 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -609,7 +609,12 @@
dependencies:
"@types/geojson" "*"
-"@upstash/redis@^1.12.0":
+"@upstash/ratelimit@^0.1.5":
+ "integrity" "sha512-v0zq3Xpq42HQBvXDvm0C4djYvKC5TjHG29uCpbIQcOw0znJNroHewI8y4Yk4tBeEF1rvj2RjDkFihjCp6uTExQ=="
+ "resolved" "https://registry.npmjs.org/@upstash/ratelimit/-/ratelimit-0.1.5.tgz"
+ "version" "0.1.5"
+
+"@upstash/redis@^1.12.0", "@upstash/redis@^1.4.0":
"integrity" "sha512-i6oarviHs7xOi9aLe8N52bFSg8FAC8JeArINLqtlEuLGNTkIhdNIJYEs4Sk/xq0EDmHSXFGPWdp+6R8JL9XoIg=="
"resolved" "https://registry.npmjs.org/@upstash/redis/-/redis-1.12.0.tgz"
"version" "1.12.0"