Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Use server actions for password page, made sitemap multitenant

Steven Tey6f68e779d194
diff --git a/app/+auth/[domain]/[key]/action.ts b/app/+auth/[domain]/[key]/action.ts
new file mode 100644
index 0000000000..a2173e7f0b
--- /dev/null
+++ b/app/+auth/[domain]/[key]/action.ts
@@ -0,0 +1,25 @@
+"use server";
+import prisma from "#/lib/prisma";
+
+export async function verifyPassword(data: FormData) {
+ const domain = data.get("domain") as string;
+ const key = data.get("key") as string;
+ const password = data.get("password") as string;
+
+ const link = await prisma.link.findUnique({
+ where: { domain_key: { domain, key } },
+ select: { url: true, password: true },
+ });
+ if (!link) {
+ return { error: "Link not found" };
+ }
+ const { url, password: realPassword } = link;
+
+ const validPassword = password === realPassword;
+
+ if (validPassword) {
+ return { url };
+ } else {
+ return { error: "Invalid password" };
+ }
+}
diff --git a/app/+auth/[domain]/[key]/form.tsx b/app/+auth/[domain]/[key]/form.tsx
new file mode 100644
index 0000000000..21903222a4
--- /dev/null
+++ b/app/+auth/[domain]/[key]/form.tsx
@@ -0,0 +1,80 @@
+"use client";
+
+import { useParams, useRouter } from "next/navigation";
+import { useState } from "react";
+import { experimental_useFormStatus as useFormStatus } from "react-dom";
+import { verifyPassword } from "./action";
+import { AlertCircleFill } from "@/components/shared/icons";
+import Button from "#/ui/button";
+import { toast } from "sonner";
+
+export default function PasswordForm() {
+ const { domain, key } = useParams() as {
+ domain: string;
+ key: string;
+ };
+ const router = useRouter();
+
+ const [error, setError] = useState(false);
+
+ return (
+ <form
+ action={(data) =>
+ verifyPassword(data).then((res) => {
+ if (res.error) {
+ setError(true);
+ toast.error(res.error);
+ } else {
+ router.push(res.url!);
+ }
+ })
+ }
+ className="flex flex-col space-y-4 bg-gray-50 px-4 py-8 sm:px-16"
+ >
+ <div>
+ <label htmlFor="password" className="block text-xs text-gray-600">
+ PASSWORD
+ </label>
+ <div className="relative mt-1 rounded-md shadow-sm">
+ <input type="hidden" name="domain" value={domain} />
+ <input type="hidden" name="key" value={key} />
+ <input
+ type="password"
+ name="password"
+ id="password"
+ autoFocus
+ required
+ onChange={() => {
+ setError(false);
+ }}
+ className={`${
+ error
+ ? "border-red-300 text-red-500 placeholder-red-300 focus:border-red-500 focus:ring-red-500"
+ : "border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:ring-gray-500"
+ } block w-full rounded-md pr-10 focus:outline-none sm:text-sm`}
+ />
+ {error && (
+ <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
+ <AlertCircleFill
+ className="h-5 w-5 text-red-500"
+ aria-hidden="true"
+ />
+ </div>
+ )}
+ </div>
+ {error && (
+ <p className="mt-2 text-sm text-red-600" id="slug-error">
+ Incorrect password
+ </p>
+ )}
+ </div>
+
+ <FormButton />
+ </form>
+ );
+}
+
+const FormButton = () => {
+ const { pending } = useFormStatus();
+ return <Button text="Authenticate" loading={pending} />;
+};
diff --git a/app/+auth/[domain]/[key]/page.tsx b/app/+auth/[domain]/[key]/page.tsx
new file mode 100644
index 0000000000..1adf01f605
--- /dev/null
+++ b/app/+auth/[domain]/[key]/page.tsx
@@ -0,0 +1,37 @@
+import { constructMetadata } from "#/lib/utils";
+import BlurImage from "#/ui/blur-image";
+import PasswordForm from "./form";
+
+const title = "Password Required";
+const description =
+ "This link is password protected. Please enter the password to view it.";
+const image = "https://dub.sh/_static/password-protected.png";
+
+export const metadata = constructMetadata({
+ title,
+ description,
+ image,
+});
+
+export default function PasswordProtectedLinkPage() {
+ return (
+ <main className="flex h-screen w-screen items-center justify-center bg-gray-50">
+ <div className="w-full max-w-md overflow-hidden rounded-2xl border border-gray-100 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="https://dub.sh" target="_blank" rel="noreferrer">
+ <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">{title}</h3>
+ <p className="text-sm text-gray-500">{description}</p>
+ </div>
+ <PasswordForm />
+ </div>
+ </main>
+ );
+}
diff --git a/app/dub.sh/layout.tsx b/app/dub.sh/layout.tsx
index 8166d63c65..3e97096f59 100644
--- a/app/dub.sh/layout.tsx
+++ b/app/dub.sh/layout.tsx
@@ -1,4 +1,4 @@
-import Providers from "./providers";
+import MarketingProviders from "./providers";
import Nav from "#/ui/home/nav";
import Footer from "#/ui/home/footer";
import Background from "#/ui/home/background";
@@ -6,7 +6,7 @@ import MobileNav from "#/ui/home/nav-mobile";
export default function MarketingLayout(props) {
return (
- <Providers modal={props.modal}>
+ <MarketingProviders modal={props.modal}>
<div className="flex min-h-screen flex-col">
<MobileNav />
<Nav />
@@ -14,6 +14,6 @@ export default function MarketingLayout(props) {
<Footer />
<Background />
</div>
- </Providers>
+ </MarketingProviders>
);
}
diff --git a/app/dub.sh/providers.tsx b/app/dub.sh/providers.tsx
index b9c4b11c13..85c1730b71 100644
--- a/app/dub.sh/providers.tsx
+++ b/app/dub.sh/providers.tsx
@@ -2,9 +2,8 @@
import { useSelectedLayoutSegment } from "next/navigation";
import { ReactNode } from "react";
-import { Toaster } from "sonner";
-export default function Providers({
+export default function MarketingProviders({
modal,
children,
}: {
@@ -13,11 +12,10 @@ export default function Providers({
}) {
const segment = useSelectedLayoutSegment();
return (
- <div>
+ <>
{/* Only show stats modal if it's on the home page */}
{!segment && modal}
- <Toaster />
{children}
- </div>
+ </>
);
}
diff --git a/app/layout.tsx b/app/layout.tsx
index 41e7323240..7c2a73ce8b 100644
--- a/app/layout.tsx
+++ b/app/layout.tsx
@@ -1,7 +1,7 @@
import "@/styles/globals.css";
import { satoshi, inter } from "@/styles/fonts";
-import { Analytics } from "@vercel/analytics/react";
import { cn, constructMetadata } from "#/lib/utils";
+import Providers from "./providers";
export const metadata = constructMetadata({});
@@ -13,8 +13,7 @@ export default function RootLayout({
return (
<html lang="en">
<body className={cn(satoshi.variable, inter.variable)}>
- {children}
- <Analytics />
+ <Providers>{children}</Providers>
</body>
</html>
);
diff --git a/app/providers.tsx b/app/providers.tsx
new file mode 100644
index 0000000000..7c3829fcfb
--- /dev/null
+++ b/app/providers.tsx
@@ -0,0 +1,15 @@
+"use client";
+
+import { ReactNode } from "react";
+import { Toaster } from "sonner";
+import { Analytics } from "@vercel/analytics/react";
+
+export default function Providers({ children }: { children: ReactNode }) {
+ return (
+ <>
+ <Toaster />
+ {children}
+ <Analytics />
+ </>
+ );
+}
diff --git a/app/sitemap.ts b/app/sitemap.ts
index a9e34c1ff7..d4cf097d5f 100644
--- a/app/sitemap.ts
+++ b/app/sitemap.ts
@@ -1,8 +1,11 @@
import prisma from "#/lib/prisma";
+import { headers } from "next/headers";
+import { getDomain } from "#/lib/utils";
import { allChangelogPosts, allLegalPosts } from "contentlayer/generated";
export default async function Sitemap() {
- const domain = "dub.sh";
+ const headersList = headers();
+ const domain = getDomain(headersList);
const links = await prisma.link.findMany({
where: {
diff --git a/components/app/modals/upgrade-plan-modal/pricing.tsx b/components/app/modals/upgrade-plan-modal/pricing.tsx
index ceda8f88f1..affcd8265f 100644
--- a/components/app/modals/upgrade-plan-modal/pricing.tsx
+++ b/components/app/modals/upgrade-plan-modal/pricing.tsx
@@ -201,7 +201,9 @@ const Pricing = ({ homePage }: { homePage?: boolean }) => {
<div className="flex h-20 items-center justify-center border-b border-t border-gray-200 bg-gray-50">
<div className="flex items-center">
<p className="text-gray-600">
- Up to {nFormatter(quota)} link clicks/mo
+ {plan === "Enterprise"
+ ? "Unlimited link clicks"
+ : `Up to ${nFormatter(quota)} link clicks/mo`}
</p>
<Tooltip content="If you exceed your monthly usage, your existing links will still work, but you need to upgrade to view their stats/add more links.">
<div className="flex h-4 w-8 justify-center">
diff --git a/lib/middleware/link.ts b/lib/middleware/link.ts
index 5e0ae79f9a..4cb164f4b8 100644
--- a/lib/middleware/link.ts
+++ b/lib/middleware/link.ts
@@ -29,16 +29,17 @@ export default async function LinkMiddleware(
const { url: target, password, proxy, ios, android } = response || {};
if (target) {
+ if (password) {
+ // rewrite to auth page (/_auth/[domain]/[key]) if the link is password protected
+ console.log("password protected link", `/+auth/${domain}/${key}`);
+ return NextResponse.rewrite(new URL(`/+auth/${domain}/${key}`, req.url));
+ }
+
// special case for link health monitoring with planetfall.io :)
if (!req.headers.get("dub-no-track")) {
ev.waitUntil(recordClick(domain, req, key)); // track the click only if there is no `dub-no-track` header
}
- if (password) {
- // rewrite to auth page (/_auth/[domain]/[key]) if the link is password protected
- return NextResponse.rewrite(new URL(`/_auth/${domain}/${key}`, req.url));
- }
-
const isBot = detectBot(req);
if (isBot && proxy) {
// rewrite to proxy page (/_proxy/[domain]/[key]) if it's a bot
diff --git a/next.config.js b/next.config.js
index 6ff5ed56f1..899f693050 100644
--- a/next.config.js
+++ b/next.config.js
@@ -3,6 +3,9 @@ const { withContentlayer } = require("next-contentlayer");
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: false,
+ experimental: {
+ serverActions: true,
+ },
images: {
domains: [
"www.google.com",
diff --git a/package.json b/package.json
index bc87e64eef..932084402f 100644
--- a/package.json
+++ b/package.json
@@ -63,7 +63,7 @@
"punycode": "^2.3.0",
"react": "^18.2.0",
"react-colorful": "^5.6.1",
- "react-dom": "18.2.0",
+ "react-dom": "^18.2.0",
"react-dom-confetti": "^0.2.0",
"react-parallax-tilt": "^1.7.70",
"react-spring": "^9.5.5",
@@ -89,8 +89,8 @@
"@types/html-escaper": "^3.0.0",
"@types/ms": "^0.7.31",
"@types/node": "18.11.9",
- "@types/react": "18.0.25",
- "@types/react-dom": "18.0.9",
+ "@types/react": "^18.2.14",
+ "@types/react-dom": "^18.2.6",
"@types/topojson-client": "^3.1.1",
"array-to-ndjson": "^1.0.1",
"autoprefixer": "^10.4.13",
@@ -99,6 +99,6 @@
"prettier": "^2.8.0",
"prettier-plugin-tailwindcss": "^0.1.13",
"tailwindcss": "^3.3.2",
- "typescript": "^4.9.3"
+ "typescript": "^5.1.6"
}
}
diff --git a/pages/_auth/[domain]/[key].tsx b/pages/_auth/[domain]/[key].tsx
deleted file mode 100644
index 3899ebe00d..0000000000
--- a/pages/_auth/[domain]/[key].tsx
+++ /dev/null
@@ -1,131 +0,0 @@
-import Head from "next/head";
-import { useRouter } from "next/router";
-import { useState } from "react";
-import BlurImage from "#/ui/blur-image";
-import { AlertCircleFill } from "@/components/shared/icons";
-import { LoadingDots } from "#/ui/icons";
-import { FAVICON_FOLDER } from "#/lib/constants";
-
-const title = "Password Required";
-const description =
- "This link is password protected. Please enter the password to view it.";
-const image = "/_static/password-protected.png";
-
-export default function PasswordProtectedLinkPage() {
- const router = useRouter();
- const { domain, key } = router.query as { domain: string; key: string };
- const [validating, setValidating] = useState(false);
- const [error, setError] = useState(false);
- const [password, setPassword] = useState("");
-
- return (
- <>
- <Head>
- <title>{title}</title>
- <meta name="description" content={description} />
- <meta property="og:title" content={title} />
- <meta property="og:description" content={description} />
- <meta property="og:image" content={image} />
- <meta name="twitter:card" content="summary_large_image" />
- <meta name="twitter:title" content={title} />
- <meta name="twitter:description" content={description} />
- <meta name="twitter:image" content={image} />
- <link rel="icon" href={`${FAVICON_FOLDER}/favicon-32x32.png`} />
- </Head>
- <main className="flex h-screen w-screen items-center justify-center bg-gray-50">
- <div className="w-full max-w-md overflow-hidden rounded-2xl border border-gray-100 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="https://dub.sh" target="_blank" rel="noreferrer">
- <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">{title}</h3>
- <p className="text-sm text-gray-500">{description}</p>
- </div>
- <form
- onSubmit={async (e) => {
- e.preventDefault();
- setValidating(true);
- fetch(`/api/auth/decrypt-password`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- domain,
- key,
- password,
- }),
- }).then(async (res) => {
- if (res.status === 200) {
- const { url } = await res.json();
- router.push(url);
- } else {
- setValidating(false);
- setError(true);
- }
- });
- }}
- className="flex flex-col space-y-4 bg-gray-50 px-4 py-8 sm:px-16"
- >
- <div>
- <label htmlFor="password" className="block text-xs text-gray-600">
- PASSWORD
- </label>
- <div className="relative mt-1 rounded-md shadow-sm">
- <input
- type="password"
- name="password"
- id="password"
- required
- onChange={(e) => {
- setError(false);
- setPassword(e.target.value);
- }}
- className={`${
- error
- ? "border-red-300 text-red-500 placeholder-red-300 focus:border-red-500 focus:ring-red-500"
- : "border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:ring-gray-500"
- } block w-full rounded-md pr-10 focus:outline-none sm:text-sm`}
- />
- {error && (
- <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
- <AlertCircleFill
- className="h-5 w-5 text-red-500"
- aria-hidden="true"
- />
- </div>
- )}
- </div>
- {error && (
- <p className="mt-2 text-sm text-red-600" id="slug-error">
- Incorrect password
- </p>
- )}
- </div>
-
- <button
- disabled={validating}
- className={`${
- validating
- ? "cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400"
- : "border-black bg-black text-white hover:bg-white hover:text-black"
- } flex h-10 w-full items-center justify-center rounded-md border text-sm transition-all focus:outline-none`}
- >
- {validating ? (
- <LoadingDots color="#808080" />
- ) : (
- <p>Authenticate</p>
- )}
- </button>
- </form>
- </div>
- </main>
- </>
- );
-}
diff --git a/pages/api/auth/decrypt-password.ts b/pages/api/auth/decrypt-password.ts
deleted file mode 100644
index 2b6069cdd8..0000000000
--- a/pages/api/auth/decrypt-password.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import { NextApiRequest, NextApiResponse } from "next";
-import prisma from "#/lib/prisma";
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- if (req.method === "POST") {
- const { domain, key, password } = req.body;
- const link = await prisma.link.findUnique({
- where: { domain_key: { domain, key } },
- select: { url: true, password: true },
- });
- if (!link) {
- return res.status(404).json({ error: "Link not found" });
- }
- const { url, password: realPassword } = link;
- const validPassword = password === realPassword;
- if (validPassword) {
- return res.status(200).json({ url });
- } else {
- return res.status(401).json({ error: "Invalid password" });
- }
- } else {
- res.setHeader("Allow", ["POST"]);
- return res.status(405).end(`Method ${req.method} Not Allowed`);
- }
-}
diff --git a/yarn.lock b/yarn.lock
index 75e075076f..ec55511bbf 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -2404,14 +2404,21 @@
resolved "https://registry.yarnpkg.com/@types/range-parser/-/range-parser-1.2.4.tgz#cd667bcfdd025213aafb7ca5915a932590acdcdc"
integrity sha512-EEhsLsD6UsDM1yFhAvy0Cjr6VwmpMWqFBCb9w07wVugF7w9nfajxLuVmngTIpgS6svCnm6Vaw+MZhoDCKnOfsw==
-"@types/react-dom@*", "@types/[email protected]":
+"@types/react-dom@*":
version "18.0.9"
resolved "https://registry.yarnpkg.com/@types/react-dom/-/react-dom-18.0.9.tgz#ffee5e4bfc2a2f8774b15496474f8e7fe8d0b504"
integrity sha512-qnVvHxASt/H7i+XG1U1xMiY5t+IHcPGUK7TDMDzom08xa7e86eCeKOiLZezwCKVxJn6NEiiy2ekgX8aQssjIKg==
dependencies:
"@types/react" "*"
-"@types/react@*", "@types/[email protected]":
+"@types/react-dom@^18.2.6":
+ version "18.2.6"
+ resolved "https://registry.yarnpkg.com/@types/react-dom/-/react-dom-18.2.6.tgz#ad621fa71a8db29af7c31b41b2ea3d8a6f4144d1"
+ integrity sha512-2et4PDvg6PVCyS7fuTc4gPoksV58bW0RwSxWKcPRcHZf0PRUGq03TKcD/rUHe3azfV6/5/biUBJw+HhCQjaP0A==
+ dependencies:
+ "@types/react" "*"
+
+"@types/react@*":
version "18.0.25"
resolved "https://registry.yarnpkg.com/@types/react/-/react-18.0.25.tgz#8b1dcd7e56fe7315535a4af25435e0bb55c8ae44"
integrity sha512-xD6c0KDT4m7n9uD4ZHi02lzskaiqcBxf4zi+tXZY98a04wvc0hi/TcCPC2FOESZi51Nd7tlUeOJY8RofL799/g==
@@ -2420,6 +2427,15 @@
"@types/scheduler" "*"
csstype "^3.0.2"
+"@types/react@^18.2.14":
+ version "18.2.14"
+ resolved "https://registry.yarnpkg.com/@types/react/-/react-18.2.14.tgz#fa7a6fecf1ce35ca94e74874f70c56ce88f7a127"
+ integrity sha512-A0zjq+QN/O0Kpe30hA1GidzyFjatVvrpIvWLxD+xv67Vt91TWWgco9IvrJBkeyHm1trGaFS/FSGqPlhyeZRm0g==
+ dependencies:
+ "@types/prop-types" "*"
+ "@types/scheduler" "*"
+ csstype "^3.0.2"
+
"@types/resolve@^1.17.1":
version "1.20.2"
resolved "https://registry.yarnpkg.com/@types/resolve/-/resolve-1.20.2.tgz#97d26e00cd4a0423b4af620abecf3e6f442b7975"
@@ -7937,7 +7953,7 @@ react-dom-confetti@^0.2.0:
dependencies:
dom-confetti "0.2.2"
+react-dom@^18.2.0:
version "18.2.0"
resolved "https://registry.yarnpkg.com/react-dom/-/react-dom-18.2.0.tgz#22aaf38708db2674ed9ada224ca4aa708d821e3d"
integrity sha512-6IMTriUmvsjHUjNtEDudZfuDQUoWXVxKHhlEGSk81n4YFS+r/Kl99wXiwlVXtPBtJenozv2P+hxDsw9eA7Xo6g==
@@ -9044,10 +9060,10 @@ [email protected]:
resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.8.4.tgz#c464abca159669597be5f96b8943500b238e60e6"
integrity sha512-QCh+85mCy+h0IGff8r5XWzOVSbBO+KfeYrMQh7NJ58QujwcE22u+NUSmUxqF+un70P9GXKxa2HCNiTTMJknyjQ==
-typescript@^4.9.3:
- version "4.9.3"
- resolved "https://registry.yarnpkg.com/typescript/-/typescript-4.9.3.tgz#3aea307c1746b8c384435d8ac36b8a2e580d85db"
- integrity sha512-CIfGzTelbKNEnLpLdGFgdyKhG23CKdKgQPOBc+OUNrkJ2vr+KSzsSV5kq5iWhEQbok+quxgGzrAtGWCyU7tHnA==
+typescript@^5.1.6:
+ version "5.1.6"
+ resolved "https://registry.yarnpkg.com/typescript/-/typescript-5.1.6.tgz#02f8ac202b6dad2c0dd5e0913745b47a37998274"
+ integrity sha512-zaWCozRZ6DLEWAWFrVDz1H6FVXzUSfTy5FUMWsQlU8Ym5JP9eO4xkTIROFCQvhQf61z6O/G6ugw3SgAnvvm+HA==
uglify-js@^3.15.4, uglify-js@^3.5.1:
version "3.17.4"