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.

Consolidate /links endpoint, allow "/" in short links

Steven Teye98e0972baab
diff --git a/app/ui/modals/add-edit-link-modal/index.tsx b/app/ui/modals/add-edit-link-modal/index.tsx
index 726c00d6c8..6ce1968baa 100644
--- a/app/ui/modals/add-edit-link-modal/index.tsx
+++ b/app/ui/modals/add-edit-link-modal/index.tsx
@@ -64,8 +64,8 @@ function AddEditLinkModal({
const router = useRouter();
const pathname = usePathname();
- const [keyExistsError, setKeyExistsError] = useState(false);
- const [urlError, setUrlError] = useState(false);
+ const [keyError, setKeyError] = useState<string | null>(null);
+ const [urlError, setUrlError] = useState<string | null>(null);
const [generatingKey, setGeneratingKey] = useState(false);
const [saving, setSaving] = useState(false);
@@ -97,13 +97,13 @@ function AddEditLinkModal({
debouncedKey !== props?.key
) {
fetch(
- slug
- ? `/api/projects/${slug}/links/${debouncedKey}/exists?domain=${domain}`
- : `/api/links/${debouncedKey}/exists`,
+ `/api/links/${encodeURIComponent(debouncedKey)}/exists${
+ slug ? `?slug=${slug}&domain=${domain}` : ""
+ }`,
).then(async (res) => {
if (res.status === 200) {
const exists = await res.json();
- setKeyExistsError(exists);
+ setKeyError(exists ? "Key already exists" : null);
}
});
}
@@ -112,9 +112,7 @@ function AddEditLinkModal({
const generateRandomKey = useCallback(async () => {
setGeneratingKey(true);
const res = await fetch(
- slug
- ? `/api/projects/${slug}/links/random?domain=${domain}`
- : `/api/links/random`,
+ `/api/links/random${slug ? `?slug=${slug}&domain=${domain}` : ""}`,
);
const key = await res.json();
setData((prev) => ({ ...prev, key }));
@@ -193,16 +191,14 @@ function AddEditLinkModal({
if (props?.key) {
return {
method: "PUT",
- url: slug
- ? `/api/projects/${slug}/links/${props.key}?domain=${domain}`
- : `/api/links/${props.key}`,
+ url: `/api/links/${props.key}${
+ slug ? `?slug=${slug}&domain=${domain}` : ""
+ }`,
};
} else {
return {
method: "POST",
- url: slug
- ? `/api/projects/${slug}/links?domain=${domain}`
- : `/api/links`,
+ url: `/api/links${slug ? `?slug=${slug}&domain=${domain}` : ""}`,
};
}
}, [props]);
@@ -230,7 +226,7 @@ function AddEditLinkModal({
if (
!showAddEditLinkModal ||
saving ||
- keyExistsError ||
+ keyError ||
urlError ||
(props &&
Object.entries(props).every(([key, value]) => {
@@ -249,7 +245,7 @@ function AddEditLinkModal({
} else {
return false;
}
- }, [showAddEditLinkModal, saving, keyExistsError, urlError, props, data]);
+ }, [showAddEditLinkModal, saving, keyError, urlError, props, data]);
const randomIdx = Math.floor(Math.random() * 100);
@@ -304,7 +300,7 @@ function AddEditLinkModal({
"Content-Type": "application/json",
},
body: JSON.stringify(data),
- }).then((res) => {
+ }).then(async (res) => {
setSaving(false);
if (res.status === 200) {
// track link creation event
@@ -313,22 +309,14 @@ function AddEditLinkModal({
type: slug ? "Custom Domain" : "Default Domain",
});
mutate(
- slug
- ? `/api/projects/${slug}/links${
- searchParams ? `?${searchParams.toString()}` : ""
- }`
- : `/api/links${
- searchParams ? `?${searchParams.toString()}` : ""
- }`,
+ `/api/links${
+ searchParams ? `?${searchParams.toString()}` : ""
+ }`,
);
mutate(
(key) =>
typeof key === "string" &&
- key.startsWith(
- slug
- ? `/api/projects/${slug}/links/count`
- : `/api/links/count`,
- ),
+ key.startsWith(`/api/links/count`),
undefined,
{ revalidate: true },
);
@@ -352,12 +340,18 @@ function AddEditLinkModal({
}
setShowAddEditLinkModal(false);
}
- } else if (res.status === 403) {
- setKeyExistsError(true);
- } else if (res.status === 400) {
- setUrlError(true);
} else {
- alert("Something went wrong");
+ const error = await res.text();
+ if (error) {
+ toast.error(error);
+ if (error.toLowerCase().includes("key")) {
+ setKeyError(error);
+ } else if (error.toLowerCase().includes("url")) {
+ setUrlError(error);
+ }
+ } else {
+ toast.error(res.statusText);
+ }
}
});
}}
@@ -387,7 +381,7 @@ function AddEditLinkModal({
placeholder="https://github.com/steven-tey/dub"
value={url}
onChange={(e) => {
- setUrlError(false);
+ setUrlError(null);
setData({ ...data, url: e.target.value });
}}
className={`${
@@ -473,21 +467,21 @@ function AddEditLinkModal({
required
pattern="[\p{Letter}\p{Mark}\d-]+" // Unicode regex to match characters from all languages and numbers (and omit all symbols except for dashes)
className={`${
- keyExistsError
+ keyError
? "border-red-300 text-red-900 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-r-md pr-10 text-sm focus:outline-none`}
placeholder="github"
value={key}
onChange={(e) => {
- setKeyExistsError(false);
+ setKeyError(null);
setData({ ...data, key: e.target.value });
}}
aria-invalid="true"
aria-describedby="key-error"
/>
)}
- {keyExistsError && (
+ {keyError && (
<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"
@@ -496,7 +490,7 @@ function AddEditLinkModal({
</div>
)}
</div>
- {keyExistsError && (
+ {keyError && (
<p className="mt-2 text-sm text-red-600" id="key-error">
Short link is already in use.
</p>
diff --git a/app/ui/stats/index.tsx b/app/ui/stats/index.tsx
index 998ca4ace7..9f7c9e03f6 100644
--- a/app/ui/stats/index.tsx
+++ b/app/ui/stats/index.tsx
@@ -72,6 +72,7 @@ export default function Stats({
const queryString =
interval || domainSlug
? `?${new URLSearchParams({
+ ...(slug && { slug }),
...(interval && { interval }),
...(domainSlug && { domain: domainSlug }),
}).toString()}`
@@ -81,25 +82,25 @@ export default function Stats({
// Project link page, e.g. app.dub.sh/dub/dub.sh/github
if (slug && domainSlug && key) {
return {
- basePath: `/${slug}/${domainSlug}/${key}`,
+ basePath: `/${slug}/${domainSlug}/${encodeURIComponent(key)}`,
domain: domainSlug,
- endpoint: `/api/projects/${slug}/links/${key}/stats`,
+ endpoint: `/api/links/${encodeURIComponent(key)}/stats`,
};
// Generic Dub.sh link page, e.g. app.dub.sh/links/steven
} else if (key && pathname?.startsWith("/links")) {
return {
- basePath: `/links/${key}`,
+ basePath: `/links/${encodeURIComponent(key)}`,
domain: "dub.sh",
- endpoint: `/api/links/${key}/stats`,
+ endpoint: `/api/links/${encodeURIComponent(key)}/stats`,
};
}
// Public stats page, e.g. dub.sh/stats/github, stey.me/stats/weathergpt
return {
- basePath: `/stats/${key}`,
+ basePath: `/stats/${encodeURIComponent(key)}`,
domain: staticDomain,
- endpoint: `/api/edge/links/${key}/stats`,
+ endpoint: `/api/edge/links/${encodeURIComponent(key)}/stats`,
};
}, [slug, key, pathname]);
diff --git a/components/app/links/link-card.tsx b/components/app/links/link-card.tsx
index 68b20f5ed3..5e8f2b736c 100644
--- a/components/app/links/link-card.tsx
+++ b/components/app/links/link-card.tsx
@@ -50,9 +50,9 @@ export default function LinkCard({ props }: { props: LinkProps }) {
const { data: clicks } = useSWR<number>(
isVisible &&
- (slug
- ? `/api/projects/${slug}/links/${key}/stats/clicks?domain=${domain}`
- : `/api/links/${key}/stats/clicks`),
+ `/api/links/${key}/stats/clicks${
+ slug ? `?slug=${slug}&domain=${domain}` : ""
+ }`,
fetcher,
{
fallbackData: props.clicks,
@@ -111,8 +111,15 @@ export default function LinkCard({ props }: { props: LinkProps }) {
const shortcuts = ["e", "d", "a", "x"];
const onKeyDown = (e: any) => {
- // only run shortcut logic if link is selected or the 3 dots menu is open
- if ((selected || openPopover) && shortcuts.includes(e.key)) {
+ // only run shortcut logic if:
+ // - usage is not exceeded
+ // - link is selected or the 3 dots menu is open
+ // - the key pressed is one of the shortcuts
+ if (
+ !exceededUsage &&
+ (selected || openPopover) &&
+ shortcuts.includes(e.key)
+ ) {
setSelected(false);
switch (e.key) {
case "e":
@@ -214,9 +221,9 @@ export default function LinkCard({ props }: { props: LinkProps }) {
onClick={(e) => {
e.stopPropagation();
}}
- href={`/${slug ? `${slug}/${domain}` : "links"}/${encodeURI(
- key,
- )}`}
+ href={`/${
+ slug ? `${slug}/${domain}` : "links"
+ }/${encodeURIComponent(key)}`}
className="flex items-center space-x-1 rounded-md bg-gray-100 px-2 py-0.5 transition-all duration-75 hover:scale-105 active:scale-100"
>
<Chart className="h-4 w-4" />
diff --git a/components/app/modals/add-edit-link-modal/index.tsx b/components/app/modals/add-edit-link-modal/index.tsx
index 7ba6e1e637..7104af0adc 100644
--- a/components/app/modals/add-edit-link-modal/index.tsx
+++ b/components/app/modals/add-edit-link-modal/index.tsx
@@ -56,8 +56,8 @@ function AddEditLinkModal({
const router = useRouter();
const { slug } = router.query as { slug: string };
- const [keyExistsError, setKeyExistsError] = useState(false);
- const [urlError, setUrlError] = useState(false);
+ const [keyError, setKeyError] = useState<string | null>(null);
+ const [urlError, setUrlError] = useState<string | null>(null);
const [generatingKey, setGeneratingKey] = useState(false);
const [saving, setSaving] = useState(false);
@@ -86,16 +86,17 @@ function AddEditLinkModal({
if (
showAddEditLinkModal &&
debouncedKey.length > 0 &&
- debouncedKey !== props?.key
+ debouncedKey !== props?.key &&
+ !keyError
) {
fetch(
- slug
- ? `/api/projects/${slug}/links/${debouncedKey}/exists?domain=${domain}`
- : `/api/links/${debouncedKey}/exists`,
+ `/api/links/${encodeURIComponent(debouncedKey)}/exists${
+ slug ? `?slug=${slug}&domain=${domain}` : ""
+ }`,
).then(async (res) => {
if (res.status === 200) {
const exists = await res.json();
- setKeyExistsError(exists);
+ setKeyError(exists ? "Key already exists" : null);
}
});
}
@@ -104,9 +105,7 @@ function AddEditLinkModal({
const generateRandomKey = useCallback(async () => {
setGeneratingKey(true);
const res = await fetch(
- slug
- ? `/api/projects/${slug}/links/random?domain=${domain}`
- : `/api/links/random`,
+ `/api/links/random${slug ? `?slug=${slug}&domain=${domain}` : ""}`,
);
const key = await res.json();
setData((prev) => ({ ...prev, key }));
@@ -185,16 +184,14 @@ function AddEditLinkModal({
if (props?.key) {
return {
method: "PUT",
- url: slug
- ? `/api/projects/${slug}/links/${props.key}?domain=${domain}`
- : `/api/links/${props.key}`,
+ url: `/api/links/${props.key}${
+ slug ? `?slug=${slug}&domain=${domain}` : ""
+ }`,
};
} else {
return {
method: "POST",
- url: slug
- ? `/api/projects/${slug}/links?domain=${domain}`
- : `/api/links`,
+ url: `/api/links${slug ? `?slug=${slug}&domain=${domain}` : ""}`,
};
}
}, [props]);
@@ -222,7 +219,7 @@ function AddEditLinkModal({
if (
!showAddEditLinkModal ||
saving ||
- keyExistsError ||
+ keyError ||
urlError ||
(props &&
Object.entries(props).every(([key, value]) => {
@@ -241,7 +238,7 @@ function AddEditLinkModal({
} else {
return false;
}
- }, [showAddEditLinkModal, saving, keyExistsError, urlError, props, data]);
+ }, [showAddEditLinkModal, saving, keyError, urlError, props, data]);
const randomIdx = Math.floor(Math.random() * 100);
@@ -296,7 +293,7 @@ function AddEditLinkModal({
"Content-Type": "application/json",
},
body: JSON.stringify(data),
- }).then((res) => {
+ }).then(async (res) => {
setSaving(false);
if (res.status === 200) {
// track link creation event
@@ -304,18 +301,12 @@ function AddEditLinkModal({
va.track("Created Link", {
type: slug ? "Custom Domain" : "Default Domain",
});
- mutate(
- slug
- ? `/api/projects/${slug}/links${getQueryString(router)}`
- : `/api/links${getQueryString(router)}`,
- );
+ mutate(`/api/links${getQueryString(router)}`);
mutate(
(key) =>
typeof key === "string" &&
key.startsWith(
- slug
- ? `/api/projects/${slug}/links/count`
- : `/api/links/count`,
+ `/api/links/count${slug ? `?slug=${slug}` : ""}`,
),
undefined,
{ revalidate: true },
@@ -338,15 +329,23 @@ function AddEditLinkModal({
.then(() => {
toast.success("Copied shortlink to clipboard!");
});
+ } else {
+ toast.success("Successfully updated shortlink!");
}
setShowAddEditLinkModal(false);
}
- } else if (res.status === 403) {
- setKeyExistsError(true);
- } else if (res.status === 400) {
- setUrlError(true);
} else {
- alert("Something went wrong");
+ const error = await res.text();
+ if (error) {
+ toast.error(error);
+ if (error.toLowerCase().includes("key")) {
+ setKeyError(error);
+ } else if (error.toLowerCase().includes("url")) {
+ setUrlError(error);
+ }
+ } else {
+ toast.error(res.statusText);
+ }
}
});
}}
@@ -376,7 +375,7 @@ function AddEditLinkModal({
placeholder="https://github.com/steven-tey/dub"
value={url}
onChange={(e) => {
- setUrlError(false);
+ setUrlError(null);
setData({ ...data, url: e.target.value });
}}
className={`${
@@ -460,23 +459,24 @@ function AddEditLinkModal({
name="key"
id={`key-${randomIdx}`}
required
- pattern="[\p{Letter}\p{Mark}\d-]+" // Unicode regex to match characters from all languages and numbers (and omit all symbols except for dashes)
+ // Unicode regex to match characters from all languages and numbers (and omit all symbols except for dashes and slashes)
+ pattern="[\p{Letter}\p{Mark}\d/-]+"
className={`${
- keyExistsError
+ keyError
? "border-red-300 text-red-900 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-r-md pr-10 text-sm focus:outline-none`}
placeholder="github"
value={key}
onChange={(e) => {
- setKeyExistsError(false);
+ setKeyError(null);
setData({ ...data, key: e.target.value });
}}
aria-invalid="true"
aria-describedby="key-error"
/>
)}
- {keyExistsError && (
+ {keyError && (
<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"
@@ -485,9 +485,9 @@ function AddEditLinkModal({
</div>
)}
</div>
- {keyExistsError && (
+ {keyError && (
<p className="mt-2 text-sm text-red-600" id="key-error">
- Short link is already in use.
+ {keyError}
</p>
)}
</div>
@@ -562,11 +562,13 @@ function AddEditLinkButton({
const target = e.target as HTMLElement;
const existingModalBackdrop = document.getElementById("modal-backdrop");
// only open modal with keyboard shortcut if:
+ // - project has not exceeded usage limit
// - c is pressed
// - user is not pressing cmd/ctrl + c
// - user is not typing in an input or textarea
// - there is no existing modal backdrop (i.e. no other modal is open)
if (
+ !exceededUsage &&
e.key === "c" &&
!e.metaKey &&
!e.ctrlKey &&
diff --git a/components/app/modals/add-project-modal.tsx b/components/app/modals/add-project-modal.tsx
index 3070df49a0..3ea1cc3660 100644
--- a/components/app/modals/add-project-modal.tsx
+++ b/components/app/modals/add-project-modal.tsx
@@ -46,33 +46,31 @@ function AddProjectModalHelper({
const [debouncedSlug] = useDebounce(slug, 500);
useEffect(() => {
- if (debouncedSlug.length > 0) {
+ if (debouncedSlug.length > 0 && !slugError) {
fetch(`/api/projects/${slug}/exists`).then(async (res) => {
if (res.status === 200) {
const exists = await res.json();
setSlugError(exists === 1 ? "Slug is already in use." : null);
}
});
- } else {
- setSlugError(null);
}
}, [debouncedSlug, slugError]);
const [debouncedDomain] = useDebounce(domain, 500);
useEffect(() => {
- if (debouncedDomain.length > 0) {
+ if (debouncedDomain.length > 0 && !domainError) {
fetch(`/api/domains/${debouncedDomain}/exists`).then(async (res) => {
if (res.status === 200) {
const exists = await res.json();
setDomainError(exists === 1 ? "Domain is already in use." : null);
}
});
- } else {
- setDomainError(null);
}
}, [debouncedDomain, domainError]);
useEffect(() => {
+ setSlugError(null);
+ setDomainError(null);
setData((prev) => ({
...prev,
slug: name
@@ -125,12 +123,14 @@ function AddProjectModalHelper({
} = await res.json();
if (slugErrorResponse) {
setSlugError(slugErrorResponse);
+ toast.error(slugErrorResponse);
}
if (domainErrorResponse) {
setDomainError(domainErrorResponse);
+ toast.error(domainErrorResponse);
}
} else {
- setDomainError("Something went wrong.");
+ toast.error(res.statusText);
}
setSaving(false);
});
diff --git a/components/app/modals/archive-link-modal.tsx b/components/app/modals/archive-link-modal.tsx
index 856f8adba9..6576b479f8 100644
--- a/components/app/modals/archive-link-modal.tsx
+++ b/components/app/modals/archive-link-modal.tsx
@@ -13,6 +13,7 @@ import Modal from "@/components/shared/modal";
import { LinkProps } from "@/lib/types";
import { getApexDomain, getQueryString, linkConstructor } from "@/lib/utils";
import { GOOGLE_FAVICON_URL } from "@/lib/constants";
+import { toast } from "sonner";
function ArchiveLinkModal({
showArchiveLinkModal,
@@ -70,9 +71,9 @@ function ArchiveLinkModal({
e.preventDefault();
setArchiving(true);
fetch(
- domain
- ? `/api/projects/${slug}/links/${props.key}/archive?domain=${domain}`
- : `/api/links/${props.key}/archive`,
+ `/api/links/${props.key}/archive${
+ slug ? `?slug=${slug}&domain=${domain}` : ""
+ }}`,
{
method: archived ? "POST" : "DELETE",
headers: {
@@ -82,12 +83,10 @@ function ArchiveLinkModal({
).then(async (res) => {
setArchiving(false);
if (res.status === 200) {
- mutate(
- domain
- ? `/api/projects/${slug}/links${getQueryString(router)}`
- : `/api/links${getQueryString(router)}`,
- );
+ mutate(`/api/links${getQueryString(router)}`);
setShowArchiveLinkModal(false);
+ } else {
+ toast.error(res.statusText);
}
});
}}
diff --git a/components/app/modals/delete-link-modal.tsx b/components/app/modals/delete-link-modal.tsx
index 16d32a920f..8b75efa951 100644
--- a/components/app/modals/delete-link-modal.tsx
+++ b/components/app/modals/delete-link-modal.tsx
@@ -65,9 +65,9 @@ function DeleteLinkModal({
e.preventDefault();
setDeleting(true);
fetch(
- slug
- ? `/api/projects/${slug}/links/${props.key}?domain=${domain}`
- : `/api/links/${props.key}`,
+ `/api/links/${encodeURIComponent(props.key)}${
+ slug ? `?slug=${slug}&domain=${domain}` : ""
+ }`,
{
method: "DELETE",
headers: {
@@ -77,24 +77,18 @@ function DeleteLinkModal({
).then(async (res) => {
setDeleting(false);
if (res.status === 200) {
- mutate(
- slug
- ? `/api/projects/${slug}/links${getQueryString(router)}`
- : `/api/links${getQueryString(router)}`,
- );
+ mutate(`/api/links${getQueryString(router)}`);
mutate(
(key) =>
typeof key === "string" &&
key.startsWith(
- slug
- ? `/api/projects/${slug}/links/count`
- : `/api/links/count`,
+ `/api/links/count${slug ? `?slug=${slug}` : ""}`,
),
undefined,
{ revalidate: true },
);
setShowDeleteLinkModal(false);
- toast.success("Deleted shortlink!");
+ toast.success("Successfully deleted shortlink!");
} else {
const { error } = await res.json();
toast.error(error);
diff --git a/components/app/projects/project-card.tsx b/components/app/projects/project-card.tsx
index 7163617474..84d28c7675 100644
--- a/components/app/projects/project-card.tsx
+++ b/components/app/projects/project-card.tsx
@@ -19,7 +19,7 @@ export default function ProjectCard({
primaryDomain,
}: ProjectWithDomainProps) {
const { data: count } = useSWR<number>(
- `/api/projects/${slug}/links/count`,
+ `/api/links/count?slug=${slug}`,
fetcher,
);
return (
diff --git a/components/layout/app/nav-tabs.tsx b/components/layout/app/nav-tabs.tsx
index 35c64529b3..4e620b9eb1 100644
--- a/components/layout/app/nav-tabs.tsx
+++ b/components/layout/app/nav-tabs.tsx
@@ -23,7 +23,6 @@ const TabsHelper = (router: NextRouter): { name: string; href: string }[] => {
return [
{ name: "Projects", href: `/` },
{ name: "Dub.sh Links", href: `/links` },
- { name: "Settings", href: `/settings` },
];
};
diff --git a/lib/auth.ts b/lib/auth.ts
index 60ca683504..62195ef056 100644
--- a/lib/auth.ts
+++ b/lib/auth.ts
@@ -1,8 +1,9 @@
import { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth/next";
import prisma from "@/lib/prisma";
-import { PlanProps, ProjectProps, UserProps } from "@/lib/types";
+import { LinkProps, PlanProps, ProjectProps, UserProps } from "@/lib/types";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { isBlacklistedKey } from "./utils";
export interface Session {
user: {
@@ -41,13 +42,12 @@ const withProjectAuth =
) =>
async (req: NextApiRequest, res: NextApiResponse) => {
const session = await getSession(req, res);
- if (!session?.user.id) return res.status(401).end("Unauthorized");
+ if (!session?.user.id)
+ return res.status(401).end("Unauthorized: Login required.");
const { slug } = req.query;
if (!slug || typeof slug !== "string") {
- return res
- .status(400)
- .json({ error: "Missing or misconfigured project slug" });
+ return res.status(400).end("Missing or misconfigured project slug.");
}
const project = (await prisma.project.findUnique({
@@ -90,16 +90,16 @@ const withProjectAuth =
},
});
if (!pendingInvites) {
- return res.status(404).json({ error: "Project not found" });
+ return res.status(404).end("Project not found.");
} else if (pendingInvites.expires < new Date()) {
- return res.status(410).json({ error: "Project invite expired" });
+ return res.status(410).end("Project invite expired.");
} else {
- return res.status(409).json({ error: "Project invite pending" });
+ return res.status(409).end("Project invite pending.");
}
}
} else {
// project doesn't exist
- return res.status(404).json({ error: "Project not found" });
+ return res.status(404).end("Project not found.");
}
// if the action doesn't need to be gated for GET requests, return handler now
@@ -139,7 +139,8 @@ const withUserAuth =
) =>
async (req: NextApiRequest, res: NextApiResponse) => {
const session = await getSession(req, res);
- if (!session?.user.id) return res.status(401).end("Unauthorized");
+ if (!session?.user.id)
+ return res.status(401).end("Unauthorized: Login required.");
if (req.method === "GET") return handler(req, res, session);
@@ -162,3 +163,136 @@ const withUserAuth =
};
export { withUserAuth };
+
+interface WithLinksAuthNextApiHandler {
+ (
+ req: NextApiRequest,
+ res: NextApiResponse,
+ session: Session,
+ project?: ProjectProps,
+ domain?: string,
+ link?: LinkProps,
+ ): any;
+}
+
+const withLinksAuth =
+ (
+ handler: WithLinksAuthNextApiHandler,
+ {
+ needNotExceededUsage, // if the action needs the user to not have exceeded their usage
+ excludeGet, // if the action doesn't need to be gated for GET requests
+ }: {
+ needNotExceededUsage?: boolean;
+ excludeGet?: boolean;
+ } = {},
+ ) =>
+ async (req: NextApiRequest, res: NextApiResponse) => {
+ // if user is not logged in
+ const session = await getSession(req, res);
+ if (!session?.user.id)
+ return res.status(401).end("Unauthorized: Login required.");
+
+ const { slug, domain } = req.query as {
+ slug?: string;
+ domain?: string;
+ };
+
+ // if slug is misconfgured
+ if (slug && typeof slug !== "string") {
+ return res.status(400).end("Missing or misconfigured project slug.");
+ }
+
+ // if there is no slug, it's the default dub.sh link
+ if (!slug) {
+ // if domain is defined, check if it's dub.sh
+ if (domain && domain !== "dub.sh") {
+ return res.status(403).end("Unauthorized: Invalid domain.");
+ }
+
+ let link: LinkProps | undefined;
+ // if key is defined, check if the current user is the owner of the link
+ const { key } = req.query;
+ if (key) {
+ if (typeof key !== "string") {
+ return res.status(400).end("Missing or misconfigured link key.");
+ } else {
+ link =
+ (await prisma.link.findUnique({
+ where: {
+ domain_key: {
+ domain: "dub.sh",
+ key,
+ },
+ },
+ })) || undefined;
+ if (!link) {
+ return res.status(404).end("Link not found.");
+ } else if (link.userId !== session.user.id) {
+ return res.status(403).end("Unauthorized: Not link owner.");
+ }
+ }
+ }
+
+ return handler(req, res, session, undefined, "dub.sh", link);
+
+ // if project slug is defined, that means it's a custom project on Dub
+ } else {
+ const project = (await prisma.project.findUnique({
+ where: {
+ slug,
+ },
+ include: {
+ users: {
+ where: {
+ userId: session.user.id,
+ },
+ select: {
+ role: true,
+ },
+ },
+ },
+ })) as ProjectProps;
+
+ // if project doesn't exist
+ if (!project) {
+ return res.status(404).end("Project not found.");
+
+ // if project exists but user is not part of it
+ } else if (project.users && project.users.length === 0) {
+ // TODO: check if user has pending invite
+ return res.status(401).end("Unauthorized: Not part of project.");
+
+ // project exists and user is part of it
+ } else {
+ // if the action requires the project to be within usage limits,
+ // and the action is not a GET request with excludeGet set to true,
+ // check if the project is within usage limits
+ if (
+ needNotExceededUsage &&
+ !(req.method === "GET" && excludeGet) &&
+ project.usage > project.usageLimit
+ ) {
+ return res.status(403).end("Unauthorized: Usage limits exceeded.");
+ }
+
+ // if domain is defined, check if it's owned by the project
+ if (domain) {
+ const domainProjectId = await prisma.domain.findUnique({
+ where: {
+ slug: domain,
+ },
+ select: {
+ projectId: true,
+ },
+ });
+ if (domainProjectId?.projectId !== project.id) {
+ return res.status(403).end("Unauthorized: Invalid domain.");
+ }
+ }
+ }
+
+ return handler(req, res, session, project, domain);
+ }
+ };
+
+export { withLinksAuth };
diff --git a/lib/hooks/use-endpoint.ts b/lib/hooks/use-endpoint.ts
index c6bc163021..f79bdc302f 100644
--- a/lib/hooks/use-endpoint.ts
+++ b/lib/hooks/use-endpoint.ts
@@ -18,6 +18,7 @@ export default function useEndpoint(staticDomain?: string) {
const queryString =
interval || domainSlug
? `?${new URLSearchParams({
+ ...(slug && { slug }),
...(interval && { interval }),
...(domainSlug && { domain: domainSlug }),
}).toString()}`
@@ -27,25 +28,25 @@ export default function useEndpoint(staticDomain?: string) {
// Project link page, e.g. app.dub.sh/dub/dub.sh/github
if (slug && domainSlug && key) {
return {
- basePath: `/${slug}/${domainSlug}/${key}`,
+ basePath: `/${slug}/${domainSlug}/${encodeURIComponent(key)}`,
domain: domainSlug,
- endpoint: `/api/projects/${slug}/links/${key}/stats`,
+ endpoint: `/api/links/${encodeURIComponent(key)}/stats`,
};
// Generic Dub.sh link page, e.g. app.dub.sh/links/steven
} else if (key && router.asPath.startsWith("/links")) {
return {
- basePath: `/links/${key}`,
+ basePath: `/links/${encodeURIComponent(key)}`,
domain: "dub.sh",
- endpoint: `/api/links/${key}/stats`,
+ endpoint: `/api/links/${encodeURIComponent(key)}/stats`,
};
}
// Public stats page, e.g. dub.sh/stats/github, stey.me/stats/weathergpt
return {
- basePath: `/stats/${key}`,
+ basePath: `/stats/${encodeURIComponent(key)}`,
domain: staticDomain,
- endpoint: `/api/edge/links/${key}/stats`,
+ endpoint: `/api/edge/links/${encodeURIComponent(key)}/stats`,
};
}, [slug, key, router.asPath]);
diff --git a/lib/middleware/utils.ts b/lib/middleware/utils.ts
index 509e32e261..502c51faa1 100644
--- a/lib/middleware/utils.ts
+++ b/lib/middleware/utils.ts
@@ -6,7 +6,11 @@ export const parse = (req: NextRequest) => {
domain = domain.replace("www.", ""); // remove www. from domain
if (HOME_HOSTNAMES.has(domain)) domain = "dub.sh";
const path = req.nextUrl.pathname;
- const key = decodeURIComponent(path.split("/")[1]); // to handle foreign languages like Hebrew
+
+ // decodeURIComponent to handle foreign languages like Hebrew
+ // slice(1) to remove the leading slash
+ const key = decodeURIComponent(path).slice(1);
+
return { domain, path, key };
};
diff --git a/lib/swr/use-link.ts b/lib/swr/use-link.ts
index 435afee271..738e5fa2b1 100644
--- a/lib/swr/use-link.ts
+++ b/lib/swr/use-link.ts
@@ -11,7 +11,7 @@ export default function useLink() {
};
const { data: link, error } = useSWR<LinkProps>(
- key && `/api/links/${key}`,
+ key && `/api/links/${encodeURIComponent(key)}`,
fetcher,
{
dedupingInterval: 10000,
diff --git a/lib/swr/use-links-count.ts b/lib/swr/use-links-count.ts
index 31e38e60cb..45e62446df 100644
--- a/lib/swr/use-links-count.ts
+++ b/lib/swr/use-links-count.ts
@@ -5,10 +5,6 @@ import { fetcher, getQueryString } from "@/lib/utils";
export default function useLinksCount({ groupBy }: { groupBy: "domain" }) {
const router = useRouter();
- const { slug } = router.query as {
- slug: string;
- };
-
const { data, error } = useSWR<
{
[groupBy]: string;
@@ -16,9 +12,10 @@ export default function useLinksCount({ groupBy }: { groupBy: "domain" }) {
}[]
>(
router.isReady &&
- `${
- slug ? `/api/projects/${slug}/links/count` : `/api/links/count`
- }${getQueryString(router, groupBy ? { groupBy } : undefined)}`,
+ `/api/links/count${getQueryString(
+ router,
+ groupBy ? { groupBy } : undefined,
+ )}`,
fetcher,
{
dedupingInterval: 10000,
diff --git a/lib/swr/use-links.ts b/lib/swr/use-links.ts
index b1d30464e0..6c84d72c75 100644
--- a/lib/swr/use-links.ts
+++ b/lib/swr/use-links.ts
@@ -6,15 +6,8 @@ import { fetcher, getQueryString } from "@/lib/utils";
export default function useLinks() {
const router = useRouter();
- const { slug } = router.query as {
- slug: string;
- };
-
const { data: links, isValidating } = useSWR<LinkProps[]>(
- router.isReady &&
- (slug
- ? `/api/projects/${slug}/links${getQueryString(router)}`
- : `/api/links${getQueryString(router)}`),
+ router.isReady && `/api/links${getQueryString(router)}`,
fetcher,
{
// disable this because it keeps refreshing the state of the modal when its open
diff --git a/lib/utils.ts b/lib/utils.ts
index 8452b8aba1..49f93db92a 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -258,11 +258,12 @@ export const getQueryString = (
) => {
// here, we omit the slug from the query string because
// for some reason it breaks the router because of middleware rewrites
- const { slug, ...queryWithoutSlug } = router.query as Record<string, string>;
+ // const { slug, ...queryWithoutSlug } = router.query as Record<string, string>;
const queryString = new URLSearchParams({
- ...queryWithoutSlug,
+ ...(router.query as Record<string, string>),
...opts,
}).toString();
+ console.log(queryString);
return `${queryString ? "?" : ""}${queryString}`;
};
diff --git a/pages/api/links/[key]/archive.ts b/pages/api/links/[key]/archive.ts
deleted file mode 100644
index b7728f454b..0000000000
--- a/pages/api/links/[key]/archive.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import { NextApiRequest, NextApiResponse } from "next";
-import { archiveLink } from "@/lib/api/links";
-import { Session, withUserAuth } from "@/lib/auth";
-import prisma from "@/lib/prisma";
-
-const domain = "dub.sh";
-
-export default withUserAuth(
- async (req: NextApiRequest, res: NextApiResponse, session: Session) => {
- const { key } = req.query as { key: string };
-
- const isOwner = await prisma.link
- .findUnique({
- where: {
- domain_key: {
- domain,
- key,
- },
- },
- })
- .then((link) => link?.userId === session.user.id);
-
- if (!isOwner) {
- return res.status(403).json({ error: "Not authorized" });
- }
-
- if (req.method === "POST") {
- const response = await archiveLink(domain, key);
- return res.status(200).json(response);
- } else if (req.method === "DELETE") {
- const response = await archiveLink(domain, key, false);
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["POST", "DELETE"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
- }
- },
-);
diff --git a/pages/api/links/[key]/exists.ts b/pages/api/links/[key]/exists.ts
index ecd82ae25f..56f29581bc 100644
--- a/pages/api/links/[key]/exists.ts
+++ b/pages/api/links/[key]/exists.ts
@@ -1,21 +1,14 @@
-import { NextApiRequest, NextApiResponse } from "next";
+import { withLinksAuth } from "@/lib/auth";
import { checkIfKeyExists } from "@/lib/api/links";
-import { withUserAuth } from "@/lib/auth";
-// This is a special route to check if a custom dub.sh links exists
-
-export default withUserAuth(
- async (req: NextApiRequest, res: NextApiResponse) => {
- // GET /api/links/[key]/exists - check if a key exists
- if (req.method === "GET") {
- const { key } = req.query as { key: string };
- const response = await checkIfKeyExists("dub.sh", key);
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["GET"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
- }
- },
-);
+export default withLinksAuth(async (req, res, _session, _project, domain) => {
+ // GET /api/links/[key]/exists - check if a key exists
+ if (req.method === "GET") {
+ const { key } = req.query as { key: string };
+ const response = await checkIfKeyExists(domain || "dub.sh", key);
+ return res.status(200).json(response);
+ } else {
+ res.setHeader("Allow", ["GET"]);
+ return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
+ }
+});
diff --git a/pages/api/links/[key]/index.ts b/pages/api/links/[key]/index.ts
index fbfa28109f..838fde1ca1 100644
--- a/pages/api/links/[key]/index.ts
+++ b/pages/api/links/[key]/index.ts
@@ -1,7 +1,5 @@
-import { NextApiRequest, NextApiResponse } from "next";
+import { withLinksAuth } from "@/lib/auth";
import { deleteLink, editLink } from "@/lib/api/links";
-import { Session, withUserAuth } from "@/lib/auth";
-import prisma from "@/lib/prisma";
import { isBlacklistedDomain, isBlacklistedKey, log } from "@/lib/utils";
import { GOOGLE_FAVICON_URL } from "@/lib/constants";
@@ -13,70 +11,72 @@ export const config = {
},
};
-const domain = "dub.sh";
-
-export default withUserAuth(
- async (req: NextApiRequest, res: NextApiResponse, session: Session) => {
+export default withLinksAuth(
+ async (req, res, session, project, domain, link) => {
const { key: oldKey } = req.query as { key: string };
- const link = await prisma.link.findUnique({
- where: {
- domain_key: {
- domain,
- key: oldKey,
- },
- },
- });
-
- const isOwner = link?.userId === session.user.id;
-
- if (!isOwner) {
- return res.status(403).json({ error: "Not authorized" });
- }
-
+ // GET /api/links/:key – get a link
if (req.method === "GET") {
return res.status(200).json(link);
+
+ // PUT /api/links/:key – edit a link
} else if (req.method === "PUT") {
let { key, url } = req.body;
if (!key || !url) {
- return res
- .status(400)
- .json({ error: "Missing key or url or title or timestamp" });
- }
- const keyBlacklisted = await isBlacklistedKey(key);
- if (keyBlacklisted) {
- return res.status(400).json({ error: "Invalid key" });
+ return res.status(400).end("Missing key or url.");
}
- const domainBlacklisted = await isBlacklistedDomain(url);
- if (domainBlacklisted) {
- return res.status(400).json({ error: "Invalid url" });
+
+ if (!project) {
+ if (key.includes("/")) {
+ return res.status(422).end("Key cannot contain '/'.");
+ }
+ const keyBlacklisted = await isBlacklistedKey(key);
+ if (keyBlacklisted) {
+ return res.status(422).end("Invalid key.");
+ }
+ const domainBlacklisted = await isBlacklistedDomain(url);
+ if (domainBlacklisted) {
+ return res.status(422).end("Invalid url.");
+ }
}
+
const [response, invalidFavicon] = await Promise.allSettled([
editLink(
{
- domain,
...req.body,
+ domain: domain || "dub.sh",
userId: session.user.id,
},
oldKey,
),
- fetch(`${GOOGLE_FAVICON_URL}${url}}`).then((res) => !res.ok),
+ ...(!project
+ ? [fetch(`${GOOGLE_FAVICON_URL}${url}}`).then((res) => !res.ok)]
+ : []),
// @ts-ignore
]).then((results) => results.map((result) => result.value));
if (response === null) {
- return res.status(400).json({ error: "Key already exists" });
+ return res.status(409).end("Key already exists.");
+ }
+
+ if (!project && invalidFavicon) {
+ await log(
+ `*${
+ session.user.email
+ }* edited a link (*dub.sh/${key}*) to the ${url} ${
+ invalidFavicon
+ ? " but it has an invalid favicon :thinking_face:"
+ : ""
+ }`,
+ "links",
+ invalidFavicon ? true : false,
+ );
}
- await log(
- `*${session.user.email}* edited a link (*dub.sh/${key}*) to the ${url} ${
- invalidFavicon ? " but it has an invalid favicon :thinking_face:" : ""
- }`,
- "links",
- invalidFavicon ? true : false,
- );
return res.status(200).json(response);
+
+ // DELETE /api/links/:key – delete a link
} else if (req.method === "DELETE") {
- const response = await deleteLink(domain, oldKey);
+ const response = await deleteLink(domain || "dub.sh", oldKey);
return res.status(200).json(response);
} else {
res.setHeader("Allow", ["GET", "PUT", "DELETE"]);
@@ -85,4 +85,7 @@ export default withUserAuth(
.json({ error: `Method ${req.method} Not Allowed` });
}
},
+ {
+ needNotExceededUsage: true,
+ },
);
diff --git a/pages/api/links/[key]/stats/[endpoint].ts b/pages/api/links/[key]/stats/[endpoint].ts
index 09f0d7e8c4..85d2ab2a99 100644
--- a/pages/api/links/[key]/stats/[endpoint].ts
+++ b/pages/api/links/[key]/stats/[endpoint].ts
@@ -1,9 +1,8 @@
-import { NextApiRequest, NextApiResponse } from "next";
-import { withUserAuth } from "@/lib/auth";
+import { withLinksAuth } from "@/lib/auth";
import { getStats, IntervalProps } from "@/lib/stats";
-export default withUserAuth(
- async (req: NextApiRequest, res: NextApiResponse) => {
+export default withLinksAuth(
+ async (req, res, _session, _project, domain) => {
// GET /api/links/[key]/stats/[endpoint] - get link stats from Tinybird
if (req.method === "GET") {
const { key, endpoint, interval } = req.query as {
@@ -12,7 +11,7 @@ export default withUserAuth(
interval: IntervalProps;
};
const response = await getStats({
- domain: "dub.sh",
+ domain: domain || "dub.sh",
key,
endpoint,
interval,
@@ -32,4 +31,7 @@ export default withUserAuth(
.json({ error: `Method ${req.method} Not Allowed` });
}
},
+ {
+ needNotExceededUsage: true,
+ },
);
diff --git a/pages/api/links/[key]/stats/index.ts b/pages/api/links/[key]/stats/index.ts
index b76c1e571c..b956b5d28f 100644
--- a/pages/api/links/[key]/stats/index.ts
+++ b/pages/api/links/[key]/stats/index.ts
@@ -1,50 +1,45 @@
-import { NextApiRequest, NextApiResponse } from "next";
-import { withUserAuth } from "@/lib/auth";
+import { withLinksAuth } from "@/lib/auth";
import prisma from "@/lib/prisma";
-export default withUserAuth(
- async (req: NextApiRequest, res: NextApiResponse, project) => {
- const { key } = req.query as {
- key: string;
- };
+export default withLinksAuth(async (req, res, _session, _project, domain) => {
+ const { key } = req.query as {
+ key: string;
+ };
- // GET /api/links/[key]/stats - get a link's stats page privacy
- if (req.method === "GET") {
- const link = await prisma.link.findUnique({
- where: {
- domain_key: {
- domain: "dub.sh",
- key,
- },
+ // GET /api/links/[key]/stats - get a link's stats page privacy
+ if (req.method === "GET") {
+ const link = await prisma.link.findUnique({
+ where: {
+ domain_key: {
+ domain: domain || "dub.sh",
+ key,
},
- select: {
- publicStats: true,
- },
- });
+ },
+ select: {
+ publicStats: true,
+ },
+ });
- return res.status(200).json(link);
+ return res.status(200).json(link);
- // PUT /api/links/[key]/stats - edit a link's stats page privacy
- } else if (req.method === "PUT") {
- const { publicStats } = req.body as { publicStats: boolean };
- const response = await prisma.link.update({
- where: {
- domain_key: {
- key,
- domain: "dub.sh",
- },
- },
- data: {
- publicStats,
+ // PUT /api/links/[key]/stats - edit a link's stats page privacy
+ } else if (req.method === "PUT") {
+ const { publicStats } = req.body as { publicStats: boolean };
+ const response = await prisma.link.update({
+ where: {
+ domain_key: {
+ domain: domain || "dub.sh",
+ key,
},
- });
+ },
+ data: {
+ publicStats,
+ },
+ });
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["PUT"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
- }
- },
-);
+ return res.status(200).json(response);
+ } else {
+ res.setHeader("Allow", ["PUT"]);
+ return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
+ }
+});
diff --git a/pages/api/links/count.ts b/pages/api/links/count.ts
index 43cc66fe99..e925651f7c 100644
--- a/pages/api/links/count.ts
+++ b/pages/api/links/count.ts
@@ -1,24 +1,19 @@
-import { NextApiRequest, NextApiResponse } from "next";
-import { Session, withUserAuth } from "@/lib/auth";
-import prisma from "@/lib/prisma";
+import { withLinksAuth } from "@/lib/auth";
import { DUB_PROJECT_ID } from "@/lib/constants";
import { getLinksCount } from "@/lib/api/links";
-export default withUserAuth(
- async (req: NextApiRequest, res: NextApiResponse, session: Session) => {
- // GET /api/links/count – get the count for dub.sh links created by the user
- if (req.method === "GET") {
- const count = await getLinksCount({
- req,
- projectId: DUB_PROJECT_ID,
- userId: session.user.id,
- });
- return res.status(200).json(count);
- } else {
- res.setHeader("Allow", ["GET"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
- }
- },
-);
+export default withLinksAuth(async (req, res, session, project) => {
+ // GET /api/links/count – get the number of links for a project
+ if (req.method === "GET") {
+ const { userId } = req.query as { userId?: string };
+ const count = await getLinksCount({
+ req,
+ projectId: project?.id || DUB_PROJECT_ID,
+ userId: project?.id ? userId : session.user.id,
+ });
+ return res.status(200).json(count);
+ } else {
+ res.setHeader("Allow", ["GET"]);
+ return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
+ }
+});
diff --git a/pages/api/links/index.ts b/pages/api/links/index.ts
index 6af341f4c8..651597a222 100644
--- a/pages/api/links/index.ts
+++ b/pages/api/links/index.ts
@@ -1,6 +1,5 @@
-import { NextApiRequest, NextApiResponse } from "next";
import { addLink, getLinksForProject } from "@/lib/api/links";
-import { Session, withUserAuth } from "@/lib/auth";
+import { withLinksAuth } from "@/lib/auth";
import { isBlacklistedDomain, isBlacklistedKey } from "@/lib/utils";
import { log } from "@/lib/utils";
import { DUB_PROJECT_ID, GOOGLE_FAVICON_URL } from "@/lib/constants";
@@ -13,24 +12,27 @@ export const config = {
},
};
-// This is a special route for retrieving and creating custom dub.sh links.
-export default withUserAuth(
- async (req: NextApiRequest, res: NextApiResponse, session: Session) => {
- // GET /api/links – get all dub.sh links created by the user
+export default withLinksAuth(
+ async (req, res, session, project) => {
+ // GET /api/links – get all links for a project
+ // if no project, get all dub.sh links for user
if (req.method === "GET") {
- const { status, tag, search, sort } = req.query as {
+ const { domain, status, tag, search, sort, userId } = req.query as {
+ domain?: string;
status?: string;
tag?: string;
search?: string;
sort?: "createdAt" | "clicks";
+ userId?: string;
};
const response = await getLinksForProject({
- projectId: DUB_PROJECT_ID,
+ projectId: project?.id || DUB_PROJECT_ID,
+ domain,
status,
tag,
search,
sort,
- userId: session.user.id,
+ userId: project?.id ? userId : session.user.id,
});
return res.status(200).json(response);
@@ -38,39 +40,54 @@ export default withUserAuth(
} else if (req.method === "POST") {
let { key, url } = req.body;
if (!key || !url) {
- return res.status(400).json({ error: "Missing key or url" });
+ return res.status(400).end("Missing key or url.");
}
- const keyBlacklisted = await isBlacklistedKey(key);
- if (keyBlacklisted) {
- return res.status(400).json({ error: "Invalid key" });
- }
- const domainBlacklisted = await isBlacklistedDomain(url);
- if (domainBlacklisted) {
- return res.status(400).json({ error: "Invalid url" });
+
+ // if it's not a custom project, do some filtering
+ if (!project) {
+ if (key.includes("/")) {
+ return res.status(422).end("Key cannot contain '/'.");
+ }
+ const keyBlacklisted = await isBlacklistedKey(key);
+ if (keyBlacklisted) {
+ return res.status(422).end("Invalid key.");
+ }
+ const domainBlacklisted = await isBlacklistedDomain(url);
+ if (domainBlacklisted) {
+ return res.status(422).end("Invalid url.");
+ }
}
+
const [response, invalidFavicon] = await Promise.allSettled([
addLink({
...req.body,
- domain: "dub.sh",
- projectId: DUB_PROJECT_ID,
+ projectId: project?.id || DUB_PROJECT_ID,
userId: session.user.id,
}),
- fetch(`${GOOGLE_FAVICON_URL}${url}}`).then((res) => !res.ok),
+ ...(!project
+ ? [fetch(`${GOOGLE_FAVICON_URL}${url}}`).then((res) => !res.ok)]
+ : []),
// @ts-ignore
]).then((results) => results.map((result) => result.value));
if (response === null) {
- return res.status(403).json({ error: "Key already exists" });
+ return res.status(409).end("Key already exists.");
}
- await log(
- `*${
- session.user.email
- }* created a new link (*dub.sh/${key}*) for ${url} ${
- invalidFavicon ? " but it has an invalid favicon :thinking_face:" : ""
- }`,
- "links",
- invalidFavicon ? true : false,
- );
+
+ if (!project && invalidFavicon) {
+ await log(
+ `*${
+ session.user.email
+ }* created a new link (*dub.sh/${key}*) for ${url} ${
+ invalidFavicon
+ ? " but it has an invalid favicon :thinking_face:"
+ : ""
+ }`,
+ "links",
+ invalidFavicon ? true : false,
+ );
+ }
+
return res.status(200).json(response);
} else {
res.setHeader("Allow", ["GET", "POST"]);
@@ -79,4 +96,8 @@ export default withUserAuth(
.json({ error: `Method ${req.method} Not Allowed` });
}
},
+ {
+ needNotExceededUsage: true,
+ excludeGet: true,
+ },
);
diff --git a/pages/api/links/random.ts b/pages/api/links/random.ts
index d77dbc3c3d..9c735bd11f 100644
--- a/pages/api/links/random.ts
+++ b/pages/api/links/random.ts
@@ -1,15 +1,12 @@
-import { NextApiRequest, NextApiResponse } from "next";
+import { withLinksAuth } from "@/lib/auth";
import { getRandomKey } from "@/lib/api/links";
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
+export default withLinksAuth(async (req, res, _session, _project, domain) => {
if (req.method === "GET") {
- const response = await getRandomKey("dub.sh");
+ const response = await getRandomKey(domain || "dub.sh");
return res.status(200).json(response);
} else {
res.setHeader("Allow", ["GET"]);
return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
}
-}
+});
diff --git a/pages/api/projects/[slug]/links/[key]/archive.ts b/pages/api/projects/[slug]/links/[key]/archive.ts
deleted file mode 100644
index b739dbe9ab..0000000000
--- a/pages/api/projects/[slug]/links/[key]/archive.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { archiveLink } from "@/lib/api/links";
-import { withProjectAuth } from "@/lib/auth";
-
-export default withProjectAuth(async (req, res) => {
- const { domain, key } = req.query as {
- domain: string;
- key: string;
- };
-
- if (req.method === "POST") {
- const response = await archiveLink(domain, key);
- return res.status(200).json(response);
- } else if (req.method === "DELETE") {
- const response = await archiveLink(domain, key, false);
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["POST", "DELETE"]);
- return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
- }
-});
diff --git a/pages/api/projects/[slug]/links/[key]/exists.ts b/pages/api/projects/[slug]/links/[key]/exists.ts
deleted file mode 100644
index 7648b042f0..0000000000
--- a/pages/api/projects/[slug]/links/[key]/exists.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-import { checkIfKeyExists } from "@/lib/api/links";
-import { withProjectAuth } from "@/lib/auth";
-
-export default withProjectAuth(async (req, res) => {
- // GET /api/projects/[slug]/domains/[domain]/links/[key]/exists - check if a key exists
- if (req.method === "GET") {
- const { domain, key } = req.query as { domain: string; key: string };
- const response = await checkIfKeyExists(domain, key);
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["GET"]);
- return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
- }
-});
diff --git a/pages/api/projects/[slug]/links/[key]/index.ts b/pages/api/projects/[slug]/links/[key]/index.ts
deleted file mode 100644
index bb89f04f56..0000000000
--- a/pages/api/projects/[slug]/links/[key]/index.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { deleteLink, editLink } from "@/lib/api/links";
-import { withProjectAuth } from "@/lib/auth";
-
-export const config = {
- api: {
- bodyParser: {
- sizeLimit: "1500kb",
- },
- },
-};
-
-export default withProjectAuth(
- async (req, res) => {
- const { domain, key: oldKey } = req.query as {
- domain: string;
- key: string;
- };
-
- // PUT /api/projects/[slug]/domains/[domain]/links/[key] - edit a link
- if (req.method === "PUT") {
- let { key, url } = req.body;
- if (!key || !url) {
- return res
- .status(400)
- .json({ error: "Missing key or url or title or timestamp" });
- }
- const response = await editLink(
- {
- domain,
- ...req.body,
- },
- oldKey,
- );
- if (response === null) {
- return res.status(400).json({ error: "Key already exists" });
- }
- return res.status(200).json(response);
- } else if (req.method === "DELETE") {
- const response = await deleteLink(domain, oldKey);
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["PUT", "DELETE"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
- }
- },
- {
- needNotExceededUsage: true,
- },
-);
diff --git a/pages/api/projects/[slug]/links/[key]/stats/[endpoint].ts b/pages/api/projects/[slug]/links/[key]/stats/[endpoint].ts
deleted file mode 100644
index 2118c2f847..0000000000
--- a/pages/api/projects/[slug]/links/[key]/stats/[endpoint].ts
+++ /dev/null
@@ -1,35 +0,0 @@
-import { withProjectAuth } from "@/lib/auth";
-import { getStats, IntervalProps } from "@/lib/stats";
-
-export default withProjectAuth(
- async (req, res) => {
- // GET /api/projects/[slug]/links/[key]/stats/[endpoint] - get link stats from Tinybird
- if (req.method === "GET") {
- const { domain, key, endpoint, interval } = req.query as {
- domain: string;
- key: string;
- endpoint: string;
- interval: IntervalProps;
- };
- const response = await getStats({
- domain,
- key,
- endpoint,
- interval,
- });
- if (!response) {
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
- }
-
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["GET"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
- }
- },
- { needNotExceededUsage: true },
-);
diff --git a/pages/api/projects/[slug]/links/[key]/stats/index.ts b/pages/api/projects/[slug]/links/[key]/stats/index.ts
deleted file mode 100644
index ec33636f87..0000000000
--- a/pages/api/projects/[slug]/links/[key]/stats/index.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import { withProjectAuth } from "@/lib/auth";
-import prisma from "@/lib/prisma";
-
-export default withProjectAuth(
- async (req, res) => {
- const { domain, key } = req.query as {
- domain: string;
- key: string;
- };
-
- // GET /api/projects/[slug]/domains/[domain]/links/[key]/stats - get a link's stats page privacy
- if (req.method === "GET") {
- const link = await prisma.link.findUnique({
- where: {
- domain_key: {
- domain,
- key,
- },
- },
- select: {
- publicStats: true,
- },
- });
-
- return res.status(200).json(link);
-
- // PUT /api/projects/[slug]/domains/[domain]/links/[key]/stats - edit a link's stats page privacy
- } else if (req.method === "PUT") {
- const { publicStats } = req.body as { publicStats: boolean };
- const response = await prisma.link.update({
- where: {
- domain_key: {
- key,
- domain,
- },
- },
- data: {
- publicStats,
- },
- });
-
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["GET", "PUT"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
- }
- },
- {
- needNotExceededUsage: true,
- },
-);
diff --git a/pages/api/projects/[slug]/links/count.ts b/pages/api/projects/[slug]/links/count.ts
deleted file mode 100644
index 3c097223f7..0000000000
--- a/pages/api/projects/[slug]/links/count.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-import { withProjectAuth } from "@/lib/auth";
-import { getLinksCount } from "@/lib/api/links";
-
-export default withProjectAuth(async (req, res, project, session) => {
- // GET /api/projects/[slug]/domains/[domain]/links/count – count the number of links for a project
- if (req.method === "GET") {
- const { userId } = req.query as { userId?: string };
- const count = await getLinksCount({
- req,
- projectId: project.id,
- userId,
- });
- return res.status(200).json(count);
- } else {
- res.setHeader("Allow", ["GET"]);
- return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
- }
-});
diff --git a/pages/api/projects/[slug]/links/index.ts b/pages/api/projects/[slug]/links/index.ts
deleted file mode 100644
index 683e26ec37..0000000000
--- a/pages/api/projects/[slug]/links/index.ts
+++ /dev/null
@@ -1,69 +0,0 @@
-import { addLink, getLinksForProject } from "@/lib/api/links";
-import { withProjectAuth } from "@/lib/auth";
-
-export const config = {
- api: {
- bodyParser: {
- sizeLimit: "1500kb",
- },
- },
-};
-
-export default withProjectAuth(
- async (req, res, project, session) => {
- // GET /api/projects/[slug]/links - Get all links for a project
- if (req.method === "GET") {
- const { domain, status, tag, search, sort, userId } = req.query as {
- domain?: string;
- status?: string;
- tag?: string;
- search?: string;
- sort?: "createdAt" | "clicks";
- userId?: string;
- };
- const response = await getLinksForProject({
- projectId: project.id,
- domain,
- status,
- tag,
- search,
- sort,
- // @ts-ignore
- userId,
- });
- return res.status(200).json(response);
-
- // POST /api/projects/[slug]/links – create a new link
- } else if (req.method === "POST") {
- const { domain } = req.query as { domain: string };
- let { key, url } = req.body;
- if (!domain || !key || !url) {
- return res.status(400).json({ error: "Missing domain or url or key" });
- }
- // Prevent the creation of recursive links
- const { hostname, pathname } = new URL(url);
- if (hostname === domain && pathname === `/${key}`) {
- return res.status(400).json({ error: "Invalid url" });
- }
-
- const response = await addLink({
- ...req.body,
- projectId: project.id,
- userId: session.user.id,
- });
- if (response === null) {
- return res.status(403).json({ error: "Key already exists" });
- }
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["GET", "POST"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
- }
- },
- {
- excludeGet: true,
- needNotExceededUsage: true,
- },
-);
diff --git a/pages/api/projects/[slug]/links/random.ts b/pages/api/projects/[slug]/links/random.ts
deleted file mode 100644
index b43a94de0a..0000000000
--- a/pages/api/projects/[slug]/links/random.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { getRandomKey } from "@/lib/api/links";
-import { withProjectAuth } from "@/lib/auth";
-
-export default withProjectAuth(async (req, res) => {
- // GET /api/projects/[slug]/domains/[domain]/links/random – get a random link
- if (req.method === "GET") {
- const { domain } = req.query as { domain: string };
- if (!domain) {
- return res.status(400).json({ error: "Missing domain" });
- }
- const key = await getRandomKey(domain);
- return res.status(200).json(key);
- } else {
- res.setHeader("Allow", ["GET"]);
- return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
- }
-});