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.

Add archived domains feature, secure endpoints

Steven Tey1548d07b4cbe
diff --git a/apps/web/app/api/projects/[slug]/domains/[domain]/route.ts b/apps/web/app/api/projects/[slug]/domains/[domain]/route.ts
index c33af4b952..189c8f2fae 100644
--- a/apps/web/app/api/projects/[slug]/domains/[domain]/route.ts
+++ b/apps/web/app/api/projects/[slug]/domains/[domain]/route.ts
@@ -11,9 +11,16 @@ import {
validateDomain,
} from "@/lib/api/domains";
import { NextResponse } from "next/server";
+import { DUB_PROJECT_ID, isDubDomain } from "@dub/utils";
// GET /api/projects/[slug]/domains/[domain] – get a project's domain
-export const GET = withAuth(async ({ domain }) => {
+export const GET = withAuth(async ({ domain, project }) => {
+ if (isDubDomain(domain) && project.id !== DUB_PROJECT_ID) {
+ return new Response("Domain does not belong to project.", {
+ status: 403,
+ });
+ }
+
const data = await prisma.domain.findUnique({
where: {
slug: domain,
@@ -45,8 +52,15 @@ export const PUT = withAuth(async ({ req, project, domain }) => {
type,
placeholder,
primary,
+ archived,
} = await req.json();
+ if (isDubDomain(domain) && project.id !== DUB_PROJECT_ID) {
+ return new Response("Domain does not belong to project.", {
+ status: 403,
+ });
+ }
+
if (newDomain !== domain) {
const validDomain = await validateDomain(newDomain);
if (validDomain !== true) {
@@ -122,6 +136,7 @@ export const PUT = withAuth(async ({ req, project, domain }) => {
type,
placeholder,
primary,
+ archived,
},
}),
]);
@@ -130,7 +145,13 @@ export const PUT = withAuth(async ({ req, project, domain }) => {
});
// DELETE /api/projects/[slug]/domains/[domain] - delete a project's domain
-export const DELETE = withAuth(async ({ domain }) => {
+export const DELETE = withAuth(async ({ domain, project }) => {
+ if (isDubDomain(domain) && project.id !== DUB_PROJECT_ID) {
+ return new Response("Domain does not belong to project.", {
+ status: 403,
+ });
+ }
+
const response = await deleteDomainAndLinks(domain);
return NextResponse.json(response);
});
diff --git a/apps/web/app/api/projects/[slug]/domains/route.ts b/apps/web/app/api/projects/[slug]/domains/route.ts
index aafef42fc7..c417a57a99 100644
--- a/apps/web/app/api/projects/[slug]/domains/route.ts
+++ b/apps/web/app/api/projects/[slug]/domains/route.ts
@@ -18,6 +18,7 @@ export const GET = withAuth(async ({ project }) => {
slug: true,
verified: true,
primary: true,
+ archived: true,
target: true,
type: true,
placeholder: true,
@@ -29,7 +30,7 @@ export const GET = withAuth(async ({ project }) => {
// POST /api/projects/[slug]/domains - add a domain
export const POST = withAuth(async ({ req, project }) => {
- const { slug: domain, primary, target, type } = await req.json();
+ const { slug: domain, primary, archived, target, type } = await req.json();
if (project.domains && project.domains?.length >= project.domainsLimit) {
return new Response(
@@ -81,6 +82,7 @@ export const POST = withAuth(async ({ req, project }) => {
type,
projectId: project.id,
primary,
+ archived,
},
}),
]);
diff --git a/apps/web/app/api/stats/[endpoint]/route.ts b/apps/web/app/api/stats/[endpoint]/route.ts
index dcfad1e3c2..4d3229a46b 100644
--- a/apps/web/app/api/stats/[endpoint]/route.ts
+++ b/apps/web/app/api/stats/[endpoint]/route.ts
@@ -1,5 +1,6 @@
import { withAuth } from "@/lib/auth";
import { getStats } from "@/lib/stats";
+import { DUB_PROJECT_ID, isDubDomain } from "@dub/utils";
import { NextResponse } from "next/server";
// GET /api/stats/[endpoint] – get stats for a specific endpoint
@@ -8,6 +9,13 @@ export const GET = withAuth(
const { endpoint } = params;
const { domain, key, interval } = searchParams;
+ // TODO: remove this after #545 merges
+ if (isDubDomain(domain) && !key && project.id !== DUB_PROJECT_ID) {
+ return new Response("Domain does not belong to project.", {
+ status: 403,
+ });
+ }
+
const constructedDomain =
domain || project?.domains?.map((d) => d.slug).join(",");
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/client.tsx
index 35d8aec2c6..1841d8aa5f 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/client.tsx
@@ -13,7 +13,7 @@ export default function AnalyticsClient({ children }: { children: ReactNode }) {
if (exceededClicks) {
return <ProjectExceededClicks />;
}
- const { domains, loading: loadingDomains } = useDomains();
+ const { allActiveDomains, loading: loadingDomains } = useDomains();
const searchParams = useSearchParams();
const domain = searchParams?.get("domain");
@@ -21,8 +21,8 @@ export default function AnalyticsClient({ children }: { children: ReactNode }) {
return <LayoutLoader />;
}
if (
- domains?.length === 0 ||
- (domain && !domains?.find((d) => d.slug === domain))
+ allActiveDomains?.length === 0 ||
+ (domain && !allActiveDomains?.find((d) => d.slug === domain))
) {
return <LinkNotFound />;
}
diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/domains/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/domains/page-client.tsx
index bcf5c7b76f..a6cd7ccb27 100644
--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/domains/page-client.tsx
+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/domains/page-client.tsx
@@ -7,6 +7,7 @@ import DomainCardPlaceholder from "@/ui/domains/domain-card-placeholder";
import NoDomainsPlaceholder from "@/ui/domains/no-domains-placeholder";
import { useAddEditDomainModal } from "@/ui/modals/add-edit-domain-modal";
import {
+ Button,
Checkbox,
InfoTooltip,
Label,
@@ -17,13 +18,13 @@ import {
import { DUB_DOMAINS, HOME_DOMAIN } from "@dub/utils";
import { ChevronDown } from "lucide-react";
import { useState } from "react";
-import { mutate } from "swr";
export default function ProjectDomainsClient() {
const { id: projectId } = useProject();
const { AddEditDomainModal, AddEditDomainButton } = useAddEditDomainModal();
- const { domains } = useDomains();
+ const { projectDomains, archivedProjectDomains } = useDomains();
+ const [showArchivedDomains, setShowArchivedDomains] = useState(false);
return (
<>
@@ -52,10 +53,10 @@ export default function ProjectDomainsClient() {
</MaxWidthWrapper>
</div>
<MaxWidthWrapper className="py-10">
- {domains ? (
- domains.length > 0 ? (
+ {projectDomains ? (
+ projectDomains.length > 0 ? (
<ul className="grid grid-cols-1 gap-3">
- {domains.map((domain) => (
+ {projectDomains.map((domain) => (
<li key={domain.slug}>
<DomainCard props={domain} />
</li>
@@ -67,6 +68,23 @@ export default function ProjectDomainsClient() {
) : (
<DomainCardPlaceholder />
)}
+ {archivedProjectDomains && archivedProjectDomains.length > 0 && (
+ <ul className="mt-3 grid grid-cols-1 gap-3">
+ {showArchivedDomains &&
+ archivedProjectDomains?.map((domain) => (
+ <li key={domain.slug}>
+ <DomainCard props={domain} />
+ </li>
+ ))}
+ <Button
+ text={`${showArchivedDomains ? "Hide" : "Show"} ${
+ archivedProjectDomains.length
+ } archived domains`}
+ variant="secondary"
+ onClick={() => setShowArchivedDomains(!showArchivedDomains)}
+ />
+ </ul>
+ )}
</MaxWidthWrapper>
</>
);
diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.ts
index 6804e31ed5..f20d9503e1 100644
--- a/apps/web/lib/api/links.ts
+++ b/apps/web/lib/api/links.ts
@@ -10,7 +10,6 @@ import {
DEFAULT_REDIRECTS,
DUB_DOMAINS,
DUB_PROJECT_ID,
- LEGAL_USER_ID,
SHORT_DOMAIN,
getDomainWithoutWWW,
getParamsFromURL,
@@ -24,7 +23,6 @@ import cloudinary from "cloudinary";
import { isIframeable } from "../middleware/utils";
import { LinkProps, ProjectProps, SimpleLinkProps } from "../types";
import { Session } from "../auth";
-import { exceededLimitError } from "./errors";
export async function getLinksForProject({
projectId,
diff --git a/apps/web/lib/auth/index.ts b/apps/web/lib/auth/index.ts
index ba59bd4c9d..96a9aa7ca9 100644
--- a/apps/web/lib/auth/index.ts
+++ b/apps/web/lib/auth/index.ts
@@ -4,12 +4,7 @@ import { Link as LinkProps } from "@prisma/client";
import { PlanProps, ProjectProps } from "../types";
import { getServerSession } from "next-auth/next";
import { createHash } from "crypto";
-import {
- API_DOMAIN,
- DUB_PROJECT_ID,
- getSearchParams,
- isDubDomain,
-} from "@dub/utils";
+import { API_DOMAIN, getSearchParams, isDubDomain } from "@dub/utils";
import { ratelimit } from "../upstash";
import { exceededLimitError } from "../api/errors";
diff --git a/apps/web/lib/swr/use-domains.ts b/apps/web/lib/swr/use-domains.ts
index fa8ccdfbe6..92a04984c8 100644
--- a/apps/web/lib/swr/use-domains.ts
+++ b/apps/web/lib/swr/use-domains.ts
@@ -1,5 +1,5 @@
import { DomainProps } from "@/lib/types";
-import { DUB_DOMAINS, fetcher } from "@dub/utils";
+import { DUB_DOMAINS, SHORT_DOMAIN, fetcher } from "@dub/utils";
import { useParams } from "next/navigation";
import useSWR from "swr";
import useProject from "./use-project";
@@ -9,13 +9,16 @@ export default function useDomains({ domain }: { domain?: string } = {}) {
slug: string;
};
- const {
- data: projectDomains,
- error,
- mutate,
- } = useSWR<DomainProps[]>(slug && `/api/projects/${slug}/domains`, fetcher, {
- dedupingInterval: 60000,
- });
+ const { data, error, mutate } = useSWR<DomainProps[]>(
+ slug && `/api/projects/${slug}/domains`,
+ fetcher,
+ {
+ dedupingInterval: 60000,
+ },
+ );
+
+ const projectDomains = data?.filter((domain) => !domain.archived);
+ const archivedProjectDomains = data?.filter((domain) => domain.archived);
const { defaultDomains: projectDefaultDomains } = useProject();
@@ -24,21 +27,27 @@ export default function useDomains({ domain }: { domain?: string } = {}) {
DUB_DOMAINS.filter((d) => projectDefaultDomains?.includes(d.slug))) ||
DUB_DOMAINS;
- const allDomains = [...(projectDomains || []), ...defaultDomains];
+ const allActiveDomains = [...(projectDomains || []), ...defaultDomains];
+
+ const primaryDomain =
+ projectDomains?.find((domain) => domain.primary)?.slug ||
+ defaultDomains.find((domain) => domain.primary)?.slug ||
+ SHORT_DOMAIN;
+
+ const verified = domain
+ ? // If a domain is passed, check if it's verified (using `allActiveDomains` cause it could be `dub.sh`)
+ allActiveDomains.find((d) => d.slug === domain)?.verified
+ : // If no domain is passed, check if any of the project domains are verified
+ projectDomains?.some((d) => d.verified);
return {
- domains: projectDomains,
+ projectDomains,
+ archivedProjectDomains,
defaultDomains,
- allDomains,
- primaryDomain:
- projectDomains?.find((domain) => domain.primary)?.slug ||
- defaultDomains.find((domain) => domain.primary)?.slug,
- verified: domain
- ? // If a domain is passed, check if it's verified
- allDomains.find((d) => d.slug === domain)?.verified
- : // If no domain is passed, check if any of the domains are verified
- allDomains.some((d) => d.verified),
- loading: !projectDomains && !error,
+ allActiveDomains,
+ primaryDomain,
+ verified,
+ loading: !data && !error,
mutate,
error,
};
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 15be19d38c..9f83e85c0c 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -98,8 +98,9 @@ export interface DomainProps {
slug: string;
verified: boolean;
primary: boolean;
+ archived: boolean;
target?: string;
- type: "redirect" | "rewrite";
+ type: string;
placeholder?: string;
clicks: number;
}
diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma
index 0a10e39e2f..74b2b8a57e 100644
--- a/apps/web/prisma/schema.prisma
+++ b/apps/web/prisma/schema.prisma
@@ -161,6 +161,7 @@ model Domain {
project Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)
projectId String?
primary Boolean @default(false)
+ archived Boolean @default(false)
links Link[]
clicks Int @default(0)
lastClicked DateTime? // when the link was last clicked
diff --git a/apps/web/ui/domains/no-domains-placeholder.tsx b/apps/web/ui/domains/no-domains-placeholder.tsx
index 4fabae71ab..231f2334a5 100644
--- a/apps/web/ui/domains/no-domains-placeholder.tsx
+++ b/apps/web/ui/domains/no-domains-placeholder.tsx
@@ -8,7 +8,7 @@ export default function NoDomainsPlaceholder({
return (
<div className="flex flex-col items-center justify-center rounded-md border border-gray-200 bg-white py-12">
<h2 className="z-10 text-xl font-semibold text-gray-700">
- You don't have any custom domains yet.
+ You don't have any active custom domains yet.
</h2>
<BlurImage
src="/_static/illustrations/call-waiting.svg"
diff --git a/apps/web/ui/links/link-filters.tsx b/apps/web/ui/links/link-filters.tsx
index 8c6f4f2155..c2df583bb6 100644
--- a/apps/web/ui/links/link-filters.tsx
+++ b/apps/web/ui/links/link-filters.tsx
@@ -178,7 +178,7 @@ const DomainsFilter = () => {
const searchParams = useSearchParams();
const { queryParams } = useRouterStuff();
const { data: domains } = useLinksCount({ groupBy: "domain" });
- const { primaryDomain, defaultDomains } = useDomains();
+ const { primaryDomain } = useDomains();
const [collapsed, setCollapsed] = useState(false);
@@ -186,7 +186,7 @@ const DomainsFilter = () => {
return domains.length === 0
? [
{
- value: primaryDomain || defaultDomains[0].slug || "",
+ value: primaryDomain,
count: 0,
},
]
@@ -194,7 +194,7 @@ const DomainsFilter = () => {
value: domain,
count: _count,
}));
- }, [domains, primaryDomain, defaultDomains]);
+ }, [domains, primaryDomain]);
return (
<fieldset className="overflow-hidden py-6">
diff --git a/apps/web/ui/modals/add-edit-domain-modal/index.tsx b/apps/web/ui/modals/add-edit-domain-modal/index.tsx
index a75aa746ea..ce5c3635c2 100644
--- a/apps/web/ui/modals/add-edit-domain-modal/index.tsx
+++ b/apps/web/ui/modals/add-edit-domain-modal/index.tsx
@@ -46,13 +46,14 @@ function AddEditDomainModal({
slug: "",
verified: false,
primary: false,
+ archived: false,
target: "",
type: "redirect",
clicks: 0,
},
);
- const { slug: domain, primary, target, type, placeholder } = data;
+ const { slug: domain, primary, archived, target, type, placeholder } = data;
const [lockDomain, setLockDomain] = useState(true);
const [saving, setSaving] = useState(false);
@@ -300,6 +301,18 @@ function AddEditDomainModal({
/>
</div>
+ <div className="flex items-center justify-between bg-gray-50">
+ <div className="flex items-center space-x-2">
+ <h2 className="text-sm font-medium text-gray-900">Archived</h2>
+ <InfoTooltip content="Archived domains will still work, but they won't show up in the link creation modal." />
+ </div>
+ <Switch
+ fn={() => setData((prev) => ({ ...prev, archived: !archived }))}
+ checked={archived}
+ disabled={props?.archived}
+ />
+ </div>
+
<div>
<label
htmlFor="placeholder"
diff --git a/apps/web/ui/modals/add-edit-link-modal/index.tsx b/apps/web/ui/modals/add-edit-link-modal/index.tsx
index 0372bd283f..82abb4304a 100644
--- a/apps/web/ui/modals/add-edit-link-modal/index.tsx
+++ b/apps/web/ui/modals/add-edit-link-modal/index.tsx
@@ -18,6 +18,7 @@ import {
cn,
deepEqual,
getApexDomain,
+ getDomainWithoutWWW,
getUrlWithoutUTMParams,
isValidUrl,
linkConstructor,
@@ -74,16 +75,17 @@ function AddEditLinkModal({
const [generatingKey, setGeneratingKey] = useState(false);
const [saving, setSaving] = useState(false);
- const { allDomains: domains, primaryDomain } = useDomains();
+ const {
+ allActiveDomains: domains,
+ primaryDomain,
+ defaultDomains,
+ } = useDomains();
const [data, setData] = useState<LinkProps>(
props ||
duplicateProps || {
...(DEFAULT_LINK_PROPS as LinkProps),
- domain:
- primaryDomain ||
- (domains && domains.length > 0 && domains[0].slug) ||
- "",
+ domain: primaryDomain,
key: "",
url: "",
},
@@ -129,13 +131,25 @@ function AddEditLinkModal({
}, [domain, slug]);
useEffect(() => {
- // generate random key when someone pastes a URL and there's no key
- if (showAddEditLinkModal && !key && url.length > 0) {
- generateRandomKey();
+ // when someone pastes a URL
+ if (showAddEditLinkModal && url.length > 0) {
+ // if it's a new link and there are matching default domains, set it as the domain
+ if (!props && defaultDomains) {
+ const urlDomain = getDomainWithoutWWW(url) || "";
+ const defaultDomain = defaultDomains.find(({ allowedHostnames }) =>
+ allowedHostnames.includes(urlDomain),
+ );
+ if (defaultDomain) {
+ setData((prev) => ({ ...prev, domain: defaultDomain.slug }));
+ }
+ }
+
+ // if there's no key, generate a random key
+ if (!key) {
+ generateRandomKey();
+ }
}
- // here, we're intentionally leaving out `key` from the dependency array
- // because we don't want to generate a new key if the user is editing the key
- }, [showAddEditLinkModal, url, generateRandomKey]);
+ }, [showAddEditLinkModal, url]);
const [generatingMetatags, setGeneratingMetatags] = useState(
props ? true : false,
diff --git a/apps/web/ui/stats/toggle.tsx b/apps/web/ui/stats/toggle.tsx
index 3338a1d95a..b3e22b77a5 100644
--- a/apps/web/ui/stats/toggle.tsx
+++ b/apps/web/ui/stats/toggle.tsx
@@ -3,7 +3,6 @@ import useProject from "@/lib/swr/use-project";
import {
Badge,
Copy,
- ExpandingArrow,
IconMenu,
Popover,
Switch,
@@ -22,21 +21,11 @@ import {
getApexDomain,
linkConstructor,
} from "@dub/utils";
-import {
- Calendar,
- ChevronDown,
- Filter,
- Globe,
- Lock,
- Share2,
- X,
-} from "lucide-react";
+import { Calendar, ChevronDown, Globe, Lock, Share2, X } from "lucide-react";
import Link from "next/link";
import { useParams, useSearchParams } from "next/navigation";
-import punycode from "punycode/";
import { useContext, useMemo, useState } from "react";
import { StatsContext } from ".";
-import { ModalContext } from "../modals/provider";
import useSWR, { mutate } from "swr";
import { toast } from "sonner";
import { BlurImage } from "../shared/blur-image";
@@ -46,7 +35,6 @@ import { DomainProps } from "@/lib/types";
export default function Toggle() {
const { slug } = useParams() as { slug?: string };
const { queryParams } = useRouterStuff();
- const { setShowAddProjectModal } = useContext(ModalContext);
const { basePath, domain, key, interval, modal } = useContext(StatsContext);
@@ -58,7 +46,7 @@ export default function Toggle() {
const scrolled = useScroll(80);
const { name, plan, logo } = useProject();
- const { domains, primaryDomain } = useDomains();
+ const { projectDomains, primaryDomain } = useDomains();
const isPublicStatsPage = basePath.startsWith("/stats");
@@ -82,13 +70,13 @@ export default function Toggle() {
<h2 className="text-lg font-semibold text-gray-800">
{primaryDomain}
</h2>
- {domains && domains?.length > 1 && (
+ {projectDomains && projectDomains.length > 0 && (
<Tooltip
- content={<DomainsFilterTooltip domains={domains} />}
+ content={<DomainsFilterTooltip domains={projectDomains} />}
side="bottom"
>
<div className="cursor-pointer">
- <Badge variant="gray">+{domains.length - 1}</Badge>
+ <Badge variant="gray">+{projectDomains.length - 1}</Badge>
</div>
</Tooltip>
)}
diff --git a/packages/utils/src/constants/index.ts b/packages/utils/src/constants/index.ts
index 2eb1edca84..a98d20a53c 100644
--- a/packages/utils/src/constants/index.ts
+++ b/packages/utils/src/constants/index.ts
@@ -122,6 +122,7 @@ export const DUB_DOMAINS = [
slug: SHORT_DOMAIN,
verified: true,
primary: true,
+ archived: false,
target: `https://${process.env.NEXT_PUBLIC_APP_DOMAIN}`,
type: "redirect",
placeholder: "https://dub.co/help/article/what-is-dub",
@@ -134,6 +135,7 @@ export const DUB_DOMAINS = [
slug: "chatg.pt",
verified: true,
primary: false,
+ archived: false,
target: "https://dub.co/tools/chatgpt-link-shortener",
type: "redirect",
placeholder: "https://chat.openai.com/g/g-UGjKKONEe-domainsgpt",
@@ -144,6 +146,7 @@ export const DUB_DOMAINS = [
slug: "amzn.id",
verified: true,
primary: false,
+ archived: false,
target: "https://dub.co/tools/amazon-link-shortener",
type: "redirect",
placeholder: "https://www.amazon.com/dp/B0BW4SWNC8",
@@ -154,6 +157,7 @@ export const DUB_DOMAINS = [
slug: "spti.fi",
verified: true,
primary: false,
+ archived: false,
target: "https://dub.co/tools/spotify-link-shortener",
type: "redirect",
placeholder: "https://open.spotify.com/album/1SCyi9a5pOasikidToUY5y",