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.

Move to redis

Kiran K12fbd2906a64
diff --git a/apps/web/app/api/cron/cleanup-expired-public-tokens/route.ts b/apps/web/app/api/cron/cleanup-expired-public-tokens/route.ts
deleted file mode 100644
index a42cb338a3..0000000000
--- a/apps/web/app/api/cron/cleanup-expired-public-tokens/route.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { handleAndReturnErrorResponse } from "@/lib/api/errors";
-import { verifyVercelSignature } from "@/lib/cron/verify-vercel";
-import { prisma } from "@/lib/prisma";
-import { log } from "@dub/utils";
-import { NextResponse } from "next/server";
-
-export const dynamic = "force-dynamic";
-
-// Cron to remove the expired public embed tokens
-// Run every day (0 12 * * *)
-export async function GET(req: Request) {
- try {
- await verifyVercelSignature(req);
-
- await prisma.embedPublicToken.deleteMany({
- where: {
- expires: {
- lt: new Date(),
- },
- },
- });
-
- return NextResponse.json({ status: "OK" });
- } catch (error) {
- await log({
- message: `Referrals public token cleanup failed - ${error.message}`,
- type: "errors",
- });
-
- return handleAndReturnErrorResponse(error);
- }
-}
diff --git a/apps/web/app/api/tokens/embed/route.ts b/apps/web/app/api/tokens/embed/route.ts
index 54b831c98e..71a0ded1a7 100644
--- a/apps/web/app/api/tokens/embed/route.ts
+++ b/apps/web/app/api/tokens/embed/route.ts
@@ -1,7 +1,9 @@
+import { DubApiError } from "@/lib/api/errors";
import { getLinkOrThrow } from "@/lib/api/links/get-link-or-throw";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
-import { createOrRetrieveEmbedToken } from "@/lib/referrals/create-or-retrieve-embed-token";
+import { embedToken } from "@/lib/referrals/embed-token";
+import { ratelimit } from "@/lib/upstash";
import {
createReferralTokenSchema,
referralTokenSchema,
@@ -9,16 +11,35 @@ import {
import { NextResponse } from "next/server";
// POST /api/tokens/embed - create a new embed token for the given link
-export const POST = withWorkspace(async ({ workspace, req }) => {
- const { linkId } = createReferralTokenSchema.parse(
- await parseRequestBody(req),
- );
+export const POST = withWorkspace(
+ async ({ workspace, req }) => {
+ const { linkId } = createReferralTokenSchema.parse(
+ await parseRequestBody(req),
+ );
- await getLinkOrThrow({ linkId, workspaceId: workspace.id });
+ await getLinkOrThrow({ linkId, workspaceId: workspace.id });
- const token = await createOrRetrieveEmbedToken(linkId);
+ // TODO:
+ // Need to reconsider this rate limit.
- return NextResponse.json(referralTokenSchema.parse(token), {
- status: 201,
- });
-});
+ const { success } = await ratelimit(10, "1 h").limit(linkId);
+
+ if (!success) {
+ throw new DubApiError({
+ code: "rate_limit_exceeded",
+ message:
+ "Too many requests. You can only generate 10 tokens per hour per link.",
+ });
+ }
+
+ const response = await embedToken.create(linkId);
+
+ return NextResponse.json(referralTokenSchema.parse(response), {
+ status: 201,
+ });
+ },
+ {
+ requiredPermissions: ["links.write"],
+ requiredAddOn: "conversion",
+ },
+);
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/page-client.tsx
index 8e71326a4d..1810e9c182 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/referrals/page-client.tsx
@@ -30,7 +30,7 @@ export default function ReferralsPageClient() {
useEffect(() => {
createPublicToken();
- }, []);
+ }, [slug]);
if (!flags?.referrals) {
redirect(`/${slug}/settings`);
diff --git a/apps/web/app/app.dub.co/embed/utils.ts b/apps/web/app/app.dub.co/embed/utils.ts
index b555fd02b5..d858f47598 100644
--- a/apps/web/app/app.dub.co/embed/utils.ts
+++ b/apps/web/app/app.dub.co/embed/utils.ts
@@ -1,23 +1,17 @@
import { prisma } from "@/lib/prisma";
+import { embedToken } from "@/lib/referrals/embed-token";
import { notFound } from "next/navigation";
-export const getLinkAndProgram = async (linkToken: string) => {
- const token = await prisma.embedPublicToken.findUnique({
- where: {
- publicToken: linkToken,
- expires: {
- gt: new Date(),
- },
- },
- });
+export const getLinkAndProgram = async (token: string) => {
+ const linkId = await embedToken.get(token);
- if (!token) {
+ if (!linkId) {
notFound();
}
const linkAndProgram = await prisma.link.findUnique({
where: {
- id: token.linkId,
+ id: linkId,
},
include: {
program: true,
diff --git a/apps/web/lib/api/utils.ts b/apps/web/lib/api/utils.ts
index 19e383fdd8..375a57c3d4 100644
--- a/apps/web/lib/api/utils.ts
+++ b/apps/web/lib/api/utils.ts
@@ -88,7 +88,6 @@ const prefixes = [
"sale_",
"pga_",
"dub_embed_",
- "ept_",
] as const;
export const createId = ({
diff --git a/apps/web/lib/auth/embed-token.ts b/apps/web/lib/auth/embed-token.ts
index 8537c07dd8..53ffde7c09 100644
--- a/apps/web/lib/auth/embed-token.ts
+++ b/apps/web/lib/auth/embed-token.ts
@@ -2,10 +2,11 @@ import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { prisma } from "@/lib/prisma";
import { ratelimit } from "@/lib/upstash";
import { getSearchParams } from "@dub/utils";
-import { EmbedPublicToken, Link, Program, Project } from "@prisma/client";
+import { Link, Program, Project } from "@prisma/client";
import { AxiomRequest, withAxiom } from "next-axiom";
import { cookies } from "next/headers";
import { EMBED_PUBLIC_TOKEN_COOKIE_NAME } from "../referrals/constants";
+import { embedToken } from "../referrals/embed-token";
interface WithEmbedTokenHandler {
({
@@ -23,7 +24,7 @@ interface WithEmbedTokenHandler {
workspace: Project;
link: Link;
program: Program;
- linkToken: EmbedPublicToken;
+ linkToken: string;
}): Promise<Response>;
}
@@ -53,27 +54,12 @@ export const withEmbedToken = (handler: WithEmbedTokenHandler) => {
});
}
- const linkToken = await prisma.embedPublicToken.findUnique({
- where: {
- publicToken: tokenFromCookie,
- },
- });
-
- if (!linkToken) {
- cookieStore.delete(EMBED_PUBLIC_TOKEN_COOKIE_NAME);
-
- throw new DubApiError({
- code: "unauthorized",
- message: "Invalid public token.",
- });
- }
-
- if (linkToken.expires < new Date()) {
- cookieStore.delete(EMBED_PUBLIC_TOKEN_COOKIE_NAME);
+ const linkId = await embedToken.get(tokenFromCookie);
+ if (!linkId) {
throw new DubApiError({
code: "unauthorized",
- message: "Public token expired.",
+ message: "Link token not found or expired.",
});
}
@@ -98,7 +84,7 @@ export const withEmbedToken = (handler: WithEmbedTokenHandler) => {
link = await prisma.link.findUniqueOrThrow({
where: {
- id: linkToken.linkId,
+ id: linkId,
},
});
@@ -130,7 +116,7 @@ export const withEmbedToken = (handler: WithEmbedTokenHandler) => {
workspace,
link,
program,
- linkToken,
+ linkToken: tokenFromCookie,
});
} catch (error) {
req.log.error(error);
diff --git a/apps/web/lib/middleware/app.ts b/apps/web/lib/middleware/app.ts
index faae2d3617..6095a4250e 100644
--- a/apps/web/lib/middleware/app.ts
+++ b/apps/web/lib/middleware/app.ts
@@ -1,7 +1,7 @@
import { parse } from "@/lib/middleware/utils";
import { NextRequest, NextResponse } from "next/server";
import { EMBED_PUBLIC_TOKEN_COOKIE_NAME } from "../referrals/constants";
-import { retrieveLinkToken } from "../referrals/retrieve-referral-token";
+import { embedToken } from "../referrals/embed-token";
import NewLinkMiddleware from "./new-link";
import { appRedirect } from "./utils/app-redirect";
import { getDefaultWorkspace } from "./utils/get-default-workspace";
@@ -20,14 +20,14 @@ export default async function AppMiddleware(req: NextRequest) {
const token = req.nextUrl.searchParams.get("token");
if (token) {
- const linkToken = await retrieveLinkToken(token);
+ const linkId = await embedToken.get(token);
- if (linkToken) {
+ if (linkId) {
return NextResponse.rewrite(
new URL(`/app.dub.co${fullPath}`, req.url),
{
headers: {
- "Set-Cookie": `${EMBED_PUBLIC_TOKEN_COOKIE_NAME}=${linkToken.publicToken}; HttpOnly; Secure; SameSite=None; Path=/`,
+ "Set-Cookie": `${EMBED_PUBLIC_TOKEN_COOKIE_NAME}=${token}; HttpOnly; Secure; SameSite=None; Path=/`,
},
},
);
diff --git a/apps/web/lib/referrals/constants.ts b/apps/web/lib/referrals/constants.ts
index 0a22f39907..981029e3f5 100644
--- a/apps/web/lib/referrals/constants.ts
+++ b/apps/web/lib/referrals/constants.ts
@@ -4,6 +4,7 @@ export const REFERRAL_CLICKS_QUOTA_BONUS_MAX = 16000;
export const REFERRAL_REVENUE_SHARE = 0.2;
// Embed public token
+export const EMBED_PUBLIC_TOKEN_PREFIX = "dub_embed_";
export const EMBED_PUBLIC_TOKEN_LENGTH = 36;
-export const EMBED_PUBLIC_TOKEN_EXPIRY = 1000 * 60 * 60 * 2; // 2 hours
+export const EMBED_PUBLIC_TOKEN_EXPIRY = 2 * 60 * 60; // 2 hours
export const EMBED_PUBLIC_TOKEN_COOKIE_NAME = "embed_public_token";
diff --git a/apps/web/lib/referrals/create-or-retrieve-embed-token.ts b/apps/web/lib/referrals/create-or-retrieve-embed-token.ts
deleted file mode 100644
index c0f4e70beb..0000000000
--- a/apps/web/lib/referrals/create-or-retrieve-embed-token.ts
+++ /dev/null
@@ -1,57 +0,0 @@
-import { prisma } from "@/lib/prisma";
-import { waitUntil } from "@vercel/functions";
-import { DubApiError } from "../api/errors";
-import { createId } from "../api/utils";
-import { ratelimit } from "../upstash";
-import {
- EMBED_PUBLIC_TOKEN_EXPIRY,
- EMBED_PUBLIC_TOKEN_LENGTH,
-} from "./constants";
-
-export const createOrRetrieveEmbedToken = async (linkId: string) => {
- const { success } = await ratelimit(10, "1 m").limit(linkId);
-
- if (!success) {
- throw new DubApiError({
- code: "rate_limit_exceeded",
- message: "Too many requests.",
- });
- }
-
- const token = await prisma.embedPublicToken.findFirst({
- where: {
- linkId,
- expires: {
- gt: new Date(),
- },
- },
- });
-
- if (token) {
- return token;
- }
-
- // Remove all expired tokens for this link
- waitUntil(
- prisma.embedPublicToken.deleteMany({
- where: {
- linkId,
- expires: {
- lte: new Date(),
- },
- },
- }),
- );
-
- return await prisma.embedPublicToken.create({
- data: {
- id: createId({ prefix: "ept_" }),
- linkId,
- expires: new Date(Date.now() + EMBED_PUBLIC_TOKEN_EXPIRY),
- publicToken: createId({
- prefix: "dub_embed_",
- length: EMBED_PUBLIC_TOKEN_LENGTH,
- }),
- },
- });
-};
diff --git a/apps/web/lib/referrals/embed-token.ts b/apps/web/lib/referrals/embed-token.ts
new file mode 100644
index 0000000000..c9cec0e2d1
--- /dev/null
+++ b/apps/web/lib/referrals/embed-token.ts
@@ -0,0 +1,32 @@
+import { redis } from "@/lib/upstash";
+import { createId } from "../api/utils";
+import {
+ EMBED_PUBLIC_TOKEN_EXPIRY,
+ EMBED_PUBLIC_TOKEN_LENGTH,
+ EMBED_PUBLIC_TOKEN_PREFIX,
+} from "./constants";
+
+class EmbedToken {
+ async create(linkId: string) {
+ const publicToken = createId({
+ prefix: EMBED_PUBLIC_TOKEN_PREFIX,
+ length: EMBED_PUBLIC_TOKEN_LENGTH,
+ });
+
+ await redis.set(publicToken, linkId, {
+ ex: EMBED_PUBLIC_TOKEN_EXPIRY,
+ nx: true,
+ });
+
+ return {
+ publicToken,
+ expires: new Date(Date.now() + EMBED_PUBLIC_TOKEN_EXPIRY),
+ };
+ }
+
+ async get(token: string) {
+ return await redis.get<string>(token);
+ }
+}
+
+export const embedToken = new EmbedToken();
diff --git a/apps/web/lib/referrals/retrieve-referral-token.ts b/apps/web/lib/referrals/retrieve-referral-token.ts
deleted file mode 100644
index 733f33be76..0000000000
--- a/apps/web/lib/referrals/retrieve-referral-token.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { prismaEdge } from "@/lib/prisma/edge";
-
-export async function retrieveLinkToken(token: string) {
- return await prismaEdge.embedPublicToken.findUnique({
- where: {
- publicToken: token,
- },
- });
-}
diff --git a/apps/web/prisma/schema/link.prisma b/apps/web/prisma/schema/link.prisma
index 2922f2e19d..f451510a0e 100644
--- a/apps/web/prisma/schema/link.prisma
+++ b/apps/web/prisma/schema/link.prisma
@@ -66,7 +66,6 @@ model Link {
dashboard Dashboard?
programEnrollment ProgramEnrollment?
programInvite ProgramInvite?
- embedPublicTokens EmbedPublicToken[]
programId String?
program Program? @relation(fields: [programId], references: [id])
diff --git a/apps/web/prisma/schema/token.prisma b/apps/web/prisma/schema/token.prisma
index 5bb63bc5a9..66e4a8ca96 100644
--- a/apps/web/prisma/schema/token.prisma
+++ b/apps/web/prisma/schema/token.prisma
@@ -65,16 +65,3 @@ model PasswordResetToken {
@@unique([identifier, token])
}
-
-model EmbedPublicToken {
- id String @id @default(cuid())
- linkId String // TODO: Do we wanna make this unique? One token per link at a time?
- publicToken String @unique
- expires DateTime
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
-
- link Link @relation(fields: [linkId], references: [id], onDelete: Cascade)
-
- @@index([linkId])
-}