The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Added /domains and /links cron endpoints
Steven Teyb0b70f271b33
diff --git a/.env.example b/.env.exampleindex 0b76c22ed1..afa326ecb0 100644--- a/.env.example+++ b/.env.example@@ -9,10 +9,12 @@ EMAIL_FROM=# Generate a random secret here: https://generate-secret.vercel.app/32NEXTAUTH_SECRET=+################################################################ Required for adding domains to Vercel using the Domains API-## Here's how you can get your Project & Team ID: https://github.com/vercel/vercel/discussions/4367#discussioncomment-1672222-VERCEL_PROJECT_ID=-VERCEL_TEAM_ID=+###############################################################+## Here's how you can get your Project & Team ID: https://vercel.com/guides/nextjs-multi-tenant-application#6.-add-custom-domains-with-the-vercel-api+PROJECT_ID_VERCEL=+TEAM_ID_VERCEL=## Here's how you can create an auth bearer token: https://vercel.com/guides/how-do-i-use-a-vercel-api-access-token#creating-an-access-tokenAUTH_BEARER_TOKEN=diff --git a/README.md b/README.mdindex 2239825786..ed4211f565 100644--- a/README.md+++ b/README.md@@ -38,7 +38,7 @@ You can easily configure custom domains on Dub – just add an A/CNAME record tYou can deploy your own hosted version of Dub for greater privacy & control. Just click the link below to deploy a ready-to-go version of Dub to Vercel.-[](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fsteven-tey%2Fdub&demo-title=Dub%20-%20Open-Source%20Link%20Shortener&demo-description=An%20open-source%20link%20shortener%20SaaS%20built%20with%20Vercel%20Edge%20Functions%20and%20Upstash.&project-name=Dub&repository-name=dub&demo-url=https%3A%2F%2Fdub.sh&demo-image=https%3A%2F%2Fdub.sh%2Fstatic%2Fthumbnail.png&integration-ids=oac_V3R1GIpkoJorr6fqyiwdhl17&env=EMAIL_SERVER,EMAIL_FROM,NEXTAUTH_SECRET,VERCEL_PROJECT_ID,VERCEL_TEAM_ID,AUTH_BEARER_TOKEN,DATABASE_URL&envDescription=Follow%20the%20instructions%20here%20to%20set%20up%20the%20required%20env%20vars%3A&envLink=https%3A%2F%2Fgithub.com%2Fsteven-tey%2Fdub%2Fblob%2Fmain%2F.env.example)+[](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fsteven-tey%2Fdub&demo-title=Dub%20-%20Open-Source%20Link%20Shortener&demo-description=An%20open-source%20link%20shortener%20SaaS%20built%20with%20Vercel%20Edge%20Functions%20and%20Upstash.&project-name=Dub&repository-name=dub&demo-url=https%3A%2F%2Fdub.sh&demo-image=https%3A%2F%2Fdub.sh%2Fstatic%2Fthumbnail.png&integration-ids=oac_V3R1GIpkoJorr6fqyiwdhl17&env=EMAIL_SERVER,EMAIL_FROM,NEXTAUTH_SECRET,PROJECT_ID_VERCEL,TEAM_ID_VERCEL,AUTH_BEARER_TOKEN,DATABASE_URL&envDescription=Follow%20the%20instructions%20here%20to%20set%20up%20the%20required%20env%20vars%3A&envLink=https%3A%2F%2Fgithub.com%2Fsteven-tey%2Fdub%2Fblob%2Fmain%2F.env.example)## Tech Stackdiff --git a/components/home/demo.tsx b/components/home/demo.tsxindex ec7c882329..22929ee068 100644--- a/components/home/demo.tsx+++ b/components/home/demo.tsx@@ -7,6 +7,7 @@ import { motion } from "framer-motion";import { SimpleLinkProps } from "@/lib/types";import Tooltip, { TooltipContent } from "@/components/shared/tooltip";import { Toaster } from "react-hot-toast";+import { FRAMER_MOTION_LIST_ITEM_VARIANTS } from "@/lib/constants";const Demo = () => {const [saving, setSaving] = useState(false);@@ -20,12 +21,15 @@ const Demo = () => {onSubmit={async (e) => {e.preventDefault();setSaving(true);- fetch(`/api/edge/links?url=${encodeURIComponent(url)}&hostname=dub.sh`, {- method: "POST",- headers: {- "Content-Type": "application/json",- },- }).then(async (response) => {+ fetch(+ `/api/edge/links?url=${encodeURIComponent(url)}&hostname=dub.sh`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ }+ ).then(async (response) => {setSaving(false);if (response.ok) {const json = await response.json();@@ -113,6 +117,21 @@ const Demo = () => {{Array.from({ length: 3 - hashes.length }).map((_, i) => (<PlaceholderCard key={i} />))}+ <motion.li+ variants={FRAMER_MOTION_LIST_ITEM_VARIANTS}+ className="border border-gray-200 bg-white p-3 rounded-md text-gray-500 text-sm"+ >+ Note: Public links will be automatically-deleted after 7 days.{" "}+ <a+ href="https://app.dub.sh/register"+ target="_blank"+ rel="noreferrer"+ className="text-gray-700 hover:text-black font-medium underline transition-all"+ >+ Create a free account+ </a>{" "}+ to keep your links forever.+ </motion.li></motion.ul></div>);diff --git a/components/home/placeholder-card.tsx b/components/home/placeholder-card.tsxindex a4573003cb..c4310ade0b 100644--- a/components/home/placeholder-card.tsx+++ b/components/home/placeholder-card.tsx@@ -5,7 +5,7 @@ export default function PlaceholderCard() {return (<motion.livariants={FRAMER_MOTION_LIST_ITEM_VARIANTS}- className="flex items-center border border-gray-200 hover:border-black bg-white p-3 max-w-md rounded-md transition-all"+ className="flex items-center border border-gray-200 bg-white p-3 rounded-md"><div className="w-10 h-10 rounded-full mr-2 bg-gray-200" /><div>diff --git a/lib/cron.ts b/lib/cron.tsnew file mode 100644index 0000000000..5ddcac81b5--- /dev/null+++ b/lib/cron.ts@@ -0,0 +1,72 @@+import prisma from "@/lib/prisma";+import { redis, deleteProject } from "@/lib/upstash";+import { removeDomain } from "./domains";++export const handleDomainUpdates = async (+ domain: string,+ createdAt: Date,+ verified: boolean,+ changed: boolean+) => {+ if (changed) {+ await log(`Domain *${domain}* changed status to *${verified}*`);+ }++ if (verified) return;++ const invalidDays = Math.floor(+ (new Date().getTime() - new Date(createdAt).getTime()) / (1000 * 3600 * 24)+ );++ if (invalidDays > 7) {+ await log(`Domain *${domain}* is invalid for ${invalidDays} days`);+ }++ if (invalidDays > 30) {+ const hasLinks = await redis.exists(`${domain}:links`);+ if (hasLinks === 0) {+ // only delete if there are no resources recorded (links, stats, etc.)+ return await Promise.all([+ prisma.project.delete({+ where: {+ domain,+ },+ }),+ removeDomain(domain),+ deleteProject(domain),+ log(`Domain *${domain}* has been invalid for > 30 days, deleting.`),+ ]);+ } else {+ return await log(+ `Domain *${domain}* has been invalid for > 30 days but has links, not deleting.`+ );+ }+ }+ return;+};++export const log = async (message: string) => {+ /* Log a message to the console */+ if (!process.env.DUB_SLACK_HOOK) return;+ try {+ return await fetch(process.env.DUB_SLACK_HOOK, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ blocks: [+ {+ type: "section",+ text: {+ type: "mrkdwn",+ text: message,+ },+ },+ ],+ }),+ });+ } catch (e) {+ console.log(`Failed to log to Vercel Slack. Error: ${e}`);+ }+};diff --git a/lib/domains.ts b/lib/domains.tsindex 2d34bb9d2e..636f31fe73 100644--- a/lib/domains.ts+++ b/lib/domains.ts@@ -5,7 +5,7 @@ interface CustomResponse extends Response {export const addDomain = async (domain: string): Promise<CustomResponse> => {return await fetch(- `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains?teamId=${process.env.VERCEL_TEAM_ID}`,+ `https://api.vercel.com/v9/projects/${process.env.PROJECT_ID_VERCEL}/domains?teamId=${process.env.TEAM_ID_VERCEL}`,{body: `{\n "name": "${domain}"\n}`,headers: {@@ -19,7 +19,7 @@ export const addDomain = async (domain: string): Promise<CustomResponse> => {export const removeDomain = async (domain: string) => {return await fetch(- `https://api.vercel.com/v6/domains/${domain}?teamId=${process.env.VERCEL_TEAM_ID}`,+ `https://api.vercel.com/v6/domains/${domain}?teamId=${process.env.TEAM_ID_VERCEL}`,{headers: {Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,@@ -31,7 +31,7 @@ export const removeDomain = async (domain: string) => {export const getDomainResponse = async (domain: string) => {return await fetch(- `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains/${domain}?teamId=${process.env.VERCEL_TEAM_ID}`,+ `https://api.vercel.com/v9/projects/${process.env.PROJECT_ID_VERCEL}/domains/${domain}?teamId=${process.env.TEAM_ID_VERCEL}`,{method: "GET",headers: {@@ -46,7 +46,7 @@ export const getDomainResponse = async (domain: string) => {export const getConfigResponse = async (domain: string) => {return await fetch(- `https://api.vercel.com/v6/domains/${domain}/config?teamId=${process.env.VERCEL_TEAM_ID}`,+ `https://api.vercel.com/v6/domains/${domain}/config?teamId=${process.env.TEAM_ID_VERCEL}`,{method: "GET",headers: {@@ -59,7 +59,7 @@ export const getConfigResponse = async (domain: string) => {export const verifyDomain = async (domain: string) => {return await fetch(- `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains/${domain}/verify?teamId=${process.env.VERCEL_TEAM_ID}`,+ `https://api.vercel.com/v9/projects/${process.env.PROJECT_ID_VERCEL}/domains/${domain}/verify?teamId=${process.env.TEAM_ID_VERCEL}`,{method: "POST",headers: {diff --git a/pages/api/cron/domains.ts b/pages/api/cron/domains.tsindex 55b1786da1..9699f8a73c 100644--- a/pages/api/cron/domains.ts+++ b/pages/api/cron/domains.ts@@ -6,11 +6,16 @@ import {getDomainResponse,verifyDomain,} from "@/lib/domains";+import { handleDomainUpdates } from "@/lib/cron";-export default async function handler(- _req: NextApiRequest,- res: NextApiResponse-) {+/**+ * Cron to check if domains are verified.+ * Runs every 3 hours+ * TODO: If a domain is invalid for more than 7 days, we send an email to the project owner.+ * If a domain is invalid for more than 30 days, we delete it and the associating project from the database.+ **/++async function handler(_req: NextApiRequest, res: NextApiResponse) {try {const projects = await prisma.project.findMany({select: {@@ -21,45 +26,64 @@ export default async function handler(orderBy: {domainLastChecked: "desc",},- where: {- domainLastChecked: {- gte: new Date(new Date().getTime() - 1000 * 60 * 60 * 6), // 7 days ago- },- },- take: 500,+ take: 100,});- const statusChanges = await Promise.all(++ const results = await Promise.all(projects.map(async (project) => {const { domain, domainVerified, createdAt } = project;const [domainJson, configJson] = await Promise.all([getDomainResponse(domain),getConfigResponse(domain),]);+let newDomainVerified;- if (!domainJson.verified) {++ if (domainJson?.error?.code === "not_found") {+ newDomainVerified = false;+ } else if (!domainJson.verified) {const verificationJson = await verifyDomain(domain);if (verificationJson && verificationJson.verified) {+ newDomainVerified = true;+ } else {newDomainVerified = false;}- }-- if (!configJson.misconfigured) {- newDomainVerified = false;- } else {+ } else if (!configJson.misconfigured) {newDomainVerified = true;+ } else {+ newDomainVerified = false;}+ const prismaResponse = await prisma.project.update({+ where: {+ domain,+ },+ data: {+ domainVerified: newDomainVerified,+ domainLastChecked: new Date(),+ },+ });++ const changed = newDomainVerified !== domainVerified;++ const updates = await handleDomainUpdates(+ domain,+ createdAt,+ newDomainVerified,+ changed+ );+return {domain,- status: newDomainVerified,- changed: newDomainVerified !== domainVerified,- invalidOver30Days:- new Date().getTime() - new Date(createdAt).getTime() >- 1000 * 60 * 60 * 24 * 30 && newDomainVerified === false,+ previousStatus: domainVerified,+ currentStatus: newDomainVerified,+ changed,+ updates,+ prismaResponse,};}));- res.status(200).json(statusChanges);+ res.status(200).json(results);} catch (error) {res.status(500).json({ error: error.message });}@@ -69,12 +93,12 @@ export default async function handler(* verifySignature will try to load `QSTASH_CURRENT_SIGNING_KEY` and `QSTASH_NEXT_SIGNING_KEY` from the environment.* To test out the endpoint manually (wihtout using QStash), you can do `export default handler` instead and- * hit this endpoint via http://localhost:3000/api/cron+ * hit this endpoint via http://localhost:3000/api/cron/domains*/-// export default verifySignature(handler);+export default verifySignature(handler);-// export const config = {-// api: {-// bodyParser: false,-// },-// };+export const config = {+ api: {+ bodyParser: false,+ },+};diff --git a/pages/api/cron/links.ts b/pages/api/cron/links.tsnew file mode 100644index 0000000000..344c112737--- /dev/null+++ b/pages/api/cron/links.ts@@ -0,0 +1,48 @@+import type { NextApiRequest, NextApiResponse } from "next";+import { verifySignature } from "@upstash/qstash/nextjs";+import { redis } from "@/lib/upstash";+import { log } from "@/lib/cron";++/**+ * Cron to delete generic links (links created on dub.sh) that are older than 30 days.+ * Runs once every day.+ **/++async function handler(_req: NextApiRequest, res: NextApiResponse) {+ try {+ const aWeekAgo = Date.now() - 1000 * 60 * 60 * 24 * 7;+ const links = await redis.zrange<string[]>(+ "dub.sh:links:timestamps:generic",+ 0,+ aWeekAgo,+ { byScore: true }+ );+ const pipeline = redis.pipeline();+ for (const link of links) {+ pipeline.zrem("dub.sh:links:timestamps:generic", link);+ pipeline.hdel("dub.sh:links", link);+ pipeline.del(`dub.sh:clicks:${link}`);+ }+ const [results, _] = await Promise.all([+ pipeline.exec(),+ log(`Successfully deleted *${links.length}* generic links.`),+ ]);+ res.status(200).json(results);+ } catch (error) {+ res.status(500).json({ error: error.message });+ }+}++/**+ * verifySignature will try to load `QSTASH_CURRENT_SIGNING_KEY` and `QSTASH_NEXT_SIGNING_KEY` from the environment.++ * To test out the endpoint manually (wihtout using QStash), you can do `export default handler` instead and+ * hit this endpoint via http://localhost:3000/api/cron/links+ */+export default verifySignature(handler);++export const config = {+ api: {+ bodyParser: false,+ },+};