The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
fixed random key implementation
Steven Teyd4b6106dbba1
diff --git a/apps/web/app/api/links/random/route.ts b/apps/web/app/api/links/random/route.tsindex 82b820e258..173a53f5f3 100644--- a/apps/web/app/api/links/random/route.ts+++ b/apps/web/app/api/links/random/route.ts@@ -1,13 +1,41 @@-import { getRandomKey } from "@/lib/api/links";-import { withAuth } from "@/lib/auth";+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";+import { getIdentityHash } from "@/lib/edge";+import { getRandomKey } from "@/lib/planetscale";+import { ratelimit } from "@/lib/upstash";import { domainKeySchema } from "@/lib/zod";-import { NextResponse } from "next/server";--// GET /api/links/random – get a random available link key-export const GET = withAuth(async ({ headers, searchParams }) => {- const { domain } = domainKeySchema.pick({ domain: true }).parse(searchParams);- const response = await getRandomKey(domain);- return NextResponse.json(response, {- headers,- });-});+import { getSearchParams } from "@dub/utils";+import { getToken } from "next-auth/jwt";+import { NextRequest, NextResponse } from "next/server";++export const runtime = "edge";++// GET /api/links/random – get a random available link key for a given domain+export const GET = async (req: NextRequest) => {+ try {+ const searchParams = getSearchParams(req.url);+ const { domain } = domainKeySchema+ .pick({ domain: true })+ .parse(searchParams);++ // 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(`metatags:${identity_hash}`);+ if (!success) {+ throw new DubApiError({+ code: "rate_limit_exceeded",+ message: "Don't DDoS me pls 🥺",+ });+ }+ }++ const response = await getRandomKey(domain);+ return NextResponse.json(response);+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }+};diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.tsindex 867d84adfe..27f5cd7cf6 100644--- a/apps/web/lib/api/links.ts+++ b/apps/web/lib/api/links.ts@@ -19,12 +19,11 @@ import {getUrlFromString,isDubDomain,linkConstructor,- nanoid,truncate,validKeyRegex,} from "@dub/utils";import cloudinary from "cloudinary";-import { checkIfKeyExists } from "../planetscale";+import { checkIfKeyExists, getRandomKey } from "../planetscale";import { recordLink } from "../tinybird";import {LinkProps,@@ -247,24 +246,6 @@ export async function keyChecks({};}-export async function getRandomKey(- domain: string,- prefix?: string,-): Promise<string> {- /* recursively get random key till it gets one that's available */- let key = nanoid();- if (prefix) {- key = `${prefix.replace(/^\/|\/$/g, "")}/${key}`;- }- const response = await keyChecks({ domain, key });- if (response.error) {- // by the off chance that key already exists- return getRandomKey(domain, prefix);- } else {- return key;- }-}-export function processKey(key: string) {if (!validKeyRegex.test(key)) {return null;diff --git a/apps/web/lib/auth/index.ts b/apps/web/lib/auth/index.tsindex f0e3824af8..cb87e2c2b0 100644--- a/apps/web/lib/auth/index.ts+++ b/apps/web/lib/auth/index.ts@@ -443,8 +443,7 @@ interface WithSessionHandler {}): Promise<Response>;}-export const withSession =- (handler: WithSessionHandler) =>+export const withSession = (handler: WithSessionHandler) => {async (req: Request, { params }: { params: Record<string, string> }) => {try {let session: Session | undefined;@@ -536,6 +535,7 @@ export const withSession =return handleAndReturnErrorResponse(error);}};+};// Internal use only (for admin portal)interface WithAdminHandler {diff --git a/apps/web/lib/planetscale.ts b/apps/web/lib/planetscale.tsindex c31683d512..6e78125709 100644--- a/apps/web/lib/planetscale.ts+++ b/apps/web/lib/planetscale.ts@@ -1,3 +1,4 @@+import { nanoid } from "@dub/utils";import { connect } from "@planetscale/database";import { DomainProps, ProjectProps } from "./types";@@ -92,3 +93,21 @@ export async function getDomainOrLink({return await getLinkViaEdge(domain, key);}}++export async function getRandomKey(+ domain: string,+ prefix?: string,+): Promise<string> {+ /* recursively get random key till it gets one that's available */+ let key = nanoid();+ if (prefix) {+ key = `${prefix.replace(/^\/|\/$/g, "")}/${key}`;+ }+ const exists = await checkIfKeyExists(domain, key);+ if (exists) {+ // by the off chance that key already exists+ return getRandomKey(domain, prefix);+ } else {+ return key;+ }+}diff --git a/apps/web/lib/zod/index.ts b/apps/web/lib/zod/index.tsindex 32898654ae..6cc3bd5c4b 100644--- a/apps/web/lib/zod/index.ts+++ b/apps/web/lib/zod/index.ts@@ -1,3 +1,4 @@+import { validDomainRegex } from "@dub/utils";import * as z from "zod";import { extendZodWithOpenApi } from "zod-openapi";@@ -6,6 +7,8 @@ extendZodWithOpenApi(z);export default z;export const domainKeySchema = z.object({- domain: z.string().min(1),+ domain: z.string().refine((v) => validDomainRegex.test(v), {+ message: "Invalid domain format",+ }),key: z.string().min(1),});