The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
update cron setup
Steven Tey2fbc0bc59b1d
diff --git a/apps/web/app/api/cron/domains/transfer/route.ts b/apps/web/app/api/cron/domains/transfer/route.tsindex 0b785d38b8..e55fceb09c 100644--- a/apps/web/app/api/cron/domains/transfer/route.ts+++ b/apps/web/app/api/cron/domains/transfer/route.ts@@ -1,4 +1,6 @@-import { qstash, receiver } from "@/lib/cron";+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { qstash } from "@/lib/cron";+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";import { prisma } from "@/lib/prisma";import { recordLink } from "@/lib/tinybird";import z from "@/lib/zod";@@ -14,45 +16,36 @@ const schema = z.object({});export async function POST(req: Request) {- const body = await req.json();-- if (process.env.VERCEL === "1") {- const isValid = await receiver.verify({- signature: req.headers.get("Upstash-Signature") || "",- body: JSON.stringify(body),- });-- if (!isValid) {- return new Response("Unauthorized", { status: 401 });- }- }+ try {+ const body = await req.json();- const { currentWorkspaceId, newWorkspaceId, domain, linksCount } =- schema.parse(body);+ await verifyQstashSignature(req, body);- const links = await prisma.link.findMany({- where: { domain, projectId: currentWorkspaceId },- take: 100,- });+ const { currentWorkspaceId, newWorkspaceId, domain, linksCount } =+ schema.parse(body);- // No remaining links to transfer- if (!links || links.length === 0) {- domainTransferredEmail({- domain,- currentWorkspaceId,- newWorkspaceId,- linksCount,+ const links = await prisma.link.findMany({+ where: { domain, projectId: currentWorkspaceId },+ take: 100,});- return NextResponse.json({- response: "success",- });- }+ // No remaining links to transfer+ if (!links || links.length === 0) {+ domainTransferredEmail({+ domain,+ currentWorkspaceId,+ newWorkspaceId,+ linksCount,+ });- // Transfer links to the new workspace- const linkIds = links.map((link) => link.id);+ return NextResponse.json({+ response: "success",+ });+ }++ // Transfer links to the new workspace+ const linkIds = links.map((link) => link.id);- try {await Promise.all([prisma.link.updateMany({where: { domain, projectId: currentWorkspaceId, id: { in: linkIds } },@@ -108,10 +101,10 @@ export async function POST(req: Request) {});} catch (error) {await log({- message: `Domain transfer cron for the workspace ${newWorkspaceId} failed. Error: ${error.message}`,- type: "errors",+ message: `Error transferring domain: ${error.message}`,+ type: "cron",});- return NextResponse.json({ error: error.message });+ return handleAndReturnErrorResponse(error);}}diff --git a/apps/web/app/api/cron/domains/verify/route.ts b/apps/web/app/api/cron/domains/verify/route.tsindex 6c557e3e0d..9e1696a8be 100644--- a/apps/web/app/api/cron/domains/verify/route.ts+++ b/apps/web/app/api/cron/domains/verify/route.ts@@ -3,7 +3,8 @@ import {getDomainResponse,verifyDomain,} from "@/lib/api/domains";-import { verifySignature } from "@/lib/cron";+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";@@ -15,15 +16,12 @@ import { handleDomainUpdates } from "./utils";* If a domain is invalid for more than 28 days, we send a second and final reminder email to the workspace owner.* If a domain is invalid for more than 30 days, we delete it from the database.**/-// Runs every 3 hours (0 */3 * * *)+// Runs every hour (0 * * * *)export async function GET(req: Request) {- const validSignature = await verifySignature(req);- if (!validSignature) {- return new Response("Unauthorized", { status: 401 });- }-try {+ await verifyVercelSignature(req);+const domains = await prisma.domain.findMany({where: {slug: {@@ -123,6 +121,6 @@ export async function GET(req: Request) {message: "Domains cron failed. Error: " + error.message,type: "errors",});- return NextResponse.json({ error: error.message });+ return handleAndReturnErrorResponse(error);}}diff --git a/apps/web/app/api/cron/domains/verify/utils.ts b/apps/web/app/api/cron/domains/verify/utils.tsindex 6d8b62e91e..b4881acd95 100644--- a/apps/web/app/api/cron/domains/verify/utils.ts+++ b/apps/web/app/api/cron/domains/verify/utils.ts@@ -1,5 +1,5 @@import { deleteDomainAndLinks } from "@/lib/api/domains";-import { limiter } from "@/lib/cron";+import { limiter } from "@/lib/cron/limiter";import { prisma } from "@/lib/prisma";import { log } from "@dub/utils";import { sendEmail } from "emails";diff --git a/apps/web/app/api/cron/import/bitly/route.ts b/apps/web/app/api/cron/import/bitly/route.tsindex 9746230e73..9e05360bae 100644--- a/apps/web/app/api/cron/import/bitly/route.ts+++ b/apps/web/app/api/cron/import/bitly/route.ts@@ -1,4 +1,5 @@-import { receiver } from "@/lib/cron";+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";import { prisma } from "@/lib/prisma";import { redis } from "@/lib/upstash";import { randomBadgeColor } from "@/ui/links/tag-badge";@@ -7,90 +8,89 @@ import { NextResponse } from "next/server";import { importLinksFromBitly } from "./utils";export async function POST(req: Request) {- const body = await req.json();- if (process.env.VERCEL === "1") {- const isValid = await receiver.verify({- signature: req.headers.get("Upstash-Signature") || "",- body: JSON.stringify(body),- });- if (!isValid) {- return new Response("Unauthorized", { status: 401 });- }- }-try {+ const body = await req.json();+ await verifyQstashSignature(req, body);const { workspaceId, bitlyGroup, importTags } = body;- const bitlyApiKey = await redis.get(`import:bitly:${workspaceId}`);- let tagsToId: Record<string, string> | null = null;- if (importTags === true) {- const tagsImported = await redis.get(`import:bitly:${workspaceId}:tags`);+ try {+ const bitlyApiKey = await redis.get(`import:bitly:${workspaceId}`);- if (!tagsImported) {- const tags = (await fetch(- `https://api-ssl.bitly.com/v4/groups/${bitlyGroup}/tags`,- {- headers: {- "Content-Type": "application/json",- Authorization: `Bearer ${bitlyApiKey}`,+ let tagsToId: Record<string, string> | null = null;+ if (importTags === true) {+ const tagsImported = await redis.get(+ `import:bitly:${workspaceId}:tags`,+ );++ if (!tagsImported) {+ const tags = (await fetch(+ `https://api-ssl.bitly.com/v4/groups/${bitlyGroup}/tags`,+ {+ headers: {+ "Content-Type": "application/json",+ Authorization: `Bearer ${bitlyApiKey}`,+ },},- },- )- .then((r) => r.json())- .then((r) => r.tags)) as string[];+ )+ .then((r) => r.json())+ .then((r) => r.tags)) as string[];- await prisma.tag.createMany({- data: tags.map((tag) => ({- name: tag,- color: randomBadgeColor(),- projectId: workspaceId,- })),- skipDuplicates: true,- });- await redis.set(`import:bitly:${workspaceId}:tags`, "true");- }+ await prisma.tag.createMany({+ data: tags.map((tag) => ({+ name: tag,+ color: randomBadgeColor(),+ projectId: workspaceId,+ })),+ skipDuplicates: true,+ });+ await redis.set(`import:bitly:${workspaceId}:tags`, "true");+ }- tagsToId = await prisma.tag- .findMany({- where: {- projectId: workspaceId,- },- select: {- id: true,- name: true,- },- })- .then((tags) =>- tags.reduce((acc, tag) => {- acc[tag.name] = tag.id;- return acc;- }, {}),- );+ tagsToId = await prisma.tag+ .findMany({+ where: {+ projectId: workspaceId,+ },+ select: {+ id: true,+ name: true,+ },+ })+ .then((tags) =>+ tags.reduce((acc, tag) => {+ acc[tag.name] = tag.id;+ return acc;+ }, {}),+ );+ }+ await importLinksFromBitly({+ ...body,+ tagsToId,+ bitlyApiKey,+ });+ return NextResponse.json({+ response: "success",+ });+ } catch (error) {+ const workspace = await prisma.project.findUnique({+ where: {+ id: workspaceId,+ },+ select: {+ slug: true,+ },+ });+ throw new DubApiError({+ code: "bad_request",+ message: `Workspace: ${workspace?.slug || workspaceId}$. Error: ${error.message}`,+ });}- await importLinksFromBitly({- ...body,- tagsToId,- bitlyApiKey,- });- return NextResponse.json({- response: "success",- });} catch (error) {- const workspace = await prisma.project.findUnique({- where: {- id: body.workspaceId,- },- select: {- slug: true,- },- });-await log({- message: `Import Bitly cron for workspace ${- workspace?.slug || body.workspaceId- } failed. Error: ${error.message}`,- type: "errors",+ message: `Error importing Bitly links: ${error.message}`,+ type: "cron",});- return NextResponse.json({ error: error.message });++ return handleAndReturnErrorResponse(error);}}diff --git a/apps/web/app/api/cron/import/csv/route.ts b/apps/web/app/api/cron/import/csv/route.tsindex a34b2067c9..e7121d76a9 100644--- a/apps/web/app/api/cron/import/csv/route.ts+++ b/apps/web/app/api/cron/import/csv/route.ts@@ -1,48 +1,46 @@-import { receiver } from "@/lib/cron";+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";import { prisma } from "@/lib/prisma";import { log } from "@dub/utils";import { NextResponse } from "next/server";import { importLinksFromCSV } from "./utils";export async function POST(req: Request) {- const body = await req.json();- if (process.env.VERCEL === "1") {- const isValid = await receiver.verify({- signature: req.headers.get("Upstash-Signature") || "",- body: JSON.stringify(body),- });- if (!isValid) {- return new Response("Unauthorized", { status: 401 });- }- }-try {+ const body = await req.json();+ await verifyQstashSignature(req, body);const { workspaceId, userId, domain, count } = body;- await importLinksFromCSV({- workspaceId,- userId,- domain,- count,- });- return NextResponse.json({- response: "success",- });- } catch (error) {- const workspace = await prisma.project.findUnique({- where: {- id: body.workspaceId,- },- select: {- slug: true,- },- });+ try {+ await importLinksFromCSV({+ workspaceId,+ userId,+ domain,+ count,+ });+ return NextResponse.json({+ response: "success",+ });+ } catch (error) {+ const workspace = await prisma.project.findUnique({+ where: {+ id: workspaceId,+ },+ select: {+ slug: true,+ },+ });+ throw new DubApiError({+ code: "bad_request",+ message: `Workspace: ${workspace?.slug || workspaceId}$. Error: ${error.message}`,+ });+ }+ } catch (error) {await log({- message: `Import CSV cron for workspace ${- workspace?.slug || body.workspaceId- } failed. Error: ${error.message}`,- type: "errors",+ message: `Error importing CSV links: ${error.message}`,+ type: "cron",});- return NextResponse.json({ error: error.message });++ return handleAndReturnErrorResponse(error);}}diff --git a/apps/web/app/api/cron/import/rebrandly/route.ts b/apps/web/app/api/cron/import/rebrandly/route.tsindex 49dbf58988..199cdd763e 100644--- a/apps/web/app/api/cron/import/rebrandly/route.ts+++ b/apps/web/app/api/cron/import/rebrandly/route.ts@@ -1,4 +1,5 @@-import { receiver } from "@/lib/cron";+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";import { prisma } from "@/lib/prisma";import { redis } from "@/lib/upstash";import { log } from "@dub/utils";@@ -6,83 +7,83 @@ import { NextResponse } from "next/server";import { importLinksFromRebrandly, importTagsFromRebrandly } from "./utils";export async function POST(req: Request) {- const body = await req.json();- if (process.env.VERCEL === "1") {- const isValid = await receiver.verify({- signature: req.headers.get("Upstash-Signature") || "",- body: JSON.stringify(body),- });- if (!isValid) {- return new Response("Unauthorized", { status: 401 });- }- }-try {+ const body = await req.json();+ await verifyQstashSignature(req, body);const { workspaceId, importTags } = body;- const rebrandlyApiKey = await redis.get<string>(- `import:rebrandly:${workspaceId}`,- );- if (!rebrandlyApiKey) {- throw new Error("No Rebrandly API key found");- }-- let tagsToId: Record<string, string> | null = null;- if (importTags === true) {- const tagsImported = await redis.get(- `import:rebrandly:${workspaceId}:tags`,+ try {+ const rebrandlyApiKey = await redis.get<string>(+ `import:rebrandly:${workspaceId}`,);- if (!tagsImported) {- await importTagsFromRebrandly({- workspaceId,- rebrandlyApiKey,+ if (!rebrandlyApiKey) {+ throw new DubApiError({+ code: "bad_request",+ message: "Rebrandly API key not found",});-- await redis.set(`import:rebrandly:${workspaceId}:tags`, "true");}- tagsToId = await prisma.tag- .findMany({- where: {- projectId: workspaceId,- },- select: {- id: true,- name: true,- },- })- .then((tags) =>- tags.reduce((acc, tag) => {- acc[tag.name] = tag.id;- return acc;- }, {}),+ let tagsToId: Record<string, string> | null = null;+ if (importTags === true) {+ const tagsImported = await redis.get(+ `import:rebrandly:${workspaceId}:tags`,);++ if (!tagsImported) {+ await importTagsFromRebrandly({+ workspaceId,+ rebrandlyApiKey,+ });++ await redis.set(`import:rebrandly:${workspaceId}:tags`, "true");+ }++ tagsToId = await prisma.tag+ .findMany({+ where: {+ projectId: workspaceId,+ },+ select: {+ id: true,+ name: true,+ },+ })+ .then((tags) =>+ tags.reduce((acc, tag) => {+ acc[tag.name] = tag.id;+ return acc;+ }, {}),+ );+ }+ await importLinksFromRebrandly({+ ...body,+ tagsToId,+ rebrandlyApiKey,+ });+ return NextResponse.json({+ response: "success",+ });+ } catch (error) {+ const workspace = await prisma.project.findUnique({+ where: {+ id: workspaceId,+ },+ select: {+ slug: true,+ },+ });+ throw new DubApiError({+ code: "bad_request",+ message: `Workspace: ${workspace?.slug || workspaceId}$. Error: ${error.message}`,+ });}- await importLinksFromRebrandly({- ...body,- tagsToId,- rebrandlyApiKey,- });- return NextResponse.json({- response: "success",- });} catch (error) {- const workspace = await prisma.project.findUnique({- where: {- id: body.workspaceId,- },- select: {- slug: true,- },- });-await log({- message: `Import Rebrandly cron for workspace ${- workspace?.slug || body.workspaceId- } failed. Error: ${error.message}`,- type: "errors",+ message: `Error importing Rebrandly links: ${error.message}`,+ type: "cron",});- return NextResponse.json({ error: error.message });++ return handleAndReturnErrorResponse(error);}}diff --git a/apps/web/app/api/cron/import/short/route.ts b/apps/web/app/api/cron/import/short/route.tsindex bb203332c6..9ce211b2a8 100644--- a/apps/web/app/api/cron/import/short/route.ts+++ b/apps/web/app/api/cron/import/short/route.ts@@ -1,4 +1,5 @@-import { receiver } from "@/lib/cron";+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";import { prisma } from "@/lib/prisma";import { redis } from "@/lib/upstash";import { log } from "@dub/utils";@@ -6,18 +7,9 @@ import { NextResponse } from "next/server";import { importLinksFromShort } from "./utils";export async function POST(req: Request) {- const body = await req.json();- if (process.env.VERCEL === "1") {- const isValid = await receiver.verify({- signature: req.headers.get("Upstash-Signature") || "",- body: JSON.stringify(body),- });- if (!isValid) {- return new Response("Unauthorized", { status: 401 });- }- }-try {+ const body = await req.json();+ await verifyQstashSignature(req, body);const {workspaceId,userId,@@ -27,38 +19,44 @@ export async function POST(req: Request) {pageToken,count,} = body;- const shortApiKey = (await redis.get(- `import:short:${workspaceId}`,- )) as string;- await importLinksFromShort({- workspaceId,- userId,- domainId,- domain,- importTags,- pageToken,- count,- shortApiKey,- });- return NextResponse.json({- response: "success",- });- } catch (error) {- const workspace = await prisma.project.findUnique({- where: {- id: body.workspaceId,- },- select: {- slug: true,- },- });+ try {+ const shortApiKey = (await redis.get(+ `import:short:${workspaceId}`,+ )) as string;+ await importLinksFromShort({+ workspaceId,+ userId,+ domainId,+ domain,+ importTags,+ pageToken,+ count,+ shortApiKey,+ });+ return NextResponse.json({+ response: "success",+ });+ } catch (error) {+ const workspace = await prisma.project.findUnique({+ where: {+ id: workspaceId,+ },+ select: {+ slug: true,+ },+ });+ throw new DubApiError({+ code: "bad_request",+ message: `Workspace: ${workspace?.slug || workspaceId}$. Error: ${error.message}`,+ });+ }+ } catch (error) {await log({- message: `Import Short.io cron for workspace ${- workspace?.slug || body.workspaceId- } failed. Error: ${error.message}`,- type: "errors",+ message: `Error importing Short.io links: ${error.message}`,+ type: "cron",});- return NextResponse.json({ error: error.message });++ return handleAndReturnErrorResponse(error);}}diff --git a/apps/web/app/api/cron/links/delete/route.ts b/apps/web/app/api/cron/links/delete/route.tsindex c073c3a9ba..8334effd19 100644--- a/apps/web/app/api/cron/links/delete/route.ts+++ b/apps/web/app/api/cron/links/delete/route.ts@@ -1,36 +1,32 @@+import { handleAndReturnErrorResponse } from "@/lib/api/errors";import { deleteLink } from "@/lib/api/links";-import { receiver } from "@/lib/cron";+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";import { prisma } from "@/lib/prisma";export async function POST(req: Request) {- const body = await req.json();- if (process.env.VERCEL === "1") {- const isValid = await receiver.verify({- signature: req.headers.get("Upstash-Signature") || "",- body: JSON.stringify(body),+ try {+ const body = await req.json();+ await verifyQstashSignature(req, body);+ const { linkId } = body;++ const link = await prisma.link.findUnique({+ where: {+ id: linkId,+ },});- if (!isValid) {- return new Response("Unauthorized", { status: 401 });- }- }- const { linkId } = body;+ if (!link) {+ return new Response("Link not found. Skipping...", { status: 200 });+ }- const link = await prisma.link.findUnique({- where: {- id: linkId,- },- });+ if (link.userId) {+ return new Response("Link claimed. Skipping...", { status: 200 });+ }- if (!link) {- return new Response("Link not found. Skipping...", { status: 200 });- }+ await deleteLink(link.id);- if (link.userId) {- return new Response("Link claimed. Skipping...", { status: 200 });+ return new Response("Link deleted.", { status: 200 });+ } catch (error) {+ return handleAndReturnErrorResponse(error);}-- await deleteLink(link.id);-- return new Response("Link deleted.", { status: 200 });}diff --git a/apps/web/app/api/cron/links/usage/route.ts b/apps/web/app/api/cron/links/usage/route.tsindex 0a16f9b063..9832c4f9fc 100644--- a/apps/web/app/api/cron/links/usage/route.ts+++ b/apps/web/app/api/cron/links/usage/route.ts@@ -1,4 +1,5 @@-import { verifySignature } from "@/lib/cron";+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { verifyVercelSignature } from "@/lib/cron/verify-vercel";import { prisma } from "@/lib/prisma";import { log } from "@dub/utils";import { sendLinksUsageEmail } from "./utils";@@ -7,57 +8,53 @@ import { sendLinksUsageEmail } from "./utils";// Runs once every 15 mins (*/15 * * * *)export async function GET(req: Request) {- const validSignature = await verifySignature(req);-- if (!validSignature) {- return new Response("Unauthorized", { status: 401 });- }+ try {+ await verifyVercelSignature(req);- // get links created in the last 15 minutes- const links = await prisma.link.findMany({- where: {- createdAt: {- gte: new Date(Date.now() - 15 * 60 * 1000),+ // get links created in the last 15 minutes+ const links = await prisma.link.findMany({+ where: {+ createdAt: {+ gte: new Date(Date.now() - 15 * 60 * 1000),+ },},- },- select: {- projectId: true,- },- });+ select: {+ projectId: true,+ },+ });- const workspacesToCheck = links- .map((link) => link.projectId)- .filter(Boolean) as string[];+ const workspacesToCheck = links+ .map((link) => link.projectId)+ .filter(Boolean) as string[];- console.log(- "Links created in the last 15 minutes: ",- links.length,- "Workspaces to check: ",- workspacesToCheck,- );+ console.log(+ "Links created in the last 15 minutes: ",+ links.length,+ "Workspaces to check: ",+ workspacesToCheck,+ );- const workspaces = await prisma.project.findMany({- select: {- id: true,- name: true,- slug: true,- plan: true,- linksUsage: true,- linksLimit: true,- sentEmails: true,- },- where: {- id: {- in: workspacesToCheck,+ const workspaces = await prisma.project.findMany({+ select: {+ id: true,+ name: true,+ slug: true,+ plan: true,+ linksUsage: true,+ linksLimit: true,+ sentEmails: true,},- },- });+ where: {+ id: {+ in: workspacesToCheck,+ },+ },+ });- if (workspaces.length === 0) {- return new Response("OK");- }+ if (workspaces.length === 0) {+ return new Response("OK");+ }- try {await Promise.allSettled(workspaces.map((workspace) => sendLinksUsageEmail(workspace)),);@@ -68,7 +65,6 @@ export async function GET(req: Request) {message: "Links usage cron failed. Error: " + error.message,type: "errors",});-- return new Response(error.message, { status: 500 });+ return handleAndReturnErrorResponse(error);}}diff --git a/apps/web/app/api/cron/links/usage/utils.ts b/apps/web/app/api/cron/links/usage/utils.tsindex 0b0e40719e..8249f8a5e6 100644--- a/apps/web/app/api/cron/links/usage/utils.ts+++ b/apps/web/app/api/cron/links/usage/utils.ts@@ -1,4 +1,4 @@-import { sendLimitEmail } from "@/lib/cron";+import { sendLimitEmail } from "@/lib/cron/send-limit-email";import { prisma } from "@/lib/prisma";import { WorkspaceProps } from "@/lib/types";import { log } from "@dub/utils";diff --git a/apps/web/app/api/cron/notify/route.tsx b/apps/web/app/api/cron/notify/route.tsxdeleted file mode 100644index 324d9be8ab..0000000000--- a/apps/web/app/api/cron/notify/route.tsx+++ /dev/null@@ -1,31 +0,0 @@-import { receiver } from "@/lib/cron";-import { sendEmail } from "emails";-import APIKeyCreated from "emails/api-key-created";--export async function POST(req: Request) {- const body = await req.json();- if (process.env.VERCEL === "1") {- const isValid = await receiver.verify({- signature: req.headers.get("Upstash-Signature") || "",- body: JSON.stringify(body),- });- if (!isValid) {- return new Response("Unauthorized", { status: 401 });- }- }-- const { type, props } = body;-- if (type === "API_KEY_CREATED") {- await sendEmail({- email: props.email,- subject: "New API Key Created",- react: APIKeyCreated({- email: props.email,- apiKeyName: props.apiKeyName,- }),- });- }-- return new Response("Notification sent.", { status: 200 });-}diff --git a/apps/web/app/api/cron/usage/route.ts b/apps/web/app/api/cron/usage/route.tsindex e76ba77162..6f13d58803 100644--- a/apps/web/app/api/cron/usage/route.ts+++ b/apps/web/app/api/cron/usage/route.ts@@ -1,4 +1,6 @@-import { receiver, verifySignature } from "@/lib/cron";+import { handleAndReturnErrorResponse } from "@/lib/api/errors";+import { verifyQstashSignature } from "@/lib/cron/verify-qstash";+import { verifyVercelSignature } from "@/lib/cron/verify-vercel";import { log } from "@dub/utils";import { NextResponse } from "next/server";import { updateUsage } from "./utils";@@ -7,31 +9,21 @@ import { updateUsage } from "./utils";// Runs once every day at noon UTC (0 12 * * *)export async function GET(req: Request) {- const body = await req.json();- if (process.env.VERCEL === "1") {- const validSignature = await verifySignature(req);- if (!validSignature) {- const isValid = await receiver.verify({- signature: req.headers.get("Upstash-Signature") || "",- body: JSON.stringify(body),- });- if (!isValid) {- return new Response("Unauthorized", { status: 401 });- }- }- }-try {- await updateUsage();+ await verifyVercelSignature(req);+ const body = await req.json();+ await verifyQstashSignature(req, body);+ await updateUsage();return NextResponse.json({response: "success",});} catch (error) {await log({- message: "Usage cron failed. Error: " + error.message,- type: "errors",+ message: `Error updating usage: ${error.message}`,+ type: "cron",});- return NextResponse.json({ error: error.message });++ return handleAndReturnErrorResponse(error);}}diff --git a/apps/web/app/api/cron/usage/utils.ts b/apps/web/app/api/cron/usage/utils.tsindex cc63c0d0e8..0f3ba387d1 100644--- a/apps/web/app/api/cron/usage/utils.ts+++ b/apps/web/app/api/cron/usage/utils.ts@@ -1,5 +1,7 @@import { getAnalytics } from "@/lib/analytics/get-analytics";-import { limiter, qstash, sendLimitEmail } from "@/lib/cron";+import { qstash } from "@/lib/cron";+import { limiter } from "@/lib/cron/limiter";+import { sendLimitEmail } from "@/lib/cron/send-limit-email";import { prisma } from "@/lib/prisma";import { WorkspaceProps } from "@/lib/types";import {diff --git a/apps/web/app/api/stripe/webhook/route.ts b/apps/web/app/api/stripe/webhook/route.tsindex 35861e7313..3959f68a33 100644--- a/apps/web/app/api/stripe/webhook/route.ts+++ b/apps/web/app/api/stripe/webhook/route.ts@@ -1,4 +1,4 @@-import { limiter } from "@/lib/cron";+import { limiter } from "@/lib/cron/limiter";import { prisma } from "@/lib/prisma";import { stripe } from "@/lib/stripe";import { redis } from "@/lib/upstash";diff --git a/apps/web/app/api/user/tokens/route.ts b/apps/web/app/api/user/tokens/route.tsindex 5b6c799084..66b458a47b 100644--- a/apps/web/app/api/user/tokens/route.ts+++ b/apps/web/app/api/user/tokens/route.ts@@ -1,7 +1,9 @@import { hashToken, withSession } from "@/lib/auth";-import { qstash } from "@/lib/cron";import { prisma } from "@/lib/prisma";-import { APP_DOMAIN_WITH_NGROK, nanoid } from "@dub/utils";+import { nanoid } from "@dub/utils";+import { waitUntil } from "@vercel/functions";+import { sendEmail } from "emails";+import APIKeyCreated from "emails/api-key-created";import { NextResponse } from "next/server";// GET /api/user/tokens – get all tokens for a specific user@@ -36,26 +38,27 @@ export const POST = withSession(async ({ req, session }) => {const hashedKey = await hashToken(token);// take first 3 and last 4 characters of the keyconst partialKey = `${token.slice(0, 3)}...${token.slice(-4)}`;- await Promise.all([- prisma.token.create({- data: {- name,- hashedKey,- partialKey,- userId: session.user.id,- },- }),- qstash.publishJSON({- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/notify`,- body: {- type: "API_KEY_CREATED",- props: {- email: session.user.email,- apiKeyName: name,- },- },++ await prisma.token.create({+ data: {+ name,+ hashedKey,+ partialKey,+ userId: session.user.id,+ },+ });++ waitUntil(+ sendEmail({+ email: session.user.email,+ subject: "New API Key Created",+ react: APIKeyCreated({+ email: session.user.email,+ apiKeyName: name,+ }),}),- ]);+ );+return NextResponse.json({ token });});diff --git a/apps/web/lib/cron/index.ts b/apps/web/lib/cron/index.tsnew file mode 100644index 0000000000..f83dd8396c--- /dev/null+++ b/apps/web/lib/cron/index.ts@@ -0,0 +1,5 @@+import { Client } from "@upstash/qstash";++export const qstash = new Client({+ token: process.env.QSTASH_TOKEN || "",+});diff --git a/apps/web/lib/cron/limiter.ts b/apps/web/lib/cron/limiter.tsnew file mode 100644index 0000000000..4e921507aa--- /dev/null+++ b/apps/web/lib/cron/limiter.ts@@ -0,0 +1,6 @@+import Bottleneck from "bottleneck";++export const limiter = new Bottleneck({+ maxConcurrent: 1, // maximum concurrent requests+ minTime: 100, // minimum time between requests in ms+});diff --git a/apps/web/lib/cron.ts b/apps/web/lib/cron/send-limit-email.tssimilarity index 58%rename from apps/web/lib/cron.tsrename to apps/web/lib/cron/send-limit-email.tsindex d3e8e3c66c..383aa7fec6 100644--- a/apps/web/lib/cron.ts+++ b/apps/web/lib/cron/send-limit-email.ts@@ -1,42 +1,9 @@import { prisma } from "@/lib/prisma";-import { Client, Receiver } from "@upstash/qstash";-import Bottleneck from "bottleneck";import { sendEmail } from "emails";import ClicksExceeded from "emails/clicks-exceeded";import LinksLimitAlert from "emails/links-limit";-import { WorkspaceProps } from "./types";--export const limiter = new Bottleneck({- maxConcurrent: 1, // maximum concurrent requests- minTime: 100, // minimum time between requests in ms-});--// we're using Upstash's Receiver to verify the request signature-export const receiver = new Receiver({- currentSigningKey: process.env.QSTASH_CURRENT_SIGNING_KEY || "",- nextSigningKey: process.env.QSTASH_NEXT_SIGNING_KEY || "",-});--export const qstash = new Client({- token: process.env.QSTASH_TOKEN || "",-});--export const verifySignature = async (req: Request) => {- const authHeader = req.headers.get("authorization");-- // if we're on Vercel and:- // 1. there's no CRON_SECRET env var- // 2. request doesn't have the correct auth header,- // then return false- if (- process.env.VERCEL === "1" &&- (!process.env.CRON_SECRET ||- authHeader !== `Bearer ${process.env.CRON_SECRET}`)- ) {- return false;- }- return true;-};+import { WorkspaceProps } from "../types";+import { limiter } from "./limiter";export const sendLimitEmail = async ({emails,diff --git a/apps/web/lib/cron/verify-qstash.ts b/apps/web/lib/cron/verify-qstash.tsnew file mode 100644index 0000000000..e59e762623--- /dev/null+++ b/apps/web/lib/cron/verify-qstash.ts@@ -0,0 +1,29 @@+import { Receiver } from "@upstash/qstash";+import { DubApiError } from "../api/errors";++// we're using Upstash's Receiver to verify the request signature+const receiver = new Receiver({+ currentSigningKey: process.env.QSTASH_CURRENT_SIGNING_KEY || "",+ nextSigningKey: process.env.QSTASH_NEXT_SIGNING_KEY || "",+});++export const verifyQstashSignature = async (+ req: Request,+ body?: Record<string, unknown>,+) => {+ body = body || (await req.json());++ const isValid = await receiver.verify({+ signature: req.headers.get("Upstash-Signature") || "",+ body: JSON.stringify(body),+ });++ console.log({ isValid });++ if (!isValid) {+ throw new DubApiError({+ code: "unauthorized",+ message: "Invalid QStash request signature",+ });+ }+};diff --git a/apps/web/lib/cron/verify-vercel.ts b/apps/web/lib/cron/verify-vercel.tsnew file mode 100644index 0000000000..3f3b05c4c3--- /dev/null+++ b/apps/web/lib/cron/verify-vercel.ts@@ -0,0 +1,18 @@+import { DubApiError } from "../api/errors";++export const verifyVercelSignature = async (req: Request) => {+ if (process.env.VERCEL !== "1") {+ return;+ }+ const authHeader = req.headers.get("authorization");++ if (+ !process.env.CRON_SECRET ||+ authHeader !== `Bearer ${process.env.CRON_SECRET}`+ ) {+ throw new DubApiError({+ code: "unauthorized",+ message: "Invalid QStash request signature",+ });+ }+};