The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Added admin panel, moved login/register page to App Router, fixed robots.txt
Steven Teydf92964ac18e
diff --git a/app/admin/action.ts b/app/admin/action.tsnew file mode 100644index 0000000000..e18c8e9709--- /dev/null+++ b/app/admin/action.ts@@ -0,0 +1,199 @@+"use server";+import { deleteUserLinks } from "#/lib/api/links";+import { hashToken } from "#/lib/auth";+import { DUB_PROJECT_ID } from "#/lib/constants";+import prisma from "#/lib/prisma";+import { getDomainWithoutWWW } from "#/lib/utils";+import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { get } from "@vercel/edge-config";+import { randomBytes } from "crypto";+import { getServerSession } from "next-auth";++async function isAdmin() {+ const session = await getServerSession(authOptions);+ if (!session?.user) return false;+ const response = await prisma.projectUsers.findUnique({+ where: {+ userId_projectId: {+ // @ts-ignore+ userId: session.user.id,+ projectId: DUB_PROJECT_ID,+ },+ },+ });+ if (!response) return false;+ return true;+}++export async function getData(data: FormData) {+ const key = data.get("key") as string;++ if (!(await isAdmin())) {+ return {+ error: "Unauthorized",+ };+ }++ const response = await prisma.user.findFirst({+ where: {+ links: {+ some: {+ domain: "dub.sh",+ key,+ },+ },+ },+ select: {+ email: true,+ links: {+ where: {+ domain: "dub.sh",+ },+ select: {+ key: true,+ url: true,+ },+ },+ projects: {+ where: {+ role: "owner",+ },+ select: {+ project: {+ select: {+ name: true,+ slug: true,+ domains: {+ select: {+ slug: true,+ verified: true,+ },+ },+ },+ },+ },+ },+ },+ });+ if (!response?.email) {+ return {+ error: "No user found",+ };+ }++ const { email, links, projects } = response;++ const hostnames = new Set<string>();++ links.map((link) => {+ const hostname = getDomainWithoutWWW(link.url);+ hostname && hostnames.add(hostname);+ });++ const verifiedDomains = projects+ .filter(({ project }) => {+ return project.domains.some(({ verified }) => verified);+ })+ .flatMap(({ project }) => project.domains.map(({ slug }) => slug));++ const token = randomBytes(32).toString("hex");++ await prisma.verificationToken.create({+ data: {+ identifier: email,+ token: hashToken(token),+ expires: new Date(Date.now() + 60000),+ },+ });++ const params = new URLSearchParams({+ callbackUrl: process.env.NEXTAUTH_URL as string,+ email,+ token,+ });++ const url = `${process.env.NEXTAUTH_URL}/api/auth/callback/email?${params}`;++ return {+ email: response?.email as string,+ hostnames: Array.from(hostnames),+ verifiedDomains: verifiedDomains || [],+ impersonateUrl: url,+ };+}++export async function banUser(data: FormData) {+ const email = data.get("email") as string;+ const hostnames = data.getAll("hostname") as string[];++ if (!(await isAdmin())) {+ return {+ error: "Unauthorized",+ };+ }++ const user = await prisma.user.findUnique({+ where: {+ email,+ },+ select: {+ id: true,+ },+ });++ if (!user) {+ return {+ error: "No user found",+ };+ }++ const blacklistedDomains = await get("domains");+ const blacklistedEmails = await get("emails");++ const ban = await Promise.allSettled([+ deleteUserLinks(user.id),+ fetch(+ `https://api.vercel.com/v1/edge-config/${process.env.EDGE_CONFIG_ID}/items?teamId=${process.env.TEAM_ID_VERCEL}`,+ {+ method: "PATCH",+ headers: {+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ items: [+ {+ operation: "update",+ key: "domains",+ value: [...blacklistedDomains, ...hostnames],+ },+ {+ operation: "update",+ key: "emails",+ value: [...blacklistedEmails, email],+ },+ ],+ }),+ },+ ).then((res) => res.json()),+ ]);++ const response = await prisma.user.delete({+ where: {+ id: user.id,+ },+ });++ console.log(+ JSON.stringify(+ {+ ban,+ response,+ },+ null,+ 2,+ ),+ );++ return true;+}diff --git a/app/admin/layout.tsx b/app/admin/layout.tsxnew file mode 100644index 0000000000..18364188da--- /dev/null+++ b/app/admin/layout.tsx@@ -0,0 +1,15 @@+import { ReactNode } from "react";+import Background from "#/ui/home/background";++export default async function AdminLayout({+ children,+}: {+ children: ReactNode;+}) {+ return (+ <div className="flex h-screen w-screen justify-center">+ <Background />+ {children}+ </div>+ );+}diff --git a/app/admin/login/page.tsx b/app/admin/login/page.tsxnew file mode 100644index 0000000000..9b87c3cd31--- /dev/null+++ b/app/admin/login/page.tsx@@ -0,0 +1 @@+export { default } from "../../app/(auth)/login/page";diff --git a/app/admin/page.tsx b/app/admin/page.tsxnew file mode 100644index 0000000000..5613a72fdc--- /dev/null+++ b/app/admin/page.tsx@@ -0,0 +1,14 @@+import { constructMetadata } from "#/lib/utils";+import AdminStuff from "./stuff";++export const metadata = constructMetadata({+ title: "Dub Admin",+});++export default function AdminPage() {+ return (+ <div className="mx-auto min-h-screen w-full max-w-screen-sm bg-white p-5">+ <AdminStuff />+ </div>+ );+}diff --git a/app/admin/profile.tsx b/app/admin/profile.tsxnew file mode 100644index 0000000000..d59ff3e551--- /dev/null+++ b/app/admin/profile.tsx@@ -0,0 +1,35 @@+import { redirect } from "next/navigation";+import Link from "next/link";+import Image from "next/image";+import { getServerSession } from "next-auth";+import { authOptions } from "@/pages/api/auth/[...nextauth]";++export default async function Profile() {+ const session = await getServerSession(authOptions);+ if (!session?.user) {+ redirect("/login");+ }++ return (+ <div className="flex w-full items-center justify-between">+ <Link+ href="/settings"+ className="flex w-full flex-1 items-center space-x-3 rounded-lg px-2 py-1.5 transition-all duration-150 ease-in-out hover:bg-stone-200 active:bg-stone-300 dark:text-white dark:hover:bg-stone-700 dark:active:bg-stone-800"+ >+ <Image+ src={+ session.user.image ??+ `https://avatar.vercel.sh/${session.user.email}`+ }+ width={40}+ height={40}+ alt={session.user.name ?? "User avatar"}+ className="h-6 w-6 rounded-full"+ />+ <span className="truncate text-sm font-medium">+ {session.user.name}+ </span>+ </Link>+ </div>+ );+}diff --git a/app/admin/stuff.tsx b/app/admin/stuff.tsxnew file mode 100644index 0000000000..b8f6a2d019--- /dev/null+++ b/app/admin/stuff.tsx@@ -0,0 +1,149 @@+"use client";++import { cn } from "#/lib/utils";+import { experimental_useFormStatus as useFormStatus } from "react-dom";+import { LoadingSpinner } from "#/ui/icons";+import { banUser, getData } from "./action";+import { useState } from "react";+import Button from "#/ui/button";+import { toast } from "sonner";+import { Copy, Tick } from "@/components/shared/icons";+import { useRouter } from "next/navigation";++export default function AdminStuff() {+ const [data, setData] = useState<{+ email: string;+ hostnames: string[];+ verifiedDomains: string[];+ impersonateUrl: string;+ } | null>(null);+ const [copied, setCopied] = useState(false);+ const router = useRouter();++ return (+ <div className="flex flex-col space-y-5">+ <form+ action={(data) =>+ getData(data).then((res) => {+ if (res.error) {+ toast.error(res.error);+ } else {+ // @ts-ignore+ setData(res);+ }+ })+ }+ >+ <Form />+ </form>+ {data && (+ <form+ action={(data) =>+ banUser(data).then(() => {+ toast.success("Successfully banned user");+ router.refresh();+ })+ }+ className="flex w-full flex-col space-y-4 rounded-md border-t border-gray-200 py-4"+ >+ <div className="flex w-full items-center space-x-3">+ <input+ type="email"+ name="email"+ id="email"+ value={data.email}+ readOnly+ className="w-full rounded-md border-gray-300 text-sm text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500"+ />+ <button+ type="button"+ onClick={() => {+ setCopied(true);+ navigator.clipboard.writeText(data.impersonateUrl);+ toast.success("Copied to clipboard");+ setTimeout(() => {+ setCopied(false);+ }, 3000);+ }}+ className="rounded-md border border-gray-300 p-2"+ >+ {copied ? (+ <Tick className="h-5 w-5 text-gray-500" />+ ) : (+ <Copy className="h-5 w-5 text-gray-500" />+ )}+ </button>+ </div>+ {data.verifiedDomains.length > 0 && (+ <div className="flex flex-col space-y-2">+ <p className="text-sm font-semibold">Verified Domains</p>+ {data.verifiedDomains.map((domain) => (+ <div+ key={domain}+ className="rounded-md border border-gray-300 p-2 text-sm text-gray-500"+ >+ {domain}+ </div>+ ))}+ </div>+ )}+ {data.hostnames.map((hostname) => (+ <div key={hostname} className="space-x-2">+ <input+ type="checkbox"+ id={hostname}+ name="hostname"+ value={hostname}+ defaultChecked+ />+ <label htmlFor={hostname}>{hostname}</label>+ </div>+ ))}+ <BanButton disabled={data.verifiedDomains.length > 0} />+ </form>+ )}+ </div>+ );+}++const Form = () => {+ const { pending } = useFormStatus();++ return (+ <div className="relative flex w-full rounded-md shadow-sm">+ <span className="inline-flex items-center rounded-l-md border border-r-0 border-gray-300 bg-gray-50 px-5 text-gray-500 sm:text-sm">+ dub.sh+ </span>+ <input+ name="key"+ id="key"+ type="text"+ autoFocus+ required+ disabled={pending}+ autoComplete="off"+ className={cn(+ "block w-full rounded-r-md border-gray-300 text-sm text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500",+ pending && "bg-gray-100",+ )}+ placeholder="Sjw30s0"+ aria-invalid="true"+ />+ {pending && (+ <LoadingSpinner className="absolute inset-y-0 right-2 my-auto h-full w-5 text-gray-400" />+ )}+ </div>+ );+};++const BanButton = ({ disabled }: { disabled?: boolean }) => {+ const { pending } = useFormStatus();+ return (+ <Button+ text="Confirm Ban"+ loading={pending}+ disabled={disabled}+ variant="danger"+ />+ );+};diff --git a/app/app/(auth)/layout.tsx b/app/app/(auth)/layout.tsxnew file mode 100644index 0000000000..8a6cb92188--- /dev/null+++ b/app/app/(auth)/layout.tsx@@ -0,0 +1,13 @@+import Background from "#/ui/home/background";+import { ReactNode } from "react";++export const runtime = "edge";++export default function AuthLayout({ children }: { children: ReactNode }) {+ return (+ <div className="flex h-screen w-screen justify-center">+ <Background />+ {children}+ </div>+ );+}diff --git a/app/app/(auth)/login/action.ts b/app/app/(auth)/login/action.tsnew file mode 100644index 0000000000..a414b9e45e--- /dev/null+++ b/app/app/(auth)/login/action.ts@@ -0,0 +1,44 @@+"use server";++// we are not using this yet because it's not possible+// to use next-auth signIn in a server action yet+// will revisit this when that's possible++import { conn } from "#/lib/planetscale";+import { isWhitelistedEmail } from "#/lib/edge-config";++export async function accountExists(data: FormData) {+ const email = data.get("email") as string | undefined;++ if (!email) {+ return {+ error: "Missing email",+ };+ }+ if (!conn) {+ return {+ error: "Database connection not established",+ };+ }++ const user = await conn+ .execute("SELECT email FROM User WHERE email = ?", [email])+ .then((res) => res.rows[0]);++ if (user) {+ return {+ exists: true,+ };+ }++ const whitelisted = await isWhitelistedEmail(email);+ if (whitelisted) {+ return {+ exists: true,+ };+ }++ return {+ exists: false,+ };+}diff --git a/app/app/(auth)/login/form.tsx b/app/app/(auth)/login/form.tsxnew file mode 100644index 0000000000..ad67e9425f--- /dev/null+++ b/app/app/(auth)/login/form.tsx@@ -0,0 +1,140 @@+"use client";++import Link from "next/link";+import { useEffect, useState } from "react";+import { signIn } from "next-auth/react";+import { useSearchParams } from "next/navigation";+import { toast } from "sonner";+import Button from "#/ui/button";+import { Google } from "@/components/shared/icons";+import { SSOWaitlist } from "#/ui/tooltip";++export default function LoginForm() {+ const searchParams = useSearchParams();+ const next = searchParams?.get("next");+ const [showEmailOption, setShowEmailOption] = useState(false);+ const [noSuchAccount, setNoSuchAccount] = useState(false);+ const [email, setEmail] = useState("");+ const [clickedGoogle, setClickedGoogle] = useState(false);+ const [clickedEmail, setClickedEmail] = useState(false);++ useEffect(() => {+ const error = searchParams?.get("error");+ error && toast.error(error);+ }, [searchParams]);++ return (+ <div className="flex flex-col space-y-3 bg-gray-50 px-4 py-8 sm:px-16">+ <Button+ text="Continue with Google"+ onClick={() => {+ setClickedGoogle(true);+ signIn("google", {+ ...(next && next.length > 0 ? { callbackUrl: next } : {}),+ });+ }}+ loading={clickedGoogle}+ disabled={clickedEmail}+ icon={<Google className="h-4 w-4" />}+ />+ <form+ onSubmit={async (e) => {+ e.preventDefault();+ setClickedEmail(true);+ fetch("/api/auth/account-exists", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ email }),+ })+ .then(async (res) => {+ const { exists } = await res.json();+ if (exists) {+ signIn("email", {+ email,+ redirect: false,+ ...(next && next.length > 0 ? { callbackUrl: next } : {}),+ }).then((res) => {+ setClickedEmail(false);+ if (res?.ok && !res?.error) {+ setEmail("");+ toast.success("Email sent - check your inbox!");+ } else {+ toast.error("Error sending email - try again?");+ }+ });+ } else {+ toast.error("No account found with that email address.");+ setNoSuchAccount(true);+ setClickedEmail(false);+ }+ })+ .catch(() => {+ setClickedEmail(false);+ toast.error("Error sending email - try again?");+ });+ }}+ className="flex flex-col space-y-3"+ >+ {showEmailOption && (+ <div>+ <div className="mb-4 mt-1 border-t border-gray-300" />+ <input+ id="email"+ name="email"+ autoFocus+ type="email"+ placeholder="[email protected]"+ autoComplete="email"+ required+ value={email}+ onChange={(e) => {+ setNoSuchAccount(false);+ setEmail(e.target.value);+ }}+ className="mt-1 block w-full appearance-none rounded-md border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-black focus:outline-none focus:ring-black sm:text-sm"+ />+ </div>+ )}+ <Button+ text="Continue with Email"+ variant="secondary"+ {...(!showEmailOption && {+ type: "button",+ onClick: (e) => {+ e.preventDefault();+ setShowEmailOption(true);+ },+ })}+ loading={clickedEmail}+ disabled={clickedGoogle}+ />+ </form>+ <Button+ text="Continue with SAML SSO"+ disabled+ disabledTooltip={<SSOWaitlist />}+ />++ {noSuchAccount ? (+ <p className="text-center text-sm text-red-500">+ No such account.{" "}+ <Link href="/register" className="font-semibold text-red-600">+ Sign up+ </Link>{" "}+ instead?+ </p>+ ) : (+ <p className="text-center text-sm text-gray-500">+ Don't have an account?{" "}+ <Link+ href="/register"+ className="font-semibold text-gray-500 transition-colors hover:text-black"+ >+ Sign up+ </Link>+ .+ </p>+ )}+ </div>+ );+}diff --git a/app/app/(auth)/login/page.tsx b/app/app/(auth)/login/page.tsxnew file mode 100644index 0000000000..0964db31a8--- /dev/null+++ b/app/app/(auth)/login/page.tsx@@ -0,0 +1,43 @@+import { Suspense } from "react";+import LoginForm from "./form";+import Button from "#/ui/button";+import { Logo } from "@/components/shared/icons";+import { constructMetadata } from "#/lib/utils";++export const metadata = constructMetadata({+ title: "Sign in to Dub",+});++export default function LoginPage() {+ return (+ <div className="z-10 mt-[calc(30vh)] h-fit w-full max-w-md overflow-hidden border border-gray-100 sm:rounded-2xl sm:shadow-xl">+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 bg-white px-4 py-6 pt-8 text-center sm:px-16">+ <a+ href={+ process.env.NEXT_PUBLIC_VERCEL_ENV === "production"+ ? "https://dub.sh"+ : "http://localhost:3000"+ }+ >+ <Logo className="h-10 w-10" />+ </a>+ <h3 className="text-xl font-semibold">Sign in to Dub</h3>+ <p className="text-sm text-gray-500">+ Start creating short links with superpowers.+ </p>+ </div>+ <Suspense+ fallback={+ <div className="flex flex-col space-y-3 bg-gray-50 px-4 py-8 sm:px-16">+ <Button disabled={true} text="" variant="secondary" />+ <Button disabled={true} text="" variant="secondary" />+ <Button disabled={true} text="" variant="secondary" />+ <div className="mx-auto h-5 w-3/4 rounded-lg bg-gray-100" />+ </div>+ }+ >+ <LoginForm />+ </Suspense>+ </div>+ );+}diff --git a/app/app/(auth)/register/form.tsx b/app/app/(auth)/register/form.tsxnew file mode 100644index 0000000000..9e46b69eca--- /dev/null+++ b/app/app/(auth)/register/form.tsx@@ -0,0 +1,45 @@+"use client";++import { useSearchParams } from "next/navigation";+import { useState } from "react";+import { signIn } from "next-auth/react";+import { Google } from "@/components/shared/icons";+import Button from "#/ui/button";+import { SSOWaitlist } from "#/ui/tooltip";+import Link from "next/link";++export default function RegisterForm() {+ const searchParams = useSearchParams();+ const next = searchParams?.get("next");+ const [clickedGoogle, setClickedGoogle] = useState(false);+ return (+ <div className="flex flex-col space-y-3 bg-gray-50 px-4 py-8 sm:px-16">+ <Button+ text="Continue with Google"+ onClick={() => {+ setClickedGoogle(true);+ signIn("google", {+ ...(next && next.length > 0 ? { callbackUrl: next } : {}),+ });+ }}+ loading={clickedGoogle}+ icon={<Google className="h-4 w-4" />}+ />+ <Button+ text="Continue with SAML SSO"+ disabled+ disabledTooltip={<SSOWaitlist />}+ />+ <p className="text-center text-sm text-gray-500">+ Already have an account?{" "}+ <Link+ href="/login"+ className="font-semibold text-gray-500 transition-colors hover:text-black"+ >+ Sign in+ </Link>+ .+ </p>+ </div>+ );+}diff --git a/app/app/(auth)/register/page.tsx b/app/app/(auth)/register/page.tsxnew file mode 100644index 0000000000..54d309efec--- /dev/null+++ b/app/app/(auth)/register/page.tsx@@ -0,0 +1,42 @@+import { Suspense } from "react";+import RegisterForm from "./form";+import Button from "#/ui/button";+import { Logo } from "@/components/shared/icons";+import { constructMetadata } from "#/lib/utils";++export const metadata = constructMetadata({+ title: "Sign up to Dub",+});++export default function RegisterPage() {+ return (+ <div className="z-10 mt-[calc(30vh)] h-fit w-full max-w-md overflow-hidden border border-gray-100 sm:rounded-2xl sm:shadow-xl">+ <div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 bg-white px-4 py-6 pt-8 text-center sm:px-16">+ <a+ href={+ process.env.NEXT_PUBLIC_VERCEL_ENV === "production"+ ? "https://dub.sh"+ : "http://localhost:3000"+ }+ >+ <Logo className="h-10 w-10" />+ </a>+ <h3 className="text-xl font-semibold">Create your Dub account</h3>+ <p className="text-sm text-gray-500">+ Get started for free. No credit card required.+ </p>+ </div>+ <Suspense+ fallback={+ <div className="flex flex-col space-y-3 bg-gray-50 px-4 py-8 sm:px-16">+ <Button disabled={true} text="" variant="secondary" />+ <Button disabled={true} text="" variant="secondary" />+ <div className="mx-auto h-5 w-3/4 rounded-lg bg-gray-100" />+ </div>+ }+ >+ <RegisterForm />+ </Suspense>+ </div>+ );+}diff --git a/app/robots.ts b/app/robots.tsnew file mode 100644index 0000000000..508db7b4d0--- /dev/null+++ b/app/robots.ts@@ -0,0 +1,18 @@+import { isHomeHostname } from "#/lib/utils";+import { MetadataRoute } from "next";+import { headers } from "next/headers";++export default function robots(): MetadataRoute.Robots {+ const headersList = headers();+ let domain = headersList.get("host") as string;+ if (isHomeHostname(domain)) domain = "dub.sh";++ return {+ rules: {+ userAgent: "*",+ disallow: "/api/",+ allow: "/api/og/",+ },+ sitemap: `https://${domain}/sitemap.xml`,+ };+}diff --git a/app/ui/home/background/background.module.css b/app/ui/home/background/background.module.cssindex 5a0b4077e4..74027d236f 100644--- a/app/ui/home/background/background.module.css+++ b/app/ui/home/background/background.module.css@@ -60,9 +60,3 @@top: 80px;opacity: 0.15;}--@media screen and (max-width: 640px) {- .content {- display: none;- }-}diff --git a/app/ui/home/background/index.tsx b/app/ui/home/background/index.tsxindex 2de8466bc7..2d52ca17d9 100644--- a/app/ui/home/background/index.tsx+++ b/app/ui/home/background/index.tsx@@ -3,14 +3,19 @@import { useSelectedLayoutSegment } from "next/navigation";import styles from "./background.module.css";-const showBackgroundSegments = new Set(["metatags", "pricing"]);+const showBackgroundSegments = new Set([+ "metatags",+ "pricing",+ "login",+ "register",+]);export default function Background() {let segment;try {segment = useSelectedLayoutSegment();} catch (e) {- // this is for /login and /signup which are still on /pages router+ // this is for /welcome which is still on /pages router}return !segment || showBackgroundSegments.has(segment) ? (diff --git a/app/ui/home/demo/action.ts b/app/ui/home/demo/action.tsindex e738c3cae4..1e81005c68 100644--- a/app/ui/home/demo/action.ts+++ b/app/ui/home/demo/action.ts@@ -1,7 +1,7 @@"use server";import { setRandomKey } from "#/lib/upstash";-import { isBlacklistedDomain } from "#/lib/utils";+import { isBlacklistedDomain } from "#/lib/edge-config";export async function createLink(data: FormData) {const url = data.get("url") as string | undefined;diff --git a/app/ui/modal-provider.tsx b/app/ui/modal-provider.tsxindex f9420475bc..e3a887105c 100644--- a/app/ui/modal-provider.tsx+++ b/app/ui/modal-provider.tsx@@ -92,11 +92,12 @@ export default function ModalProvider({ children }: { children: ReactNode }) {!loading &&session?.user?.email &&!session.user?.name &&+ !router.asPath.startsWith("/welcome") &&!Cookies.get("hideGoogleOauthModal")) {setShowGoogleOauthModal(true);}- }, [error, session]);+ }, [error, session, router.asPath]);if (error && error.status === 404) {return <ErrorPage statusCode={404} />;diff --git a/lib/api/links.ts b/lib/api/links.tsindex 5aa814e20c..e091e951bf 100644--- a/lib/api/links.ts+++ b/lib/api/links.ts@@ -3,13 +3,8 @@ import { DEFAULT_REDIRECTS } from "#/lib/constants";import prisma from "#/lib/prisma";import { LinkProps } from "#/lib/types";import { redis } from "#/lib/upstash";-import {- getParamsFromURL,- isReservedKey,- nanoid,- truncate,- validKeyRegex,-} from "#/lib/utils";+import { getParamsFromURL, nanoid, truncate, validKeyRegex } from "#/lib/utils";+import { isReservedKey } from "#/lib/edge-config";import { NextApiRequest } from "next";export async function getLinksForProject({diff --git a/lib/auth.ts b/lib/auth.tsindex 3b4d13f419..8a536af99a 100644--- a/lib/auth.ts+++ b/lib/auth.ts@@ -3,6 +3,7 @@ import { getServerSession } from "next-auth/next";import prisma from "#/lib/prisma";import { LinkProps, PlanProps, ProjectProps, UserProps } from "#/lib/types";import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { createHash } from "crypto";export interface Session {user: {@@ -17,6 +18,11 @@ export async function getSession(req: NextApiRequest, res: NextApiResponse) {return (await getServerSession(req, res, authOptions)) as Session;}+export const hashToken = (token: string) => {+ return createHash("sha256")+ .update(`${token}${process.env.NEXTAUTH_SECRET}`)+ .digest("hex");+};interface WithProjectNextApiHandler {(req: NextApiRequest,diff --git a/lib/edge-config.ts b/lib/edge-config.tsnew file mode 100644index 0000000000..e941b76af8--- /dev/null+++ b/lib/edge-config.ts@@ -0,0 +1,54 @@+import { get } from "@vercel/edge-config";+import { getDomainWithoutWWW } from "./utils";++export const isBlacklistedDomain = async (domain: string) => {+ let blacklistedDomains;+ try {+ blacklistedDomains = await get("domains");+ } catch (e) {+ blacklistedDomains = [];+ }+ return new RegExp(blacklistedDomains.join("|")).test(+ getDomainWithoutWWW(domain) || domain,+ );+};++export const isBlacklistedKey = async (key: string) => {+ let blacklistedKeys;+ try {+ blacklistedKeys = await get("keys");+ } catch (e) {+ blacklistedKeys = [];+ }+ return new RegExp(blacklistedKeys.join("|"), "i").test(key);+};++export const isWhitelistedEmail = async (email: string) => {+ let whitelistedEmails;+ try {+ whitelistedEmails = await get("whitelist");+ } catch (e) {+ whitelistedEmails = [];+ }+ return new Set(whitelistedEmails).has(email);+};++export const isBlacklistedEmail = async (email: string) => {+ let blacklistedEmails;+ try {+ blacklistedEmails = await get("emails");+ } catch (e) {+ blacklistedEmails = [];+ }+ return new RegExp(blacklistedEmails.join("|"), "i").test(email);+};++export const isReservedKey = async (key: string) => {+ let reservedKey;+ try {+ reservedKey = await get("reserved");+ } catch (e) {+ reservedKey = [];+ }+ return new Set(reservedKey).has(key);+};diff --git a/lib/middleware/admin.ts b/lib/middleware/admin.tsnew file mode 100644index 0000000000..a7466a56c4--- /dev/null+++ b/lib/middleware/admin.ts@@ -0,0 +1,38 @@+import { NextRequest, NextResponse } from "next/server";+import { getToken } from "next-auth/jwt";+import { parse } from "#/lib/middleware/utils";+import { UserProps } from "../types";+import { conn } from "../planetscale";+import { DUB_PROJECT_ID } from "../constants";++export default async function AdminMiddleware(req: NextRequest) {+ const { path } = parse(req);+ let isAdmin = false;++ const session = (await getToken({+ req,+ secret: process.env.NEXTAUTH_SECRET,+ })) as {+ id?: string;+ email?: string;+ user?: UserProps;+ };++ const response = await conn+ ?.execute("SELECT projectId FROM ProjectUsers WHERE userId = ?", [+ session?.user?.id,+ ])+ .then((res) => res.rows[0] as { projectId: string } | undefined);++ if (response?.projectId === DUB_PROJECT_ID) {+ isAdmin = true;+ }++ if (path === "/login" && isAdmin) {+ return NextResponse.redirect(new URL("/", req.url));+ } else if (path !== "/login" && !isAdmin) {+ return NextResponse.redirect(new URL(`/login`, req.url));+ }++ return NextResponse.rewrite(new URL(`/admin${path}`, req.url));+}diff --git a/lib/utils.ts b/lib/utils.tsindex 91aeabae98..a0df0273d6 100644--- a/lib/utils.ts+++ b/lib/utils.ts@@ -11,7 +11,6 @@ import {SECOND_LEVEL_DOMAINS,HOME_HOSTNAMES,} from "./constants";-import { get } from "@vercel/edge-config";export function cn(...inputs: ClassValue[]) {return twMerge(clsx(inputs));@@ -452,55 +451,3 @@ export const log = async ({console.log(`Failed to log to Dub Slack. Error: ${e}`);}};--export const isBlacklistedDomain = async (domain: string) => {- let blacklistedDomains;- try {- blacklistedDomains = await get("domains");- } catch (e) {- blacklistedDomains = [];- }- return new RegExp(blacklistedDomains.join("|")).test(- getDomainWithoutWWW(domain) || domain,- );-};--export const isBlacklistedKey = async (key: string) => {- let blacklistedKeys;- try {- blacklistedKeys = await get("keys");- } catch (e) {- blacklistedKeys = [];- }- return new RegExp(blacklistedKeys.join("|"), "i").test(key);-};--export const isWhitelistedEmail = async (email: string) => {- let whitelistedEmails;- try {- whitelistedEmails = await get("whitelist");- } catch (e) {- whitelistedEmails = [];- }- return new Set(whitelistedEmails).has(email);-};--export const isBlacklistedEmail = async (email: string) => {- let blacklistedEmails;- try {- blacklistedEmails = await get("emails");- } catch (e) {- blacklistedEmails = [];- }- return new RegExp(blacklistedEmails.join("|"), "i").test(email);-};--export const isReservedKey = async (key: string) => {- let reservedKey;- try {- reservedKey = await get("reserved");- } catch (e) {- reservedKey = [];- }- return new Set(reservedKey).has(key);-};diff --git a/middleware.ts b/middleware.tsindex 7c132e2b38..b5d248f240 100644--- a/middleware.ts+++ b/middleware.ts@@ -7,7 +7,8 @@ import {RootMiddleware,} from "#/lib/middleware";import { parse } from "#/lib/middleware/utils";-import { isReservedKey } from "#/lib/utils";+import { isReservedKey } from "#/lib/edge-config";+import AdminMiddleware from "./lib/middleware/admin";export const config = {matcher: [@@ -18,9 +19,9 @@ export const config = {* 3. /_proxy/ (special page for OG tags proxying)* 4. /_static (inside /public)* 5. /_vercel (Vercel internals)- * 6. /favicon.ico, /sitemap.xml (static files)+ * 6. /favicon.ico, /sitemap.xml, /robots.txt (static files)*/- "/((?!api/|_next/|_proxy/|_static|_vercel|favicon.ico|sitemap.xml).*)",+ "/((?!api/|_next/|_proxy/|_static|_vercel|favicon.ico|sitemap.xml|robots.txt).*)",],};@@ -37,6 +38,11 @@ export default async function middleware(req: NextRequest, ev: NextFetchEvent) {return ApiMiddleware(req);}+ // for Admin (admin.dub.sh and admin.localhost:3000)+ if (domain === "admin.dub.sh" || domain === "admin.localhost:3000") {+ return AdminMiddleware(req);+ }+// for public stats pages (e.g. dub.sh/stats/github)if (key === "stats") {return NextResponse.rewrite(new URL(`/${domain}${path}`, req.url));diff --git a/next.config.js b/next.config.jsindex 4fd7f74e7e..770155e056 100644--- a/next.config.js+++ b/next.config.js@@ -4,7 +4,9 @@ const { withContentlayer } = require("next-contentlayer");const nextConfig = {reactStrictMode: false,experimental: {+ useDeploymentId: true,serverActions: true,+ useDeploymentIdServerActions: true,},images: {domains: [diff --git a/package.json b/package.jsonindex 0b8fd6f16d..9043566c4a 100644--- a/package.json+++ b/package.json@@ -56,7 +56,7 @@"lucide-react": "^0.192.0","ms": "^2.1.3","next": "^13.4.10-canary.3",- "next-auth": "^4.22.1",+ "next-auth": "^4.22.3","next-contentlayer": "^0.3.3","node-html-parser": "^6.1.4","nodemailer": "^6.9.3",diff --git a/pages/api/auth/[...nextauth].tsx b/pages/api/auth/[...nextauth].tsxindex 950c4ca595..7596f3f63c 100644--- a/pages/api/auth/[...nextauth].tsx+++ b/pages/api/auth/[...nextauth].tsx@@ -6,7 +6,7 @@ import NextAuth, { type NextAuthOptions } from "next-auth";import EmailProvider from "next-auth/providers/email";import GoogleProvider from "next-auth/providers/google";import prisma from "#/lib/prisma";-import { isBlacklistedEmail } from "#/lib/utils";+import { isBlacklistedEmail } from "#/lib/edge-config";const VERCEL_DEPLOYMENT = !!process.env.VERCEL_URL;diff --git a/pages/api/auth/account-exists.ts b/pages/api/auth/account-exists.tsindex b8fcc98c22..86f5bb5b44 100644--- a/pages/api/auth/account-exists.ts+++ b/pages/api/auth/account-exists.ts@@ -3,7 +3,7 @@ import { ratelimit } from "#/lib/upstash";import { ipAddress } from "@vercel/edge";import { LOCALHOST_IP } from "#/lib/constants";import { conn } from "#/lib/planetscale";-import { isWhitelistedEmail } from "#/lib/utils";+import { isWhitelistedEmail } from "#/lib/edge-config";export const config = {runtime: "edge",diff --git a/pages/api/links/[key]/index.ts b/pages/api/links/[key]/index.tsindex ae2c7b10f9..183be3c165 100644--- a/pages/api/links/[key]/index.ts+++ b/pages/api/links/[key]/index.ts@@ -1,6 +1,7 @@import { withLinksAuth } from "#/lib/auth";import { deleteLink, editLink, processKey } from "#/lib/api/links";-import { isBlacklistedDomain, isBlacklistedKey, log } from "#/lib/utils";+import { isBlacklistedDomain, isBlacklistedKey } from "#/lib/edge-config";+import { log } from "#/lib/utils";import { GOOGLE_FAVICON_URL } from "#/lib/constants";export const config = {diff --git a/pages/api/links/index.ts b/pages/api/links/index.tsindex 18e1ca0660..d7df4a1203 100644--- a/pages/api/links/index.ts+++ b/pages/api/links/index.ts@@ -1,6 +1,6 @@import { addLink, getLinksForProject, processKey } from "#/lib/api/links";import { withLinksAuth } from "#/lib/auth";-import { isBlacklistedDomain, isBlacklistedKey } from "#/lib/utils";+import { isBlacklistedDomain, isBlacklistedKey } from "#/lib/edge-config";import { log } from "#/lib/utils";import { DUB_PROJECT_ID, GOOGLE_FAVICON_URL } from "#/lib/constants";diff --git a/pages/api/projects/[slug]/exists.ts b/pages/api/projects/[slug]/exists.tsindex d6c481ce9d..b19bf747a4 100644--- a/pages/api/projects/[slug]/exists.ts+++ b/pages/api/projects/[slug]/exists.ts@@ -2,7 +2,7 @@ import { NextApiRequest, NextApiResponse } from "next";import { withUserAuth } from "#/lib/auth";import { DEFAULT_REDIRECTS } from "#/lib/constants";import prisma from "#/lib/prisma";-import { isReservedKey } from "#/lib/utils";+import { isReservedKey } from "#/lib/edge-config";export default withUserAuth(async (req: NextApiRequest, res: NextApiResponse) => {diff --git a/pages/api/projects/[slug]/invites/index.tsx b/pages/api/projects/[slug]/invites/index.tsxindex 55b7d534e5..7205eac735 100644--- a/pages/api/projects/[slug]/invites/index.tsx+++ b/pages/api/projects/[slug]/invites/index.tsx@@ -1,15 +1,9 @@-import { withProjectAuth } from "#/lib/auth";+import { hashToken, withProjectAuth } from "#/lib/auth";import prisma from "#/lib/prisma";import { sendEmail } from "emails";-import { randomBytes, createHash } from "crypto";+import { randomBytes } from "crypto";import ProjectInvite from "emails/project-invite";-const hashToken = (token: string) => {- return createHash("sha256")- .update(`${token}${process.env.NEXTAUTH_SECRET}`)- .digest("hex");-};-export default withProjectAuth(async (req, res, project, session) => {// GET /api/projects/[slug]/invites - Get all pending invites for a projectif (req.method === "GET") {diff --git a/pages/api/projects/index.ts b/pages/api/projects/index.tsindex 63c8760212..5273237b28 100644--- a/pages/api/projects/index.ts+++ b/pages/api/projects/index.ts@@ -7,7 +7,8 @@ import {validateDomain,} from "#/lib/api/domains";import prisma from "#/lib/prisma";-import { isReservedKey, validSlugRegex } from "#/lib/utils";+import { isReservedKey } from "#/lib/edge-config";+import { validSlugRegex } from "#/lib/utils";export default withUserAuth(async (req: NextApiRequest, res: NextApiResponse, session: Session) => {diff --git a/pages/app/login.tsx b/pages/app/login.tsxdeleted file mode 100644index c75cb372d7..0000000000--- a/pages/app/login.tsx+++ /dev/null@@ -1,167 +0,0 @@-import Link from "next/link";-import { useEffect, useState } from "react";-import { signIn } from "next-auth/react";-import Meta from "@/components/layout/meta";-import BlurImage from "#/ui/blur-image";-import Background from "#/ui/home/background";-import { toast } from "sonner";-import Button from "#/ui/button";-import { Google } from "@/components/shared/icons";-import { SSOWaitlist } from "#/ui/tooltip";-import { useRouter } from "next/router";--export default function Login() {- const router = useRouter();- const { next, error } = router.query as { next?: string; error?: string };- const [showEmailOption, setShowEmailOption] = useState(false);- const [noSuchAccount, setNoSuchAccount] = useState(false);- const [email, setEmail] = useState("");- const [clickedGoogle, setClickedGoogle] = useState(false);- const [clickedEmail, setClickedEmail] = useState(false);-- useEffect(() => {- error && toast.error(error);- }, [error]);-- return (- <div className="flex h-screen w-screen justify-center">- <Meta title="Sign in to Dub" />- <Background />- <div className="z-10 mt-[calc(30vh)] h-fit w-full max-w-md overflow-hidden border border-gray-100 sm:rounded-2xl sm:shadow-xl">- <div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 bg-white px-4 py-6 pt-8 text-center sm:px-16">- <a- href={- process.env.NEXT_PUBLIC_VERCEL_ENV === "production"- ? "https://dub.sh"- : "http://localhost:3000"- }- >- <BlurImage- src="/_static/logo.png"- alt="Dub.sh logo"- className="h-10 w-10 rounded-full"- width={20}- height={20}- />- </a>- <h3 className="text-xl font-semibold">Sign in to Dub</h3>- <p className="text-sm text-gray-500">- Start creating short links with superpowers.- </p>- </div>- <div className="flex flex-col space-y-3 bg-gray-50 px-4 py-8 sm:px-16">- <Button- text="Continue with Google"- onClick={() => {- setClickedGoogle(true);- signIn("google", {- ...(next && next.length > 0 ? { callbackUrl: next } : {}),- });- }}- loading={clickedGoogle}- disabled={clickedEmail}- icon={<Google className="h-4 w-4" />}- />- <form- onSubmit={async (e) => {- e.preventDefault();- setClickedEmail(true);- fetch("/api/auth/account-exists", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ email }),- })- .then(async (res) => {- const { exists } = await res.json();- if (exists) {- signIn("email", {- email,- redirect: false,- ...(next && next.length > 0 ? { callbackUrl: next } : {}),- }).then((res) => {- setClickedEmail(false);- if (res?.ok && !res?.error) {- setEmail("");- toast.success("Email sent - check your inbox!");- } else {- toast.error("Error sending email - try again?");- }- });- } else {- toast.error("No account found with that email address.");- setNoSuchAccount(true);- setClickedEmail(false);- }- })- .catch(() => {- setClickedEmail(false);- toast.error("Error sending email - try again?");- });- }}- className="flex flex-col space-y-3"- >- {showEmailOption && (- <div>- <div className="mb-4 mt-1 border-t border-gray-300" />- <input- id="email"- name="email"- autoFocus- type="email"- placeholder="[email protected]"- autoComplete="email"- required- value={email}- onChange={(e) => {- setNoSuchAccount(false);- setEmail(e.target.value);- }}- className="mt-1 block w-full appearance-none rounded-md border border-gray-300 px-3 py-2 placeholder-gray-400 shadow-sm focus:border-black focus:outline-none focus:ring-black sm:text-sm"- />- </div>- )}- <Button- text="Continue with Email"- variant="secondary"- {...(!showEmailOption && {- type: "button",- onClick: (e) => {- e.preventDefault();- setShowEmailOption(true);- },- })}- loading={clickedEmail}- disabled={clickedGoogle}- />- </form>- <Button- text="Continue with SAML SSO"- disabled- disabledTooltip={<SSOWaitlist />}- />-- {noSuchAccount ? (- <p className="text-center text-sm text-red-500">- No such account.{" "}- <Link href="/register" className="font-semibold text-red-600">- Sign up- </Link>{" "}- instead?- </p>- ) : (- <p className="text-center text-sm text-gray-500">- Don't have an account?{" "}- <Link- href="/register"- className="font-semibold text-gray-500 transition-colors hover:text-black"- >- Sign up- </Link>- .- </p>- )}- </div>- </div>- </div>- );-}diff --git a/pages/app/register.tsx b/pages/app/register.tsxdeleted file mode 100644index dbd5d64cf3..0000000000--- a/pages/app/register.tsx+++ /dev/null@@ -1,75 +0,0 @@-import { useState } from "react";-import { signIn } from "next-auth/react";-import Meta from "@/components/layout/meta";-import BlurImage from "#/ui/blur-image";-import Background from "#/ui/home/background";-import { Google } from "@/components/shared/icons";-import Button from "#/ui/button";-import { SSOWaitlist } from "#/ui/tooltip";-import Link from "next/link";-import { useRouter } from "next/router";--export default function Register() {- const router = useRouter();- const { next } = router.query as { next?: string };- const [clickedGoogle, setClickedGoogle] = useState(false);-- return (- <div className="flex h-screen w-screen justify-center">- <Meta title="Sign up for Dub" />- <Background />- <div className="z-10 mt-[calc(30vh)] h-fit w-full max-w-md overflow-hidden border border-gray-100 sm:rounded-2xl sm:shadow-xl">- <div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 bg-white px-4 py-6 pt-8 text-center sm:px-16">- <a- href={- process.env.NEXT_PUBLIC_VERCEL_ENV === "production"- ? "https://dub.sh"- : "http://localhost:3000"- }- >- <BlurImage- src="/_static/logo.png"- alt="Dub.sh logo"- className="h-10 w-10 rounded-full"- width={20}- height={20}- />- </a>- <h3 className="text-xl font-semibold">Create your Dub account</h3>- <p className="text-sm text-gray-500">- Get started for free. No credit card required.- </p>- </div>-- <div className="flex flex-col space-y-3 bg-gray-50 px-4 py-8 sm:px-16">- <Button- text="Continue with Google"- onClick={() => {- setClickedGoogle(true);- signIn("google", {- ...(next && next.length > 0 ? { callbackUrl: next } : {}),- });- }}- loading={clickedGoogle}- icon={<Google className="h-4 w-4" />}- />- <Button- text="Continue with SAML SSO"- disabled- disabledTooltip={<SSOWaitlist />}- />- <p className="text-center text-sm text-gray-500">- Already have an account?{" "}- <Link- href="/login"- className="font-semibold text-gray-500 transition-colors hover:text-black"- >- Sign in- </Link>- .- </p>- </div>- </div>- </div>- );-}diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 1c428b3f8a..35e59320b4 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -9,7 +9,7 @@ datasource db {generator client {provider = "prisma-client-js"- previewFeatures = ["fullTextSearch", "fullTextIndex", "jsonProtocol"]+ previewFeatures = ["fullTextSearch", "fullTextIndex"]}model User {diff --git a/yarn.lock b/yarn.lockindex 6535c95120..db7a1962df 100644--- a/yarn.lock+++ b/yarn.lock@@ -6254,10 +6254,10 @@ negotiator@^0.6.3:resolved "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz"integrity sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==-next-auth@^4.22.1:- version "4.22.1"- resolved "https://registry.npmjs.org/next-auth/-/next-auth-4.22.1.tgz"- integrity sha512-NTR3f6W7/AWXKw8GSsgSyQcDW6jkslZLH8AiZa5PQ09w1kR8uHtR9rez/E9gAq/o17+p0JYHE8QjF3RoniiObA==+next-auth@^4.22.3:+ version "4.22.3"+ resolved "https://registry.yarnpkg.com/next-auth/-/next-auth-4.22.3.tgz#bbe5152e0e3ea6d625731f23adba4fd2e3d2d570"+ integrity sha512-XAgy9xV3J2eJOXrQhmxdjV6MLM29ibm6WtMXc3KY6IPZeApf+SuBuPvlqCUfbu5YsAzlg9WSw6u01dChTfeZOA==dependencies:"@babel/runtime" "^7.20.13""@panva/hkdf" "^1.0.2"