The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
started work on domains cron
Steven Tey9ee73b1158bb
diff --git a/components/app/custom-domain/domain-configuration.tsx b/components/app/custom-domain/domain-configuration.tsxindex 05fe409e62..1ff6827e89 100644--- a/components/app/custom-domain/domain-configuration.tsx+++ b/components/app/custom-domain/domain-configuration.tsx@@ -53,6 +53,14 @@ export default function DomainConfiguration({);}+ if (data.status === "Unknown Error") {+ return (+ <div className="border-t border-gray-200 pt-5">+ <p className="mb-5 text-sm">{data.response.domainJson.error.message}</p>+ </div>+ );+ }+return (<div className="border-t border-gray-200 pt-5"><div className="flex justify-start space-x-4">diff --git a/lib/domains.ts b/lib/domains.tsindex f7a1e890b3..4fe5c62b23 100644--- a/lib/domains.ts+++ b/lib/domains.ts@@ -28,3 +28,44 @@ export const removeDomain = async (domain: string) => {}).then((res) => res.json());};++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}`,+ {+ method: "GET",+ headers: {+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,+ "Content-Type": "application/json",+ },+ }+ ).then((res) => {+ return res.json();+ });+};++export const getConfigResponse = async (domain: string) => {+ return await fetch(+ `https://api.vercel.com/v6/domains/${domain}/config?teamId=${process.env.VERCEL_TEAM_ID}`,+ {+ method: "GET",+ headers: {+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,+ "Content-Type": "application/json",+ },+ }+ ).then((res) => res.json());+};++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}`,+ {+ method: "POST",+ headers: {+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,+ "Content-Type": "application/json",+ },+ }+ ).then((res) => res.json());+};diff --git a/lib/types.ts b/lib/types.tsindex f5140d74a2..a28c6618fb 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -27,4 +27,5 @@ export type DomainVerificationStatusProps =| "Valid Configuration"| "Invalid Configuration"| "Pending Verification"- | "Domain Not Found";+ | "Domain Not Found"+ | "Unknown Error";diff --git a/package.json b/package.jsonindex cf4792ae6b..768df413fc 100644--- a/package.json+++ b/package.json@@ -13,6 +13,7 @@"@radix-ui/react-tooltip": "^1.0.0","@stripe/stripe-js": "^1.36.0","@tailwindcss/forms": "^0.5.3",+ "@upstash/qstash": "^0.1.7","@upstash/ratelimit": "^0.1.5","@upstash/redis": "^1.12.0","@visx/axis": "^2.12.2",diff --git a/pages/api/cron/domains.ts b/pages/api/cron/domains.tsnew file mode 100644index 0000000000..c7994b352b--- /dev/null+++ b/pages/api/cron/domains.ts@@ -0,0 +1,64 @@+import type { NextApiRequest, NextApiResponse } from "next";+import { verifySignature } from "@upstash/qstash/nextjs";+import prisma from "@/lib/prisma";+import {+ getConfigResponse,+ getDomainResponse,+ verifyDomain,+} from "@/lib/domains";++async function handler(_req: NextApiRequest, res: NextApiResponse) {+ try {+ const projects = await prisma.project.findMany({+ select: {+ domain: true,+ domainVerified: true,+ createdAt: true,+ },+ orderBy: {+ domainLastChecked: "desc",+ },+ where: {+ domainLastChecked: {+ lte: new Date(new Date().getTime() - 1000 * 60 * 60 * 6), // 7 days ago+ },+ },+ take: 500,+ })+ const statusChanges = 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?.error) {+ newDomainVerified = false+ return {+ domain,+ status: newDomainVerified,+ changed: newDomainVerified !== domainVerified,+ };+ } else if (!domainJson.verified) {+ const verificationJson = await verifyDomain(domain);+ if (!configJson.misconfigured) {++ }))+ } 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+ */+export default verifySignature(handler);++export const config = {+ api: {+ bodyParser: false,+ },+};diff --git a/pages/api/projects/[slug]/domains/[domain]/verify.ts b/pages/api/projects/[slug]/domains/[domain]/verify.tsindex b0a96e4f1b..f49c75f057 100644--- a/pages/api/projects/[slug]/domains/[domain]/verify.ts+++ b/pages/api/projects/[slug]/domains/[domain]/verify.ts@@ -2,6 +2,11 @@ import { withProjectAuth } from "@/lib/auth";import { NextApiRequest, NextApiResponse } from "next";import { DomainVerificationStatusProps } from "@/lib/types";import prisma from "@/lib/prisma";+import {+ getConfigResponse,+ getDomainResponse,+ verifyDomain,+} from "@/lib/domains";export default withProjectAuth(async (req: NextApiRequest, res: NextApiResponse) => {@@ -9,58 +14,32 @@ export default withProjectAuth(const { slug, domain } = req.query as { slug: string; domain: string };let status: DomainVerificationStatusProps = "Valid Configuration";- const [domainResponse, configResponse] = await Promise.all([- fetch(- `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains/${domain}?teamId=${process.env.VERCEL_TEAM_ID}`,- {- method: "GET",- headers: {- Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,- "Content-Type": "application/json",- },- }- ),- fetch(- `https://api.vercel.com/v6/domains/${domain}/config?teamId=${process.env.VERCEL_TEAM_ID}`,- {- method: "GET",- headers: {- Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,- "Content-Type": "application/json",- },- }- ),+ const [domainJson, configJson] = await Promise.all([+ getDomainResponse(domain),+ getConfigResponse(domain),]);- const domainJson = await domainResponse.json();- const configJson = await configResponse.json();- if (domainResponse.status !== 200) {+ if (domainJson?.error?.code === "not_found") {// domain not found on Vercel projectstatus = "Domain Not Found";return res.status(200).json({ status, response: { configJson, domainJson } });+ } else if (domainJson.error) {+ status = "Unknown Error";+ return res+ .status(200)+ .json({ status, response: { configJson, domainJson } });}/*** If domain is not verified, we try to verify now*/- let verificationResponse = null;if (!domainJson.verified) {status = "Pending Verification";- const verificationRes = await fetch(- `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains/${domain}/verify?teamId=${process.env.VERCEL_TEAM_ID}`,- {- method: "POST",- headers: {- Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,- "Content-Type": "application/json",- },- }- );- verificationResponse = await verificationRes.json();+ const verificationJson = await verifyDomain(domain);- if (verificationResponse && verificationResponse.verified) {+ if (verificationJson && verificationJson.verified) {/*** Domain was just verified*/@@ -72,7 +51,7 @@ export default withProjectAuth(response: {configJson,domainJson,- verificationResponse,+ verificationJson,},});}@@ -85,6 +64,7 @@ export default withProjectAuth(},data: {domainVerified: true,+ domainLastChecked: new Date(),},});} else {@@ -95,6 +75,7 @@ export default withProjectAuth(},data: {domainVerified: false,+ domainLastChecked: new Date(),},});}diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 318dc93615..b237110d8c 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -59,18 +59,19 @@ model VerificationToken {}model Project {- id String @id @default(cuid())- name String- slug String @unique- domain String @unique- domainVerified Boolean @default(false)- plan String @default("free")- usageLimit Int @default(1000)- stripeId String? @unique // Stripe customer ID- lastBilled DateTime?- createdAt DateTime @default(now())- updatedAt DateTime @updatedAt- users ProjectUsers[]+ id String @id @default(cuid())+ name String+ slug String @unique+ domain String @unique+ domainVerified Boolean @default(false)+ plan String @default("free")+ usageLimit Int @default(1000)+ stripeId String? @unique // Stripe customer ID+ lastBilled DateTime?+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt+ domainLastChecked DateTime @default(now())+ users ProjectUsers[]}model ProjectUsers {diff --git a/yarn.lock b/yarn.lockindex 17c8b89fb6..14415f6e6d 100644--- a/yarn.lock+++ b/yarn.lock@@ -14,6 +14,11 @@resolved "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz"integrity sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==+"@deno/shim-crypto@~0.3.0":+ version "0.3.1"+ resolved "https://registry.yarnpkg.com/@deno/shim-crypto/-/shim-crypto-0.3.1.tgz#416155b2b6f9ad728f80ebcb422c803efc1023c2"+ integrity sha512-ed4pNnfur6UbASEgF34gVxR9p7Mc3qF+Ygbmjiil8ws5IhNFhPDFy5vE5hQAUA9JmVsSxXPcVLM5Rf8LOZqQ5Q==+"@emotion/is-prop-valid@^0.8.2":version "0.8.8"resolved "https://registry.npmjs.org/@emotion/is-prop-valid/-/is-prop-valid-0.8.8.tgz"@@ -359,7 +364,7 @@dependencies:json-parse-even-better-errors "^2.3.1"-"@npmcli/promise-spawn@*", "@npmcli/promise-spawn@^3.0.0":+"@npmcli/promise-spawn@^3.0.0":version "3.0.0"resolved "https://registry.npmjs.org/@npmcli/promise-spawn/-/promise-spawn-3.0.0.tgz"integrity sha512-s9SgS+p3a9Eohe68cSI3fi+hpcZUmXq5P7w0kMlAsWVtR7XbK3ptkZqKT2cK1zLDObJ3sR+8P59sJE0w/KTL1g==@@ -810,6 +815,13 @@dependencies:"@types/geojson" "*"+"@upstash/qstash@^0.1.7":+ version "0.1.7"+ resolved "https://registry.yarnpkg.com/@upstash/qstash/-/qstash-0.1.7.tgz#637555fa6d13d044eb8ebefc0dad5a54517c21c5"+ integrity sha512-QrQuT+m54cIAC+XPp3sWF89G/1gV63i+jiSQWonoMLC6vmXaEg+YSAvWkFLdFWBm1WPheFFQLuKwlZNtUH51SA==+ dependencies:+ "@deno/shim-crypto" "~0.3.0"+"@upstash/ratelimit@^0.1.5":version "0.1.5"resolved "https://registry.npmjs.org/@upstash/ratelimit/-/ratelimit-0.1.5.tgz"@@ -1675,7 +1687,7 @@ fs-extra@^8.1.0:jsonfile "^4.0.0"universalify "^0.1.0"-fs-minipass@*, fs-minipass@^2.0.0, fs-minipass@^2.1.0:+fs-minipass@^2.0.0, fs-minipass@^2.1.0:version "2.1.0"resolved "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz"integrity sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==@@ -2277,13 +2289,6 @@ mini-svg-data-uri@^1.2.3:resolved "https://registry.npmjs.org/mini-svg-data-uri/-/mini-svg-data-uri-1.4.4.tgz"integrity sha512-r9deDe9p5FJUPZAk3A59wGH7Ii9YrjjWw0jmw/liSbHl2CHiyXj6FcDXDu2K3TjVAXqiJdaw3xxwlZZr9E6nHg==-minimatch@*, minimatch@^5.0.1, minimatch@^5.1.0:- version "5.1.0"- resolved "https://registry.npmjs.org/minimatch/-/minimatch-5.1.0.tgz"- integrity sha512-9TPBGGak4nHfGZsPBohm9AWg6NoT7QTCehS3BIJABslyZbzxfV78QM2Y6+i741OPZIafFAaiiEMh5OyIrJPgtg==- dependencies:- brace-expansion "^2.0.1"-minimatch@^3.1.1:version "3.1.2"resolved "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz"@@ -2291,6 +2296,13 @@ minimatch@^3.1.1:dependencies:brace-expansion "^1.1.7"+minimatch@^5.0.1, minimatch@^5.1.0:+ version "5.1.0"+ resolved "https://registry.npmjs.org/minimatch/-/minimatch-5.1.0.tgz"+ integrity sha512-9TPBGGak4nHfGZsPBohm9AWg6NoT7QTCehS3BIJABslyZbzxfV78QM2Y6+i741OPZIafFAaiiEMh5OyIrJPgtg==+ dependencies:+ brace-expansion "^2.0.1"+minimist@^1.2.6:version "1.2.6"resolved "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz"