Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: add custom domain interfaces and api routes
Marc Seitz2d341758e9e7
diff --git a/components/domains/add-domain-modal.tsx b/components/domains/add-domain-modal.tsxnew file mode 100644index 00000000..ab597bb9--- /dev/null+++ b/components/domains/add-domain-modal.tsx@@ -0,0 +1,92 @@+import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import useDomains from "@/lib/swr/use-domains";+import { useState } from "react";+import { mutate } from "swr";++export function AddDomainModal({+ onAddition,+ children,+}: {+ onAddition: (newDomain: string) => void;+ children: React.ReactNode;+}) {+ const { domains } = useDomains();+ const [domain, setDomain] = useState<string>("");+ const [loading, setLoading] = useState<boolean>(false);+ const [open, setOpen] = useState<boolean>(false);++ const handleSubmit = async (event: any) => {+ event.preventDefault();++ if (domain == "") return;++ setLoading(true);+ const response = await fetch("/api/domains", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ domain: domain,+ }),+ });++ if (!response.ok) {+ throw new Error(`HTTP error! status: ${response.status}`);+ }++ const newDomain = await response.json();++ console.log(newDomain);++ // Update local data with the new link+ onAddition(newDomain);++ setOpen(false);++ setLoading(false);+ };++ return (+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogTrigger>{children}</DialogTrigger>+ <DialogContent className="sm:max-w-[425px]">+ <DialogHeader>+ <DialogTitle>Add Domain</DialogTitle>+ <DialogDescription>+ You can easily add a custom domain.+ </DialogDescription>+ </DialogHeader>+ <form onSubmit={handleSubmit}>+ <div className="grid gap-4 py-4">+ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="domain" className="text-right">+ Domain+ </Label>+ <Input+ id="domain"+ placeholder="yourdomain.com"+ className="col-span-3"+ onChange={(e) => setDomain(e.target.value)}+ />+ </div>+ </div>+ <DialogFooter>+ <Button type="submit">Add domain</Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/components/domains/domain-card.tsx b/components/domains/domain-card.tsxnew file mode 100644index 00000000..ab7d3995--- /dev/null+++ b/components/domains/domain-card.tsx@@ -0,0 +1,101 @@+import { mutate } from "swr";+import { useDomainStatus } from "./use-domain-status";+import DomainConfiguration from "./domain-configuration";++import CheckCircle2 from "../shared/icons/check-cirlce-2";+import AlertCircle from "../shared/icons/alert-circle";+import XCircle from "../shared/icons/x-circle";+import LoadingSpinner from "../ui/loading-spinner";+import ExternalLink from "../shared/icons/external-link";+import { Button } from "../ui/button";+import { useState } from "react";++export default function DomainCard({+ domain,+ onDelete,+}: {+ domain: string;+ onDelete: (deletedDomain: string) => void;+}) {+ const { status, loading } = useDomainStatus({ domain });+ const [deleting, setDeleting] = useState<boolean>(false)++ const handleDelete = async () => {+ console.log("Deleting domain...", domain);++ setDeleting(true)+ const response = await fetch(`/api/domains/${domain}`, {+ method: "DELETE",+ });++ if (!response.ok) {+ throw new Error(`HTTP error! status: ${response.status}`);+ }++ // Update local data by filtering out the deleted domain+ onDelete(domain);+ setDeleting(false);+ };++ return (+ <>+ <div className="flex flex-col space-y-3 rounded-lg border border-gray-700 bg-gray-800 px-5 py-8 sm:px-10">+ <div className="flex flex-col justify-between space-y-4 sm:flex-row sm:space-x-4">+ <div className="flex items-center space-x-2">+ <a+ href={`http://${domain}`}+ target="_blank"+ rel="noreferrer"+ className="flex items-center space-x-2"+ >+ <p className="flex items-center text-xl font-semibold">+ {domain}+ </p>+ <ExternalLink className="h-5 w-5" />+ </a>+ </div>+ <div className="flex space-x-3">+ <Button+ variant="secondary"+ className="bg-gray-700 hover:bg-gray-700/80"+ loading={loading}+ onClick={() => {+ mutate(`/api/domains/${domain}/verify`);+ }}+ >+ Refresh+ </Button>+ <Button+ variant="destructive"+ onClick={handleDelete}+ loading={deleting}+ >+ Delete+ </Button>+ </div>+ </div>+ <div className="flex h-10 flex-col space-y-2 sm:flex-row sm:items-center sm:space-x-5 sm:space-y-0">+ <div className="flex items-center space-x-2">+ {status ? (+ status === "Valid Configuration" ? (+ <CheckCircle2 className="h-6 w-6 text-blue-500" />+ ) : status === "Pending Verification" ? (+ <AlertCircle className="h-6 w-6 text-yellow-500" />+ ) : (+ <XCircle className="h-6 w-6 text-red-500" />+ )+ ) : (+ <LoadingSpinner className="mr-1 h-5 w-5" />+ )}+ <p className="text-sm text-gray-400">+ {status ? status : "Checking Domain Status"}+ </p>+ </div>+ </div>+ {status && status !== "Valid Configuration" && (+ <DomainConfiguration domain={domain} />+ )}+ </div>+ </>+ );+}diff --git a/components/domains/domain-configuration.tsx b/components/domains/domain-configuration.tsxnew file mode 100644index 00000000..4c6cc47d--- /dev/null+++ b/components/domains/domain-configuration.tsx@@ -0,0 +1,150 @@+"use client";++import { useState } from "react";+import { useDomainStatus } from "./use-domain-status";+import { getSubdomain } from "@/lib/domains";+import { cn } from "@/lib/utils";++export const InlineSnippet = ({+ className,+ children,+}: {+ className?: string;+ children: string;+}) => {+ return (+ <span+ className={cn(+ "inline-block rounded-md bg-blue-100 px-1 py-0.5 font-mono text-blue-900 dark:bg-blue-900 dark:text-blue-100",+ className+ )}+ >+ {children}+ </span>+ );+};+export default function DomainConfiguration({ domain }: { domain: string }) {+ const { status, domainJson } = useDomainStatus({ domain });++ if (!status || status === "Valid Configuration" || !domainJson) return null;++ const subdomain = getSubdomain(domainJson.name, domainJson.apexName);++ const [recordType, setRecordType] = useState<"A" | "CNAME">(subdomain ? "CNAME" : "A");++ const txtVerification =+ (status === "Pending Verification" &&+ domainJson.verification.find((x: any) => x.type === "TXT")) ||+ null;++ return (+ <div className="border-t border-stone-200 pb-5 pt-7 dark:border-stone-700">+ {txtVerification ? (+ <>+ <p className="text-sm dark:text-white">+ Please set the following TXT record on{" "}+ <InlineSnippet>{domainJson.apexName}</InlineSnippet> to prove+ ownership of <InlineSnippet>{domainJson.name}</InlineSnippet>:+ </p>+ <div className="my-5 flex items-start justify-start space-x-10 rounded-md bg-stone-50 p-2 dark:bg-stone-800 dark:text-white">+ <div>+ <p className="text-sm font-bold">Type</p>+ <p className="mt-2 font-mono text-sm">{txtVerification.type}</p>+ </div>+ <div>+ <p className="text-sm font-bold">Name</p>+ <p className="mt-2 font-mono text-sm">+ {txtVerification.domain.slice(+ 0,+ txtVerification.domain.length - domainJson.apexName.length - 1+ )}+ </p>+ </div>+ <div>+ <p className="text-sm font-bold">Value</p>+ <p className="mt-2 font-mono text-sm">+ <span className="text-ellipsis">{txtVerification.value}</span>+ </p>+ </div>+ </div>+ <p className="text-sm dark:text-stone-400">+ Warning: if you are using this domain for another site, setting this+ TXT record will transfer domain ownership away from that site and+ break it. Please exercise caution when setting this record.+ </p>+ </>+ ) : status === "Unknown Error" ? (+ <p className="mb-5 text-sm dark:text-white">+ {domainJson.error.message}+ </p>+ ) : (+ <>+ <div className="flex justify-start space-x-4">+ <button+ type="button"+ onClick={() => setRecordType("A")}+ className={`${+ recordType == "A"+ ? "border-black text-black dark:border-white dark:text-white"+ : " text-stone-400 dark:text-stone-600"+ } ease border-b-2 pb-1 text-sm transition-all duration-150`}+ >+ A Record{!subdomain && " (recommended)"}+ </button>+ <button+ type="button"+ onClick={() => setRecordType("CNAME")}+ className={`${+ recordType == "CNAME"+ ? "border-black text-black dark:border-white dark:text-white"+ : " text-stone-400 dark:text-stone-600"+ } ease border-b-2 pb-1 text-sm transition-all duration-150`}+ >+ CNAME Record{subdomain && " (recommended)"}+ </button>+ </div>+ <div className="my-3 text-left">+ <p className="my-5 text-sm dark:text-white">+ To configure your{" "}+ {recordType === "A" ? "apex domain" : "subdomain"} (+ <InlineSnippet>+ {recordType === "A" ? domainJson.apexName : domainJson.name}+ </InlineSnippet>+ ), set the following {recordType} record on your DNS provider to+ continue:+ </p>+ <div className="flex items-center justify-start space-x-10 rounded-md bg-stone-50 p-2 dark:bg-stone-800 dark:text-white">+ <div>+ <p className="text-sm font-bold">Type</p>+ <p className="mt-2 font-mono text-sm">{recordType}</p>+ </div>+ <div>+ <p className="text-sm font-bold">Name</p>+ <p className="mt-2 font-mono text-sm">+ {recordType === "A" ? "@" : subdomain ?? "www"}+ </p>+ </div>+ <div>+ <p className="text-sm font-bold">Value</p>+ <p className="mt-2 font-mono text-sm">+ {recordType === "A"+ ? `76.76.21.21`+ : `cname.vercel-dns.com`}+ </p>+ </div>+ <div>+ <p className="text-sm font-bold">TTL</p>+ <p className="mt-2 font-mono text-sm">86400</p>+ </div>+ </div>+ <p className="mt-5 text-sm dark:text-white">+ Note: for TTL, if <InlineSnippet>86400</InlineSnippet> is not+ available, set the highest value possible. Also, domain+ propagation can take up to an hour.+ </p>+ </div>+ </>+ )}+ </div>+ );+}diff --git a/components/domains/use-domain-status.ts b/components/domains/use-domain-status.tsnew file mode 100644index 00000000..9f522323--- /dev/null+++ b/components/domains/use-domain-status.ts@@ -0,0 +1,24 @@+import useSWR from "swr";+import { fetcher } from "@/lib/utils";+import { DomainResponse, DomainVerificationStatusProps } from "@/lib/types";++export function useDomainStatus({ domain }: { domain: string }) {+ const { data, isValidating } = useSWR<{+ status: DomainVerificationStatusProps;+ domainJson: DomainResponse & { error: { code: string; message: string } };+ }>(+ `/api/domains/${domain}/verify`,+ (input, init) => fetcher(input, { ...init, cache: "no-store" }),+ {+ revalidateOnMount: true,+ refreshInterval: 5000,+ keepPreviousData: true,+ }+ );++ return {+ status: data?.status,+ domainJson: data?.domainJson,+ loading: isValidating,+ };+}diff --git a/lib/domains.ts b/lib/domains.tsnew file mode 100644index 00000000..fb661ffb--- /dev/null+++ b/lib/domains.ts@@ -0,0 +1,131 @@+import {+ DomainResponse,+ DomainConfigResponse,+ DomainVerificationResponse,+} from "@/lib/types";++import prisma from "@/lib/prisma"++export const addDomainToVercel = async (domain: string) => {+ return await fetch(+ `https://api.vercel.com/v9/projects/${process.env.PROJECT_ID_VERCEL}/domains?teamId=${process.env.TEAM_ID_VERCEL}`,+ {+ body: `{\n "name": "${domain}"\n}`,+ headers: {+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,+ "Content-Type": "application/json",+ },+ method: "POST",+ }+ ).then((res) => res.json());+};++export const removeDomainFromVercelProject = async (domain: string) => {+ return await fetch(+ `https://api.vercel.com/v9/projects/${process.env.PROJECT_ID_VERCEL}/domains/${domain}?teamId=${process.env.TEAM_ID_VERCEL}`,+ {+ headers: {+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,+ },+ method: "DELETE",+ }+ ).then((res) => res.json());+};++export const removeDomainFromVercelTeam = async (domain: string) => {+ return await fetch(+ `https://api.vercel.com/v6/domains/${domain}?teamId=${process.env.TEAM_ID_VERCEL}`,+ {+ headers: {+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,+ },+ method: "DELETE",+ }+ ).then((res) => res.json());+};++export const removeDomainFromVercel = async (domain: string, domainCount: number) => {+ if (domainCount > 1) {+ // the apex domain is being used by other domains+ // so we should only remove it from our Vercel project+ removeDomainFromVercelProject(domain);+ } else {+ // this is the only domain using this apex domain+ // so we can remove it entirely from our Vercel team+ removeDomainFromVercelProject(domain);+ removeDomainFromVercelTeam(domain);+ }+};++export const getDomainResponse = async (+ domain: string+): Promise<DomainResponse & { error: { code: string; message: string } }> => {+ return await fetch(+ `https://api.vercel.com/v9/projects/${process.env.PROJECT_ID_VERCEL}/domains/${domain}?teamId=${process.env.TEAM_ID_VERCEL}`,+ {+ 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+): Promise<DomainConfigResponse> => {+ return await fetch(+ `https://api.vercel.com/v6/domains/${domain}/config?teamId=${process.env.TEAM_ID_VERCEL}`,+ {+ method: "GET",+ headers: {+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,+ "Content-Type": "application/json",+ },+ }+ ).then((res) => res.json());+};++export const verifyDomain = async (+ domain: string+): Promise<DomainVerificationResponse> => {+ return await fetch(+ `https://api.vercel.com/v9/projects/${process.env.PROJECT_ID_VERCEL}/domains/${domain}/verify?teamId=${process.env.TEAM_ID_VERCEL}`,+ {+ method: "POST",+ headers: {+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,+ "Content-Type": "application/json",+ },+ }+ ).then((res) => res.json());+};++export const getSubdomain = (name: string, apexName: string) => {+ if (name === apexName) return null;+ return name.slice(0, name.length - apexName.length - 1);+};++export const getApexDomain = (url: string) => {+ let domain;+ try {+ domain = new URL(url).hostname;+ } catch (e) {+ return "";+ }+ const parts = domain.split(".");+ if (parts.length > 2) {+ // if it's a subdomain (e.g. dub.vercel.app), return the last 2 parts+ return parts.slice(-2).join(".");+ }+ // if it's a normal domain (e.g. dub.sh), we return the domain+ return domain;+};++// courtesy of ChatGPT: https://sharegpt.com/c/pUYXtRs+export const validDomainRegex = new RegExp(+ /^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/+);diff --git a/lib/swr/use-domains.ts b/lib/swr/use-domains.tsnew file mode 100644index 00000000..b4e08b8f--- /dev/null+++ b/lib/swr/use-domains.ts@@ -0,0 +1,20 @@+import useSWR from "swr";+import { fetcher } from "@/lib/utils";+import { Domain } from "@prisma/client";++export default function useDomains() {++ const { data: domains, error } = useSWR<Domain[]>(+ `/api/domains`,+ fetcher,+ {+ dedupingInterval: 60000,+ }+ );++ return {+ domains,+ loading: !domains && !error,+ error,+ };+}diff --git a/lib/types.ts b/lib/types.tsindex 5ec30f0f..718a1005 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -38,4 +38,65 @@ export interface Geo {region?: string | undefined;latitude?: string | undefined;longitude?: string | undefined;-}\ No newline at end of file+}++// Custom Domain Types++export type DomainVerificationStatusProps =+ | "Valid Configuration"+ | "Invalid Configuration"+ | "Pending Verification"+ | "Domain Not Found"+ | "Unknown Error";++// From https://vercel.com/docs/rest-api/endpoints#get-a-project-domain+export interface DomainResponse {+ name: string;+ apexName: string;+ projectId: string;+ redirect?: string | null;+ redirectStatusCode?: (307 | 301 | 302 | 308) | null;+ gitBranch?: string | null;+ updatedAt?: number;+ createdAt?: number;+ /** `true` if the domain is verified for use with the project. If `false` it will not be used as an alias on this project until the challenge in `verification` is completed. */+ verified: boolean;+ /** A list of verification challenges, one of which must be completed to verify the domain for use on the project. After the challenge is complete `POST /projects/:idOrName/domains/:domain/verify` to verify the domain. Possible challenges: - If `verification.type = TXT` the `verification.domain` will be checked for a TXT record matching `verification.value`. */+ verification: {+ type: string;+ domain: string;+ value: string;+ reason: string;+ }[];+}++// From https://vercel.com/docs/rest-api/endpoints#get-a-domain-s-configuration+export interface DomainConfigResponse {+ /** How we see the domain's configuration. - `CNAME`: Domain has a CNAME pointing to Vercel. - `A`: Domain's A record is resolving to Vercel. - `http`: Domain is resolving to Vercel but may be behind a Proxy. - `null`: Domain is not resolving to Vercel. */+ configuredBy?: ("CNAME" | "A" | "http") | null;+ /** Which challenge types the domain can use for issuing certs. */+ acceptedChallenges?: ("dns-01" | "http-01")[];+ /** Whether or not the domain is configured AND we can automatically generate a TLS certificate. */+ misconfigured: boolean;+}++// From https://vercel.com/docs/rest-api/endpoints#verify-project-domain+export interface DomainVerificationResponse {+ name: string;+ apexName: string;+ projectId: string;+ redirect?: string | null;+ redirectStatusCode?: (307 | 301 | 302 | 308) | null;+ gitBranch?: string | null;+ updatedAt?: number;+ createdAt?: number;+ /** `true` if the domain is verified for use with the project. If `false` it will not be used as an alias on this project until the challenge in `verification` is completed. */+ verified: boolean;+ /** A list of verification challenges, one of which must be completed to verify the domain for use on the project. After the challenge is complete `POST /projects/:idOrName/domains/:domain/verify` to verify the domain. Possible challenges: - If `verification.type = TXT` the `verification.domain` will be checked for a TXT record matching `verification.value`. */+ verification?: {+ type: string;+ domain: string;+ value: string;+ reason: string;+ }[];+}diff --git a/pages/api/domains/[slug]/index.ts b/pages/api/domains/[slug]/index.tsnew file mode 100644index 00000000..4843f179--- /dev/null+++ b/pages/api/domains/[slug]/index.ts@@ -0,0 +1,83 @@+import { NextApiRequest, NextApiResponse } from "next";+import { getServerSession } from "next-auth/next";+import prisma from "@/lib/prisma";+import { authOptions } from "@/pages/api//auth/[...nextauth]";+import { log } from "@/lib/utils";+import { getApexDomain, removeDomainFromVercel } from "@/lib/domains";+import { CustomUser } from "@/lib/types";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse+) {+ if (req.method === "DELETE") {+ // DELETE /api/domains/:domain+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ // Assuming the domain slug is sent in the request body.+ const { slug: domain } = req.query as { slug: string };++ console.log("Deleting domain:", domain);++ if (!domain) {+ return res.status(400).json("Domain is required for deletion");+ }++ try {+ // calculate the domainCount+ const apexDomain = getApexDomain(`https://${domain}`);+ const domainCount = await prisma.domain.count({+ where: {+ OR: [+ {+ slug: apexDomain,+ },+ {+ slug: {+ endsWith: `.${apexDomain}`,+ },+ },+ ],+ },+ });++ const domainToBeDeleted = await prisma.domain.findFirst({+ where: {+ slug: domain,+ userId: (session.user as CustomUser).id,+ },+ select: {+ id: true,+ },+ });++ if (!domainToBeDeleted) {+ return res.status(404).json("Domain not found");+ }++ await Promise.allSettled([+ removeDomainFromVercel(domain, domainCount),+ prisma.domain.delete({+ where: {+ id: domainToBeDeleted.id,+ },+ }),+ ]);++ res.status(204).end(); // 204 No Content response for successful deletes+ } catch (error) {+ log(`Failed to delete domain: ${domain}. Error: \n\n ${error}`);+ res.status(500).json({+ message: "Internal Server Error",+ error: (error as Error).message+ });+ }+ } else {+ // We only allow POST requests+ res.setHeader("Allow", ["DELETE"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}diff --git a/pages/api/domains/[slug]/verify.ts b/pages/api/domains/[slug]/verify.tsnew file mode 100644index 00000000..810dff06--- /dev/null+++ b/pages/api/domains/[slug]/verify.ts@@ -0,0 +1,51 @@+import { NextApiRequest, NextApiResponse } from 'next';+import {+ getConfigResponse,+ getDomainResponse,+ verifyDomain,+} from "@/lib/domains";+import { DomainVerificationStatusProps } from "@/lib/types";++export default async function handle(req: NextApiRequest, res: NextApiResponse) {+ // GET /api/domains/[slug]/verify - get domain verification status+ if (req.method === "GET") {+ const { slug: domain } = req.query as { slug: string; };+ let status: DomainVerificationStatusProps = "Valid Configuration";++ const [domainJson, configJson] = await Promise.all([+ getDomainResponse(domain),+ getConfigResponse(domain),+ ]);++ if (domainJson?.error?.code === "not_found") {+ // domain not found on Vercel project+ status = "Domain Not Found";++ // unknown error+ } else if (domainJson.error) {+ status = "Unknown Error";++ // if domain is not verified, we try to verify now+ } else if (!domainJson.verified) {+ status = "Pending Verification";+ const verificationJson = await verifyDomain(domain);++ // domain was just verified+ if (verificationJson && verificationJson.verified) {+ status = "Valid Configuration";+ }+ } else if (configJson.misconfigured) {+ status = "Invalid Configuration";+ } else {+ status = "Valid Configuration";+ }++ return res.status(200).json({+ status,+ domainJson,+ });+ } else {+ res.setHeader("Allow", ["GET"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}diff --git a/pages/api/domains/index.ts b/pages/api/domains/index.tsnew file mode 100644index 00000000..5b2d2dde--- /dev/null+++ b/pages/api/domains/index.ts@@ -0,0 +1,73 @@+import { NextApiRequest, NextApiResponse } from "next";+import { getServerSession } from "next-auth/next";+import prisma from "@/lib/prisma";+import { authOptions } from "../auth/[...nextauth]";+import { CustomUser } from "@/lib/types";+import { log } from "@/lib/utils";+import { addDomainToVercel, validDomainRegex } from "@/lib/domains";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse+) {+ if (req.method === "GET") {+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const domains = await prisma.domain.findMany({+ where: {+ userId: (session.user as CustomUser).id,+ },+ select: {+ slug: true,+ verified: true,+ },+ });+ return res.status(200).json(domains);++ } else if (req.method === "POST") {+ // POST /api/domains+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ res.status(401).end("Unauthorized");+ return;+ }++ // Assuming data is an object with `domain` properties+ const { domain } = req.body;++ // You could perform some validation here++ try {+ // TODO: Add check for if the domain already exists on another user+ const validDomain = validDomainRegex.test(domain);+ if (validDomain !== true) {+ return res.status(422).json("Invalid domain");+ }++ console.log("Valid domain", domain);++ const response = await prisma.domain.create({+ data: {+ slug: domain,+ userId: (session.user as CustomUser).id,+ },+ });+ await addDomainToVercel(domain)++ res.status(201).json(response);+ } catch (error) {+ log(`Failed to add domain. Error: \n\n ${error}`);+ res.status(500).json({+ message: "Internal Server Error",+ error: (error as Error).message,+ });+ }+ } else {+ // We only allow GET and POST requests+ res.setHeader("Allow", ["GET", "POST"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}diff --git a/pages/api/links/domains/[domain]/[slug]/index.ts b/pages/api/links/domains/[domain]/[slug]/index.tsnew file mode 100644index 00000000..0738c91e--- /dev/null+++ b/pages/api/links/domains/[domain]/[slug]/index.ts@@ -0,0 +1,43 @@+import { NextApiRequest, NextApiResponse } from "next";+import prisma from "@/lib/prisma";+import { getServerSession } from "next-auth/next";+import { authOptions } from "@/pages/api/auth/[...nextauth]";++export default async function handle(+ req: NextApiRequest,+ res: NextApiResponse+) {+ if (req.method === "GET") {+ // GET /api/links/domains/:domain/:slug+ const session = await getServerSession(req, res, authOptions);+ if (!session) {+ return res.status(401).end("Unauthorized");+ }++ const { domain, slug } = req.query as { domain: string, slug: string };++ try {+ const link = await prisma.link.findFirst({+ where: {+ slug: slug,+ domainSlug: domain,+ },+ select: {+ id: true,+ document: { select: { id: true, name: true, file: true } },+ },+ });++ res.status(200).json(link);+ } catch (error) {+ return res.status(500).json({+ message: "Internal Server Error",+ error: (error as Error).message,+ });+ }+ } else {+ // We only allow GET and POST requests+ res.setHeader("Allow", ["GET"]);+ return res.status(405).end(`Method ${req.method} Not Allowed`);+ }+}diff --git a/pages/settings/domains.tsx b/pages/settings/domains.tsxnew file mode 100644index 00000000..af72e6e2--- /dev/null+++ b/pages/settings/domains.tsx@@ -0,0 +1,61 @@+import { AddDomainModal } from "@/components/domains/add-domain-modal";+import DomainCard from "@/components/domains/domain-card";+import AppLayout from "@/components/layouts/app";+import useDomains from "@/lib/swr/use-domains";+import { mutate } from "swr";++export default function Domains() {++ const { domains } = useDomains();++ const handleDomainDeletion = (deletedDomain: string) => {+ mutate(+ "/api/domains",+ domains?.filter((domain) => domain.slug !== deletedDomain),+ false+ );+ };++ const handleDomainAddition = (newDomain: string) => {+ mutate("/api/domains", [...(domains || []), newDomain], false);+ }++ return (+ <AppLayout>+ <div className="p-4 sm:p-4 sm:m-4">+ <div className="flex items-center justify-between mb-4 md:mb-8 lg:mb-12">+ <div className="space-y-1">+ <h2 className="text-2xl text-white font-semibold tracking-tight">+ Domains+ </h2>+ <p className="text-sm text-gray-400">Manage your custom domains</p>+ </div>+ <ul className="flex items-center justify-between gap-4">+ <AddDomainModal onAddition={handleDomainAddition}>+ <button+ type="button"+ className="inline-flex items-center px-4 py-2 border border-transparent shadow-sm text-sm font-medium rounded-md text-gray-950 bg-gray-300 hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500"+ >+ Add Domain+ </button>+ </AddDomainModal>+ </ul>+ </div>+ {domains ? (+ <div>+ <h2 className="text-2xl font-semibold">Domains</h2>+ <ul>+ {domains.map((domain, index) => (+ <li key={index} className="mt-4">+ <DomainCard domain={domain.slug} onDelete={handleDomainDeletion} />+ </li>+ ))}+ </ul>+ </div>+ ) : null}+ </div>+ </AppLayout>+ );+}++diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex c868adaa..715719a5 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -46,6 +46,7 @@ model User {accounts Account[]sessions Session[]documents Document[]+ domains Domain[]}model VerificationToken {@@ -63,7 +64,7 @@ model Document {file String // This should be a reference to where the file is stored (S3, Google Cloud Storage, etc.)type String? // This should be a reference to the file type (pdf, docx, etc.)numPages Int? // This should be a reference to the number of pages in the document- owner User @relation(fields: [ownerId], references: [id])+ owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)ownerId String // This field holds the foreign key.createdAt DateTime @default(now())updatedAt DateTime @updatedAt@@ -73,24 +74,43 @@ model Document {model Link {id String @id @default(cuid())- document Document @relation(fields: [documentId], references: [id])+ document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)documentId Stringurl String? @uniquename String? // Link name+ slug String? // Link slug for pretty URLsexpiresAt DateTime? // Optional expiration datepassword String? // Optional password for link protectionallowedEmails String[] // Array of emails allowed to view the documentemailProtected Boolean? @default(true) // Optional email protectionviews View[]+ domain Domain? @relation(fields: [domainId], references: [id], onDelete: SetNull)+ domainId String? // This can be nullable, representing links without custom domains+ domainSlug String? // This will store the domain's slug even if the domain is deletedcreatedAt DateTime @default(now())updatedAt DateTime @updatedAt++ @@unique([domainSlug, slug])+}++model Domain {+ id String @id @default(cuid())+ slug String @unique+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ userId String+ verified Boolean @default(false) // Whether the domain has been verified+ lastChecked DateTime @default(now())+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt+ links Link[] // links associated with this domain}+model View {id String @id @default(cuid())link Link @relation(fields: [linkId], references: [id])linkId String- document Document @relation(fields: [documentId], references: [id])+ document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)documentId StringviewerEmail String? // Email of the viewer if knownviewedAt DateTime @default(now())