Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add cron job for domain verification
Marc Seitzb09c1735d24c
diff --git a/.env.example b/.env.exampleindex 3c6ffd3b..33f05830 100644--- a/.env.example+++ b/.env.example@@ -22,4 +22,10 @@ TINYBIRD_TOKEN=# These variables are from Vercel and used for setting up custom domainsPROJECT_ID_VERCEL=TEAM_ID_VERCEL=-AUTH_BEARER_TOKEN=\ No newline at end of file+AUTH_BEARER_TOKEN=++# Upstash QStash – required for queues and background jobs+# Get your QStash Token here: https://upstash.com/docs/qstash/overall/getstarted+QSTASH_TOKEN=+QSTASH_CURRENT_SIGNING_KEY=+QSTASH_NEXT_SIGNING_KEY=\ No newline at end of filediff --git a/app/api/cron.ts b/app/api/cron.tsnew file mode 100644index 00000000..118b3187--- /dev/null+++ b/app/api/cron.ts@@ -0,0 +1,117 @@+import { NextResponse } from "next/server";+import { receiver } from "@/lib/cron";+import { handleDomainUpdates } from "@/lib/cron/domain";+import {+ getConfigResponse,+ getDomainResponse,+ verifyDomain,+} from "@/lib/domains";+import prisma from "@/lib/prisma";+import { log } from "@/lib/utils";++/**+ * Cron to check if domains are verified.+ * If a domain is invalid for more than 14 days, we send a reminder email to the owner.+ * If a domain is invalid for more than 28 days, we send a second and final reminder email to the owner.+ * If a domain is invalid for more than 30 days, we delete it from the database.+ **/+// Runs once per day at 12pm (0 12 * * *)++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 domains = await prisma.domain.findMany({+ where: {+ slug: {+ // exclude domains that belong to us+ notIn: ["papermark.io"],+ },+ },+ select: {+ slug: true,+ verified: true,+ createdAt: true,+ userId: true,+ _count: {+ select: {+ links: true,+ },+ },+ },+ orderBy: {+ lastChecked: "asc",+ },+ take: 100,+ });++ const results = await Promise.allSettled(+ domains.map(async (domain) => {+ const { slug, verified, createdAt, _count } = domain;+ const [domainJson, configJson] = await Promise.all([+ getDomainResponse(slug),+ getConfigResponse(slug),+ ]);++ let newVerified;++ if (domainJson?.error?.code === "not_found") {+ newVerified = false;+ } else if (!domainJson.verified) {+ const verificationJson = await verifyDomain(slug);+ if (verificationJson && verificationJson.verified) {+ newVerified = true;+ } else {+ newVerified = false;+ }+ } else if (!configJson.misconfigured) {+ newVerified = true;+ } else {+ newVerified = false;+ }++ const prismaResponse = await prisma.domain.update({+ where: {+ slug,+ },+ data: {+ verified: newVerified,+ lastChecked: new Date(),+ },+ });++ const changed = newVerified !== verified;++ const updates = await handleDomainUpdates({+ domain: slug,+ createdAt,+ verified: newVerified,+ changed,+ linksCount: _count.links,+ });++ return {+ domain,+ previousStatus: verified,+ currentStatus: newVerified,+ changed,+ updates,+ prismaResponse,+ };+ })+ );+ return NextResponse.json(results);+ } catch (error) {+ await log(`Domains cron failed. Error: " + ${(error as Error).message}`, true);+ return NextResponse.json({ error: (error as Error).message });+ }+}diff --git a/lib/cron/domain.ts b/lib/cron/domain.tsnew file mode 100644index 00000000..164ccb75--- /dev/null+++ b/lib/cron/domain.ts@@ -0,0 +1,111 @@+import { log } from "@/lib/utils";+import { deleteDomain } from "@/lib/domains";+import prisma from "@/lib/prisma";+import { limiter } from "@/lib/cron";+import { sendDeletedDomainEmail } from "@/lib/emails/send-deleted-domain";+import { sendInvalidDomainEmail } from "@/lib/emails/send-invalid-domain";++export const handleDomainUpdates = async ({+ domain,+ createdAt,+ verified,+ changed,+ linksCount,+}: {+ domain: string;+ createdAt: Date;+ verified: boolean;+ changed: boolean;+ linksCount: number;+}) => {+ if (changed) {+ await log(`Domain *${domain}* changed status to *${verified}*`, verified);+ }++ if (verified) return;++ const invalidDays = Math.floor(+ (new Date().getTime() - new Date(createdAt).getTime()) / (1000 * 3600 * 24)+ );++ // do nothing if domain is invalid for less than 14 days+ if (invalidDays < 14) return;++ const user = await prisma.user.findFirst({+ where: {+ domains: {+ some: {+ slug: domain,+ },+ },+ },+ select: {+ id: true,+ name: true,+ email: true,+ },+ });+ if (!user) {+ await log(`Domain *${domain}* is invalid but not associated with any user, skipping.`, true);+ return;+ }++ // if domain is invalid for more than 30 days, check if we can delete it+ if (invalidDays >= 30) {+ // if there are still links associated with the domain,+ // and those links have views associated with them,+ // don't delete the domain (manual inspection required)+ if (linksCount > 0) {+ const linksViews = await prisma.link.findMany({+ where: {+ domainSlug: domain,+ },+ select: {+ _count: {+ select: {+ views: true,+ },+ },+ },+ });++ const totalLinksViews = linksViews.reduce(+ (acc, link) => acc + link._count.views,+ 0+ );++ if (totalLinksViews > 0) {+ return await log(`Domain *${domain}* has been invalid for > 30 days and has links with clicks, skipping.`);+ }+ }+ // else, delete the domain and send email+ return await Promise.allSettled([+ deleteDomain(domain),+ log(`Domain *${domain}* has been invalid for > 30 days and ${+ linksCount > 0 ? "has links but no link clicks" : "has no links"+ }, deleting.`),+ limiter.schedule(() =>+ sendDeletedDomainEmail(user.email!, domain)+ )+ ]);+ }++ // if domain is invalid for more than 28 days, send email+ if (invalidDays >= 28) {+ return await Promise.allSettled([+ log(`Domain *${domain}* is invalid for ${invalidDays} days, email sent.`),+ limiter.schedule(() => sendInvalidDomainEmail(user.email!, domain, invalidDays)),+ ]);+ }++ // if domain is invalid for more than 14 days, send email+ if (invalidDays >= 14) {+ return await Promise.allSettled([+ log(`Domain *${domain}* is invalid for ${invalidDays} days, email sent.`),+ limiter.schedule(() =>+ sendInvalidDomainEmail(user.email!, domain, invalidDays)+ ),+ ]);+ }+ return;+};\ No newline at end of filediff --git a/lib/cron/index.ts b/lib/cron/index.tsnew file mode 100644index 00000000..07015e97--- /dev/null+++ b/lib/cron/index.ts@@ -0,0 +1,19 @@+import Bottleneck from "bottleneck";+import { Receiver } from "@upstash/qstash";+import { Client } from "@upstash/qstash";++// we're using Bottleneck to avoid running into Resend's rate limit of 10 req/s+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 || "",+});diff --git a/package-lock.json b/package-lock.jsonindex 35d42281..40dcb221 100644--- a/package-lock.json+++ b/package-lock.json@@ -32,11 +32,13 @@"@types/node": "^20.7.0","@types/react": "^18.2.23","@types/react-dom": "^18.2.8",+ "@upstash/qstash": "^2.1.8","@vercel/analytics": "^1.0.2","@vercel/blob": "^0.12.5","autoprefixer": "^10.4.16","base-x": "^4.0.0","bcryptjs": "^2.4.3",+ "bottleneck": "^2.19.5","class-variance-authority": "^0.7.0","clsx": "^2.0.0","date-fns": "^2.30.0",@@ -3124,6 +3126,15 @@"url": "https://opencollective.com/typescript-eslint"}},+ "node_modules/@upstash/qstash": {+ "version": "2.1.8",+ "resolved": "https://registry.npmjs.org/@upstash/qstash/-/qstash-2.1.8.tgz",+ "integrity": "sha512-p8PQ6fE1ljhnrHmP5iQiqZAVf3ljFoC4/i8f2usLQ75Emq1cCiDHvW8u/J/U/N0zCLewxxA1g1W5bGJ7+5iKyQ==",+ "dependencies": {+ "crypto-js": "^4.1.1",+ "jose": "^4.14.4"+ }+ },"node_modules/@vercel/analytics": {"version": "1.0.2","resolved": "https://registry.npmjs.org/@vercel/analytics/-/analytics-1.0.2.tgz",@@ -3649,6 +3660,11 @@"resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.4.7.tgz","integrity": "sha512-iD3898SR7sWVRHbiQv+sHUtHnMvC1o3nW5rAcqnq3uOn07DSAppZYUkIGslDz6gXC7HfunPe7YVBgoEJASPcHA=="},+ "node_modules/bottleneck": {+ "version": "2.19.5",+ "resolved": "https://registry.npmjs.org/bottleneck/-/bottleneck-2.19.5.tgz",+ "integrity": "sha512-VHiNCbI1lKdl44tGrhNfU3lup0Tj/ZBMJB5/2ZbNXRCPuRCO7ed2mgcK4r17y+KB2EfuYuRaVlwNbAeaWGSpbw=="+ },"node_modules/bplist-parser": {"version": "0.2.0","resolved": "https://registry.npmjs.org/bplist-parser/-/bplist-parser-0.2.0.tgz",@@ -4085,6 +4101,11 @@"node": ">= 8"}},+ "node_modules/crypto-js": {+ "version": "4.1.1",+ "resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.1.1.tgz",+ "integrity": "sha512-o2JlM7ydqd3Qk9CA0L4NL6mTzU2sdx96a+oOfPu8Mkl/PK51vSyoi8/rQ8NknZtk44vq15lmhAj9CIAGwgeWKw=="+ },"node_modules/css-unit-converter": {"version": "1.1.2","resolved": "https://registry.npmjs.org/css-unit-converter/-/css-unit-converter-1.1.2.tgz",@@ -12827,6 +12848,15 @@"eslint-visitor-keys": "^3.3.0"}},+ "@upstash/qstash": {+ "version": "2.1.8",+ "resolved": "https://registry.npmjs.org/@upstash/qstash/-/qstash-2.1.8.tgz",+ "integrity": "sha512-p8PQ6fE1ljhnrHmP5iQiqZAVf3ljFoC4/i8f2usLQ75Emq1cCiDHvW8u/J/U/N0zCLewxxA1g1W5bGJ7+5iKyQ==",+ "requires": {+ "crypto-js": "^4.1.1",+ "jose": "^4.14.4"+ }+ },"@vercel/analytics": {"version": "1.0.2","resolved": "https://registry.npmjs.org/@vercel/analytics/-/analytics-1.0.2.tgz",@@ -13205,6 +13235,11 @@"resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.4.7.tgz","integrity": "sha512-iD3898SR7sWVRHbiQv+sHUtHnMvC1o3nW5rAcqnq3uOn07DSAppZYUkIGslDz6gXC7HfunPe7YVBgoEJASPcHA=="},+ "bottleneck": {+ "version": "2.19.5",+ "resolved": "https://registry.npmjs.org/bottleneck/-/bottleneck-2.19.5.tgz",+ "integrity": "sha512-VHiNCbI1lKdl44tGrhNfU3lup0Tj/ZBMJB5/2ZbNXRCPuRCO7ed2mgcK4r17y+KB2EfuYuRaVlwNbAeaWGSpbw=="+ },"bplist-parser": {"version": "0.2.0","resolved": "https://registry.npmjs.org/bplist-parser/-/bplist-parser-0.2.0.tgz",diff --git a/package.json b/package.jsonindex c6f47174..4a450443 100644--- a/package.json+++ b/package.json@@ -38,11 +38,13 @@"@types/node": "^20.7.0","@types/react": "^18.2.23","@types/react-dom": "^18.2.8",+ "@upstash/qstash": "^2.1.8","@vercel/analytics": "^1.0.2","@vercel/blob": "^0.12.5","autoprefixer": "^10.4.16","base-x": "^4.0.0","bcryptjs": "^2.4.3",+ "bottleneck": "^2.19.5","class-variance-authority": "^0.7.0","clsx": "^2.0.0","date-fns": "^2.30.0",