The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
updated CRON functions for /api/projects/links and /api/links
Steven Tey2fc8c9bee836
diff --git a/README.md b/README.mdindex 2d74a09edc..be1f92e48b 100644--- a/README.md+++ b/README.md@@ -69,9 +69,9 @@ Dub is built as a standard Next.js application with [Middleware](https://nextjs.[Redis](https://redis.io/) is used as the caching layer for all short links. Redis also has the Sorted Set data type, which is perfect for storing & retrieving time-series analytics data. Here's the full schema:-- `{hostname}:{key}` – string containing a JSON object with the target URL and password (optional). Also has an optional TTL.-- `{hostname}:clicks:{key}` – sorted set of all clicks for a given link (e.g. `dub.sh:clicks:github`)-- `{hostname}:root:clicks` – sorted set of all root link clicks for a given hostname (e.g. `dub.sh:root:clicks`)+- `{domain}:{key}` – string containing a JSON object with the target URL and password (optional). Also has an optional TTL.+- `{domain}:clicks:{key}` – sorted set of all clicks for a given link (e.g. `dub.sh:clicks:github`)+- `{domain}:root:clicks` – sorted set of all root link clicks for a given hostname (e.g. `dub.sh:root:clicks`)[MySQL](https://www.mysql.com/) is used as the database for storing user data, project data, and link metadata. You can refer to the Prisma schema [here](/prisma/schema.prisma).diff --git a/components/app/link-card.tsx b/components/app/link-card.tsxindex 0a48debd4c..923d501001 100644--- a/components/app/link-card.tsx+++ b/components/app/link-card.tsx@@ -20,7 +20,7 @@ import { useDeleteLinkModal } from "./modals/delete-link-modal";import { useLinkQRModal } from "./modals/link-qr-modal";export default function LinkCard({ props }: { props: LinkProps }) {- const { key, url, title, timestamp } = props;+ const { key, url, title, createdAt } = props;const apexDomain = getApexDomain(url);@@ -31,11 +31,14 @@ export default function LinkCard({ props }: { props: LinkProps }) {const { domain } = project || {};const { exceededUsage } = useUsage();- const { data: clicks, isValidating } = useSWR<string>(+ const { data: clicks, isValidating } = useSWR<number>(domain? `/api/projects/${slug}/domains/${domain}/links/${key}/clicks`: `/api/edge/links/${key}/clicks`,fetcher,+ {+ fallbackData: props.clicks,+ },);const { setShowAddEditLinkModal, AddEditLinkModal } = useAddEditLinkModal({@@ -86,10 +89,10 @@ export default function LinkCard({ props }: { props: LinkProps }) {<a className="flex items-center space-x-1 rounded-md bg-gray-100 px-2 py-0.5 hover:scale-105 active:scale-95 transition-all duration-75"><Chart className="w-4 h-4" /><p className="text-sm text-gray-500 whitespace-nowrap">- {isValidating || !clicks ? (+ {isValidating ? (<LoadingDots color="#71717A" />) : (- nFormatter(parseInt(clicks))+ nFormatter(clicks))}<span className="hidden sm:inline-block ml-1">clicks</span></p>@@ -97,13 +100,13 @@ export default function LinkCard({ props }: { props: LinkProps }) {</Link></div><h3 className="text-sm font-medium text-gray-700 line-clamp-1">- {title}+ {title || url}</h3></div></div><div className="flex items-center space-x-3 w-full sm:w-auto"><p className="text-sm hidden sm:block text-gray-500">- Added {timeAgo(timestamp)}+ Added {timeAgo(createdAt)}</p>{slug && exceededUsage ? (<Tooltipdiff --git a/components/app/links-container.tsx b/components/app/links-container.tsxindex c391441933..9061012e6d 100644--- a/components/app/links-container.tsx+++ b/components/app/links-container.tsx@@ -22,6 +22,10 @@ export default function LinksContainer({const { data: links } = useSWR<LinkProps[]>(domain ? `/api/projects/${slug}/domains/${domain}/links` : `/api/links`,fetcher,+ {+ // disable this because it keeps refreshing the state of the modal when its open+ revalidateOnFocus: false,+ },);return (diff --git a/components/app/modals/add-edit-link-modal.tsx b/components/app/modals/add-edit-link-modal.tsxindex 75c8706127..0b7cd669c7 100644--- a/components/app/modals/add-edit-link-modal.tsx+++ b/components/app/modals/add-edit-link-modal.tsx@@ -37,21 +37,23 @@ function AddEditLinkModal({const router = useRouter();const { slug } = router.query as { slug: string };const { project: { domain } = {} } = useProject();- const { plan } = useUsage();const [keyExistsError, setKeyExistsError] = useState(false);const [generatingSlug, setGeneratingSlug] = useState(false);- const [generatingTitle, setGeneratingTitle] = useState(false);const [saving, setSaving] = useState(false);const [data, setData] = useState<LinkProps>(props || {+ domain: domain || "",key: "",url: "",- title: "",+ archived: false,+ clicks: 0,+ userId: "",+ createdAt: new Date(),},);- const { key, url, title } = data;+ const { key, url } = data;const heroProps = useMemo(() => {if (props?.url) {@@ -80,11 +82,11 @@ function AddEditLinkModal({fetch(domain? `/api/projects/${slug}/domains/${domain}/links/${debouncedKey}/exists`- : `/api/edge/links/${debouncedKey}/exists`,+ : `/api/links/${debouncedKey}/exists`,).then(async (res) => {if (res.status === 200) {const exists = await res.json();- setKeyExistsError(exists === 1);+ setKeyExistsError(exists);}});}@@ -102,28 +104,6 @@ function AddEditLinkModal({setGeneratingSlug(false);}, []);- const [debouncedUrl] = useDebounce(url, 500);- useEffect(() => {- if (debouncedUrl.length > 0 && title.length === 0) {- // only fetch title if user hasn't entered one- generateTitleFromUrl(debouncedUrl);- }- }, [debouncedUrl]);-- const generateTitleFromUrl = useCallback(- (debouncedUrl: string) => {- setGeneratingTitle(true);- fetch(`/api/edge/title?url=${debouncedUrl}`).then(async (res) => {- if (res.status === 200) {- const results = await res.json();- setData((prev) => ({ ...prev, title: results }));- setGeneratingTitle(false);- }- });- },- [debouncedUrl],- );-const endpoint = useMemo(() => {if (props?.key) {return {@@ -169,22 +149,19 @@ function AddEditLinkModal({"Content-Type": "application/json",},body: JSON.stringify(data),- })- .then((res) => {- setSaving(false);- if (res.status === 200) {- mutate(- domain- ? `/api/projects/${slug}/domains/${domain}/links`- : `/api/links`,- );- setShowAddEditLinkModal(false);- }- })- .catch(() => {- setSaving(false);+ }).then((res) => {+ setSaving(false);+ if (res.status === 200) {+ mutate(+ domain+ ? `/api/projects/${slug}/domains/${domain}/links`+ : `/api/links`,+ );+ setShowAddEditLinkModal(false);+ } else {setKeyExistsError(true);- });+ }+ });}}className="grid gap-6 bg-gray-50 py-8">@@ -273,54 +250,9 @@ function AddEditLinkModal({/></div></div>-- <div>- <div className="flex justify-between items-center">- <label- htmlFor="title"- className="block text-sm font-medium text-gray-700"- >- Title- </label>- <button- className={`${- url.length === 0- ? "cursor-not-allowed text-gray-300"- : "hover:text-black active:scale-95"- } flex items-center space-x-2 text-gray-500 text-sm transition-all duration-75`}- onClick={() => generateTitleFromUrl(url)}- disabled={url.length === 0 || generatingTitle}- type="button"- >- {generatingTitle && <LoadingCircle />}- <p>{generatingTitle ? "Generating" : "Generate from URL"}</p>- </button>- </div>- <div className="flex mt-1 rounded-md shadow-sm">- <TextareaAutosize- name="title"- id="title"- required- minRows={3}- className="border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:ring-gray-500 pr-10 block w-full rounded-md focus:outline-none sm:text-sm"- placeholder="Dub - an open-source link shortener SaaS with built-in analytics + free custom domains."- value={title}- onChange={(e) => {- setData({ ...data, title: e.target.value });- }}- aria-invalid="true"- />- </div>- </div></div>- {plan?.startsWith("Pro") && slug && (- <AdvancedSettings- data={data}- setData={setData}- debouncedUrl={debouncedUrl}- />- )}+ <AdvancedSettings data={data} setData={setData} /><div className="sm:px-16 px-4"><button@@ -344,32 +276,34 @@ function AddEditLinkModal({);}-function AdvancedSettings({ data, setData, debouncedUrl }) {+function AdvancedSettings({ data, setData }) {const [expanded, setExpanded] = useState(false);+ const [generatingTitle, setGeneratingTitle] = useState(false);const [generatingDescription, setGeneratingDescription] = useState(false);- const { url, description, image } = data;+ const { url, title, description, image } = data;- useEffect(() => {- if (debouncedUrl.length > 0 && description?.length === 0) {- // only fetch title if user hasn't entered one- generateTitleFromUrl(debouncedUrl);- }- }, [debouncedUrl]);+ const generateTitleFromUrl = async () => {+ setGeneratingTitle(true);+ fetch(`/api/edge/title?url=${url}`).then(async (res) => {+ if (res.status === 200) {+ const results = await res.json();+ setData((prev) => ({ ...prev, title: results }));+ setGeneratingTitle(false);+ }+ });+ };- const generateTitleFromUrl = useCallback(- (debouncedUrl: string) => {- setGeneratingDescription(true);- fetch(`/api/edge/description?url=${debouncedUrl}`).then(async (res) => {- if (res.status === 200) {- const results = await res.json();- setData((prev) => ({ ...prev, description: results }));- setGeneratingDescription(false);- }- });- },- [debouncedUrl],- );+ const generateDescriptionFromUrl = async () => {+ setGeneratingDescription(true);+ fetch(`/api/edge/description?url=${url}`).then(async (res) => {+ if (res.status === 200) {+ const results = await res.json();+ setData((prev) => ({ ...prev, description: results }));+ setGeneratingDescription(false);+ }+ });+ };const onChangePicture = useCallback((e) => {@@ -402,13 +336,50 @@ function AdvancedSettings({ data, setData, debouncedUrl }) {{expanded && (<div className="mt-4 grid gap-5 bg-white border-t border-b border-gray-200 sm:px-16 px-4 py-8">+ <div>+ <div className="flex justify-between items-center">+ <label+ htmlFor="title"+ className="block text-sm font-medium text-gray-700"+ >+ OG Title+ </label>+ <button+ className={`${+ url.length === 0+ ? "cursor-not-allowed text-gray-300"+ : "hover:text-black active:scale-95"+ } flex items-center space-x-2 text-gray-500 text-sm transition-all duration-75`}+ onClick={() => generateTitleFromUrl()}+ disabled={url.length === 0 || generatingTitle}+ type="button"+ >+ {generatingTitle && <LoadingCircle />}+ <p>{generatingTitle ? "Generating" : "Generate from URL"}</p>+ </button>+ </div>+ <div className="flex mt-1 rounded-md shadow-sm">+ <TextareaAutosize+ name="title"+ id="title"+ minRows={3}+ className="border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:ring-gray-500 pr-10 block w-full rounded-md focus:outline-none sm:text-sm"+ placeholder="Dub - an open-source link shortener SaaS with built-in analytics + free custom domains."+ value={title}+ onChange={(e) => {+ setData({ ...data, title: e.target.value });+ }}+ aria-invalid="true"+ />+ </div>+ </div><div><div className="flex justify-between items-center"><labelhtmlFor="description"className="block text-sm font-medium text-gray-700">- Description+ OG Description</label><buttonclassName={`${@@ -416,7 +387,7 @@ function AdvancedSettings({ data, setData, debouncedUrl }) {? "cursor-not-allowed text-gray-300": "hover:text-black active:scale-95"} flex items-center space-x-2 text-gray-500 text-sm transition-all duration-75`}- onClick={() => generateTitleFromUrl(url)}+ onClick={() => generateDescriptionFromUrl()}disabled={url.length === 0 || generatingDescription}type="button">diff --git a/components/layout/app/list-box.tsx b/components/layout/app/list-box.tsxindex 1e90a82f39..9f0c1fc570 100644--- a/components/layout/app/list-box.tsx+++ b/components/layout/app/list-box.tsx@@ -27,6 +27,9 @@ export default function ListBox() {name: session?.user?.name || session?.user?.email || "User",slug: "/",domain: "dub.sh",+ logo:+ session?.user?.image ||+ `https://avatars.dicebear.com/api/micah/${session?.user?.email}.svg`,});}, [router, projects, session]);@@ -54,10 +57,8 @@ export default function ListBox() {<div className="flex justify-start items-center space-x-3"><BlurImagesrc={- selected.slug === "/"- ? session?.user?.image ||- `https://avatars.dicebear.com/api/micah/${session?.user?.email}.svg`- : `https://www.google.com/s2/favicons?sz=64&domain_url=${selected.domain}`+ selected.logo ||+ `https://www.google.com/s2/favicons?sz=64&domain_url=${selected.domain}`}alt={selected.slug}className="w-8 h-8 flex-shrink-0 rounded-full overflow-hidden border border-gray-300"@@ -85,7 +86,7 @@ export default function ListBox() {leaveTo="transform opacity-0 scale-95"><Listbox.Options className="absolute mt-1 max-h-60 w-60 overflow-auto rounded-md bg-white p-2 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm">- {projects.map(({ name, slug, domain }) => (+ {projects.map(({ name, slug, domain, logo }) => (<Listbox.Optionkey={slug}className={`relative flex items-center space-x-2 cursor-pointer p-2 rounded-md hover:bg-gray-100 active:scale-95 ${@@ -94,7 +95,10 @@ export default function ListBox() {value={{ name, slug }}><BlurImage- src={`https://www.google.com/s2/favicons?sz=64&domain_url=${domain}`}+ src={+ logo ||+ `https://www.google.com/s2/favicons?sz=64&domain_url=${domain}`+ }alt={slug}className="w-7 h-7 rounded-full overflow-hidden"width={48}diff --git a/components/stats/referer.tsx b/components/stats/referer.tsxindex cd57a24c9e..ddd4d1a474 100644--- a/components/stats/referer.tsx+++ b/components/stats/referer.tsx@@ -33,7 +33,7 @@ export default function Referer({ data: rawData }: { data: StatsProps }) {onScroll={handleScroll}><div className="mb-5 flex">- <h1 className="text-xl font-semibold">Referrals</h1>+ <h1 className="text-xl font-semibold">Referrers</h1></div><divclassName={diff --git a/lib/api/links.ts b/lib/api/links.tsnew file mode 100644index 0000000000..774e191aab--- /dev/null+++ b/lib/api/links.ts@@ -0,0 +1,220 @@+import cloudinary from "cloudinary";+import { DEFAULT_REDIRECTS, RESERVED_KEYS } from "@/lib/constants";+import prisma from "@/lib/prisma";+import { LinkProps } from "@/lib/types";+import { redis } from "@/lib/upstash";++export async function getLinksForProject({+ domain,+ archived = false,+ orderBy = "createdAt",+ userId,+}: {+ domain: string;+ archived?: boolean;+ orderBy?: "createdAt" | "clicks"; // always descending for both+ userId?: string;+}): Promise<LinkProps[]> {+ return await prisma.link.findMany({+ where: {+ domain,+ archived,+ ...(userId && { userId }),+ },+ orderBy: {+ [orderBy]: "desc",+ },+ });+}++export async function checkIfKeyExists(domain: string, key: string) {+ if (+ domain === "dub.sh" &&+ (RESERVED_KEYS.has(key) || DEFAULT_REDIRECTS[key])+ ) {+ return true; // reserved keys for dub.sh+ }+ const link = await prisma.link.findUnique({+ where: {+ domain_key: {+ domain,+ key,+ },+ },+ });+ return !!link;+}++export async function addLink(link: LinkProps) {+ const {+ domain,+ key,+ url,+ expiresAt,+ passwordHash,+ title,+ description,+ image,+ } = link;+ const password = passwordHash ? true : false;+ const proxy = title && description && image ? true : false;+ const exat = expiresAt ? expiresAt.getTime() : null;++ const exists = await checkIfKeyExists(domain, key);+ if (exists) return null;++ let [response, _] = await Promise.all([+ prisma.link.create({+ data: {+ ...link,+ // can't upload base64 image string to mysql, need to upload to cloudinary first+ image: undefined,+ },+ }),+ redis.set(+ `${domain}:${key}`,+ {+ url,+ password,+ proxy,+ },+ {+ nx: true,+ // if the key has an expiry, set exat+ ...(exat && { exat }),+ },+ ),+ ]);+ if (image) {+ const { secure_url } = await cloudinary.v2.uploader.upload(image, {+ public_id: key,+ folder: domain,+ overwrite: true,+ invalidate: true,+ });+ response = await prisma.link.update({+ where: {+ id: response.id,+ },+ data: {+ image: secure_url,+ },+ });+ }+ return response;+}++export async function editLink(+ link: LinkProps,+ oldKey: string,+ projectSlug: string,+) {+ const {+ id,+ domain,+ key,+ url,+ expiresAt,+ passwordHash,+ title,+ description,+ image,+ } = link;+ const password = passwordHash ? true : false;+ const proxy = title && description && image ? true : false;+ const exat = expiresAt ? expiresAt.getTime() : null;+ const changedKey = key !== oldKey;+ const uploadedImage = image && image.startsWith("data:image");++ if (changedKey) {+ const exists = await checkIfKeyExists(domain, key);+ if (exists) return null;+ }++ const [response, ...effects] = await Promise.all([+ prisma.link.update({+ where: {+ id,+ },+ data: {+ ...link,+ // if it's an uploaded image (base64 URI), need to upload to cloudinary first+ image: uploadedImage ? undefined : image,+ },+ }),+ // only upload image to cloudinary if it's changed+ uploadedImage &&+ cloudinary.v2.uploader.upload(image, {+ public_id: key,+ folder: domain,+ overwrite: true,+ invalidate: true,+ }),+ redis.set(+ `${domain}:${key}`,+ {+ url,+ password,+ proxy,+ },+ {+ // if the key has an expiry, set exat+ ...(exat && { exat }),+ },+ ),+ // if key is changed: rename resource in Cloudinary, delete the old key in Redis and change the clicks key name+ ...(changedKey+ ? [+ cloudinary.v2.uploader+ .rename(`${domain}/${oldKey}`, `${domain}/${key}`, {+ invalidate: true,+ })+ .catch(() => {}),+ redis.del(`${domain}:${oldKey}`),+ redis+ .rename(`${domain}:clicks:${oldKey}`, `${domain}:clicks:${key}`)+ .catch(() => {}),+ ]+ : []),+ // if this link has custom OG tags and the key is the same, update the proxy cache+ proxy &&+ !changedKey &&+ (await fetch(+ `https://dub.sh/api/projects/${projectSlug}/domains/${domain}/links/${oldKey}/revalidate?secret=${process.env.REVALIDATE_TOKEN}`,+ )),+ ]);+ if (uploadedImage) {+ const { secure_url } = effects[0];+ response.image = secure_url;+ await prisma.link.update({+ where: {+ id,+ },+ data: {+ image: secure_url,+ },+ });+ }++ console.log(effects);++ return response;+}++export async function deleteLink(domain: string, key: string) {+ return await Promise.all([+ prisma.link.delete({+ where: {+ domain_key: {+ domain,+ key,+ },+ },+ }),+ cloudinary.v2.uploader.destroy(`${domain}/${key}`, {+ invalidate: true,+ }),+ redis.del(`${domain}:${key}`),+ redis.del(`${domain}:clicks:${key}`),+ ]);+}diff --git a/lib/auth.ts b/lib/auth.tsindex 0c6b3ec6f5..b94f1d3adb 100644--- a/lib/auth.ts+++ b/lib/auth.ts@@ -27,6 +27,7 @@ interface WithProjectNextApiHandler {req: NextApiRequest,res: NextApiResponse,project?: ProjectProps,+ session?: Session,): Promise<void>;}@@ -95,16 +96,6 @@ const withProjectAuth =}if (needNotExceededUsage || needProSubscription) {- const user = (await prisma.user.findUnique({- where: {- id: session.user.id,- },- select: {- usage: true,- usageLimit: true,- },- })) as UsageProps;-if (needNotExceededUsage && project.ownerExceededUsage) {return res.status(403).end("Unauthorized: Usage limits exceeded.");}@@ -115,7 +106,7 @@ const withProjectAuth =}}- return handler(req, res, project);+ return handler(req, res, project, session);};export { withProjectAuth };diff --git a/lib/constants.ts b/lib/constants.tsindex cc26e72cd2..5d3ce9f324 100644--- a/lib/constants.ts+++ b/lib/constants.ts@@ -596,3 +596,7 @@ export const secondLevelDomains = new Set(["gov","in",]);++export const SPECIAL_APEX_DOMAINS = {+ "youtu.be": "youtube.com",+};diff --git a/lib/middleware/link.ts b/lib/middleware/link.tsindex 1da458fcff..165e30d179 100644--- a/lib/middleware/link.ts+++ b/lib/middleware/link.ts@@ -14,13 +14,17 @@ export default async function LinkMiddleware(return NextResponse.next();}- const response = await redis.get<{ url: string; password?: boolean }>(- `${hostname}:${key}`,- );- const { url: target, password } = response || {};+ const response = await redis.get<{+ url: string;+ password?: boolean;+ proxy?: boolean;+ }>(`${hostname}:${key}`);+ const { url: target, password, proxy } = response || {};++ console.log(req.cookies.get("dub_authenticated"));if (target) {- if (password) {+ if (password && !req.cookies.get("dub_authenticated")) {return NextResponse.rewrite(`https://dub.sh/auth/${hostname}/${key}`);}diff --git a/lib/types.ts b/lib/types.tsindex 9bfc99b40c..257f5a0410 100644--- a/lib/types.ts+++ b/lib/types.ts@@ -4,12 +4,28 @@ export interface SimpleLinkProps {}export interface LinkProps {+ id?: string;+ domain: string;key: string;url: string;- title: string;- timestamp?: number;+ archived: boolean;+ expiresAt?: Date;+ passwordHash?: string;++ title?: string;description?: string;image?: string;++ utm_source?: string;+ utm_medium?: string;+ utm_campaign?: string;+ utm_term?: string;+ utm_content?: string;++ clicks: number;+ userId: string;++ createdAt: Date;}export interface ProjectProps {diff --git a/lib/upstash.ts b/lib/upstash.tsindex a34a87f9e2..9c9bf54362 100644--- a/lib/upstash.ts+++ b/lib/upstash.ts@@ -115,7 +115,7 @@ export async function recordClick(* Get the links associated with a project**/export async function getLinksForProject(- slug: string,+ domain: string,userId?: string,): Promise<LinkProps[]> {/*@@ -126,7 +126,7 @@ export async function getLinksForProject(Otherwise, it will return all links for the project.*/const keys = await redis.zrange<string[]>(- `${slug}:links:timestamps${userId ? `:${userId}` : ""}`,+ `${domain}:links:timestamps${userId ? `:${userId}` : ""}`,0,-1,{@@ -134,7 +134,7 @@ export async function getLinksForProject(},);if (!keys || keys.length === 0) return []; // no links for this project- const metadata = (await redis.hmget(`${slug}:links`, ...keys)) as {+ const metadata = (await redis.hmget(`${domain}:links`, ...keys)) as {[key: string]: Omit<LinkProps, "key">;};const links = keys.map((key) => ({@@ -151,10 +151,10 @@ export async function getLinkCountForProject(slug: string) {return await redis.zcard(`${slug}:links:timestamps`);}-export async function getLinkClicksCount(hostname: string, key: string) {+export async function getLinkClicksCount(domain: string, key: string) {const start = Date.now() - 2629746000; // 30 days agoreturn (- (await redis.zcount(`${hostname}:clicks:${key}`, start, Date.now())) || "0"+ (await redis.zcount(`${domain}:clicks:${key}`, start, Date.now())) || 0);}@@ -191,72 +191,6 @@ export async function addLink(}}-/**- * Edit a link- **/-export async function editLink(- domain: string,- oldKey: string,- link: LinkProps,- userId?: string,-) {- let { key, url, title, timestamp, description: rawDescription, image } = link;-- // if there's an image but no description, try and auto generate one- const description =- image && !rawDescription ? getDescriptionFromUrl(url) : rawDescription;-- if (oldKey === key) {- // if key is the same, just update the url and title- return await redis.hset(`${domain}:links`, {- [oldKey]: { url, title, timestamp, description, image },- });- } else {- // if key is different- if (domain === "dub.sh" && RESERVED_KEYS.has(key)) {- return null; // reserved keys for dub.sh- }- const keyExists = await checkIfKeyExists(domain, key);- if (keyExists === 1) {- return null; // key already exists- }-- // get number of clicks for oldKey (we'll add it to key)- const numClicks = await redis.zcard(`${domain}:clicks:${oldKey}`);- const pipeline = redis.pipeline();- // delete old key and add new key from hash- pipeline.hdel(`${domain}:links`, oldKey);- pipeline.hset(`${domain}:links`, {- [key]: { url, title, timestamp, description, image },- });- // remove old key from links:timestamps and add new key (with same timestamp)- pipeline.zrem(- `${domain}:links:timestamps${userId ? `:${userId}` : ""}`,- oldKey,- );- pipeline.zadd(`${domain}:links:timestamps${userId ? `:${userId}` : ""}`, {- score: timestamp,- member: key,- });- // update name for clicks:[key] (if numClicks > 0, because we don't create clicks:[key] until the first click)- if (numClicks > 0) {- pipeline.rename(`${domain}:clicks:${oldKey}`, `${domain}:clicks:${key}`);- }- return await pipeline.exec();- }-}--/**- * Delete a link- **/-export async function deleteLink(domain: string, key: string, userId?: string) {- const pipeline = redis.pipeline();- pipeline.hdel(`${domain}:links`, key);- pipeline.zrem(`${domain}:links:timestamps${userId ? `:${userId}` : ""}`, key);- pipeline.del(`${domain}:clicks:${key}`);- return await pipeline.exec();-}-/*** Get the usage for a project**/diff --git a/lib/utils.ts b/lib/utils.tsindex d44d7111f3..c8601b10da 100644--- a/lib/utils.ts+++ b/lib/utils.ts@@ -1,5 +1,5 @@import ms from "ms";-import { ccTLDs, secondLevelDomains } from "./constants";+import { SPECIAL_APEX_DOMAINS, ccTLDs, secondLevelDomains } from "./constants";interface SWRError extends Error {status: number;@@ -108,9 +108,9 @@ export const getDescriptionFromUrl = async (url: string) => {return description;};-export const timeAgo = (timestamp: number): string => {+export const timeAgo = (timestamp: Date): string => {if (!timestamp) return "never";- return `${ms(Date.now() - timestamp)} ago`;+ return `${ms(Date.now() - new Date(timestamp).getTime())} ago`;};export const generateSlugFromName = (name: string) => {@@ -181,6 +181,9 @@ export const getApexDomain = (url: string) => {} catch (e) {return "";}+ // special apex domains (e.g. youtu.be)+ if (SPECIAL_APEX_DOMAINS[domain]) return SPECIAL_APEX_DOMAINS[domain];+const parts = domain.split(".");if (parts.length > 2) {// if this is a second-level TLD (e.g. co.uk, .com.ua, .org.tt), we need to return the last 3 partsdiff --git a/pages/api/auth/decrypt-password.ts b/pages/api/auth/decrypt-password.tsindex 09a219a20a..a84791429d 100644--- a/pages/api/auth/decrypt-password.ts+++ b/pages/api/auth/decrypt-password.ts@@ -1,5 +1,6 @@import { NextApiRequest, NextApiResponse } from "next";import { compare } from "bcrypt";+import { serialize } from "cookie";import prisma from "@/lib/prisma";export default async function handler(@@ -14,6 +15,17 @@ export default async function handler(});const validPassword = await compare(password, passwordHash);if (validPassword) {+ // Set cookie to authenticate user for 1 week+ res.setHeader(+ "Set-Cookie",+ serialize("dub_authenticated", "1", {+ path: `/${key}`,+ maxAge: 60 * 60 * 24 * 7, // 1 week+ httpOnly: true,+ domain: process.env.NODE_ENV === "production" ? domain : null,+ secure: process.env.NODE_ENV === "production",+ }),+ );return res.status(200).json({ url });} else {return res.status(401).json({ error: "Invalid password" });diff --git a/pages/api/links/[key].ts b/pages/api/links/[key].tsdeleted file mode 100644index 657cfe4fb7..0000000000--- a/pages/api/links/[key].ts+++ /dev/null@@ -1,48 +0,0 @@-import { NextApiRequest, NextApiResponse } from "next";-import { getSession } from "@/lib/auth";-import { deleteLink, editLink, redis } from "@/lib/upstash";--export default async function handler(- req: NextApiRequest,- res: NextApiResponse,-) {- const session = await getSession(req, res);- const { key: oldKey } = req.query as { key: string };-- const isOwner = await redis.zscore(- `dub.sh:links:timestamps:${session.user.id}`,- oldKey,- );-- if (!session?.user.id || !isOwner) return res.status(401).end("Unauthorized");-- if (req.method === "PUT") {- let { key, url, title, timestamp } = req.body;- if (!key || !url || !title || !timestamp) {- return res- .status(400)- .json({ error: "Missing key or url or title or timestamp" });- }- const response = await editLink(- "dub.sh",- oldKey,- {- key,- url,- title,- timestamp,- },- session.user.id,- );- 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("dub.sh", oldKey, session.user.id);- return res.status(200).json(response);- } else {- res.setHeader("Allow", ["GET", "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.tsnew file mode 100644index 0000000000..ecd82ae25f--- /dev/null+++ b/pages/api/links/[key]/exists.ts@@ -0,0 +1,21 @@+import { NextApiRequest, NextApiResponse } from "next";+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` });+ }+ },+);diff --git a/pages/api/links/[key]/index.ts b/pages/api/links/[key]/index.tsnew file mode 100644index 0000000000..33daf363e0--- /dev/null+++ b/pages/api/links/[key]/index.ts@@ -0,0 +1,57 @@+import { NextApiRequest, NextApiResponse } from "next";+import { deleteLink, editLink } from "@/lib/api/links";+import { withUserAuth } from "@/lib/auth";+import prisma from "@/lib/prisma";++const domain = "dub.sh";++export default withUserAuth(+ async (req: NextApiRequest, res: NextApiResponse, userId: string) => {+ const { key: oldKey } = req.query as { key: string };++ const isOwner = await prisma.link+ .findUnique({+ where: {+ domain_key: {+ domain,+ key: oldKey,+ },+ },+ })+ .then((link) => link?.userId === userId);++ if (!isOwner) {+ return res.status(403).json({ error: "Not authorized" });+ }++ 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,+ userId,+ },+ oldKey,+ "dub",+ );+ 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", ["GET", "POST", "DELETE"]);+ return res+ .status(405)+ .json({ error: `Method ${req.method} Not Allowed` });+ }+ },+);diff --git a/pages/api/links/index.ts b/pages/api/links/index.tsindex aa36f96814..f71b776d03 100644--- a/pages/api/links/index.ts+++ b/pages/api/links/index.ts@@ -1,39 +1,40 @@import { NextApiRequest, NextApiResponse } from "next";-import { getSession } from "@/lib/auth";-import { addLink, getLinksForProject } from "@/lib/upstash";+import { addLink, getLinksForProject } from "@/lib/api/links";+import { withUserAuth } from "@/lib/auth";-// This is a special route for creating custom dub.sh links.+// This is a special route for retrieving and creating custom dub.sh links.-export default async function handler(- req: NextApiRequest,- res: NextApiResponse,-) {- const session = await getSession(req, res);- if (!session?.user.id) return res.status(401).end("Unauthorized");+export default withUserAuth(+ async (req: NextApiRequest, res: NextApiResponse, userId: string) => {+ // GET /api/links – get all dub.sh links created by the user+ if (req.method === "GET") {+ const response = await getLinksForProject({+ domain: "dub.sh",+ userId,+ });+ return res.status(200).json(response);- // GET /api/links – get all dub.sh links created by the user- if (req.method === "GET") {- const response = await getLinksForProject("dub.sh", session.user.id);- return res.status(200).json(response);+ // POST /api/links – create a new link+ } else if (req.method === "POST") {+ let { key, url } = req.body;+ if (!key || !url) {+ return res.status(400).json({ error: "Missing key or url" });+ }+ const response = await addLink({+ ...req.body,+ domain: "dub.sh",+ userId,+ });- // POST /api/links – create a new link- } else if (req.method === "POST") {- let { key, url, title } = req.body;- if (!url) {- return res.status(400).json({ error: "Missing url" });+ if (response === null) {+ return res.status(400).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` });}- const response = await addLink(- "dub.sh",- { url, key, title },- session.user.id,- );-- if (response === null) {- return res.status(400).json({ error: "Key already exists" });- }- return res.status(200).json({ key, url, title });- } else {- res.setHeader("Allow", ["GET", "POST"]);- return res.status(405).json({ error: `Method ${req.method} Not Allowed` });- }-}+ },+);diff --git a/pages/api/projects/[slug]/domains/[domain]/links/[key]/clicks.ts b/pages/api/projects/[slug]/domains/[domain]/links/[key]/clicks.tsindex b5408eca5b..53efe9a6a7 100644--- a/pages/api/projects/[slug]/domains/[domain]/links/[key]/clicks.ts+++ b/pages/api/projects/[slug]/domains/[domain]/links/[key]/clicks.ts@@ -1,14 +1,27 @@import { NextApiRequest, NextApiResponse } from "next";import { withProjectAuth } from "@/lib/auth";-import { getLinkClicksCount, redis } from "@/lib/upstash";+import prisma from "@/lib/prisma";+import { getLinkClicksCount } from "@/lib/upstash";export default withProjectAuth(async (req: NextApiRequest, res: NextApiResponse) => {// GET /api/projects/[slug]/domains/[domain]/links/[key]/clicks - get link clicksif (req.method === "GET") {const { domain, key } = req.query as { domain: string; key: string };- const response = await getLinkClicksCount(domain, key);- return res.status(200).json(response);+ const clicks = await getLinkClicksCount(domain, key);+ await prisma.link.update({+ where: {+ domain_key: {+ domain,+ key,+ },+ },+ data: {+ clicks,+ clicksUpdatedAt: new Date(),+ },+ });+ return res.status(200).json(clicks);} else {res.setHeader("Allow", ["GET"]);return resdiff --git a/pages/api/projects/[slug]/domains/[domain]/links/[key]/exists.ts b/pages/api/projects/[slug]/domains/[domain]/links/[key]/exists.tsindex 760d7f0d6d..fa62043258 100644--- a/pages/api/projects/[slug]/domains/[domain]/links/[key]/exists.ts+++ b/pages/api/projects/[slug]/domains/[domain]/links/[key]/exists.ts@@ -1,6 +1,6 @@import { NextApiRequest, NextApiResponse } from "next";+import { checkIfKeyExists } from "@/lib/api/links";import { withProjectAuth } from "@/lib/auth";-import { checkIfKeyExists } from "@/lib/upstash";export default withProjectAuth(async (req: NextApiRequest, res: NextApiResponse) => {diff --git a/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.ts b/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.tsindex 0d9fff0540..5ccdb14f2a 100644--- a/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.ts+++ b/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.ts@@ -1,10 +1,9 @@import { NextApiRequest, NextApiResponse } from "next";-import cloudinary from "cloudinary";+import { deleteLink, editLink } from "@/lib/api/links";import { withProjectAuth } from "@/lib/auth";-import { deleteLink, editLink } from "@/lib/upstash";export default withProjectAuth(- async (req: NextApiRequest, res: NextApiResponse) => {+ async (req: NextApiRequest, res: NextApiResponse, _, session) => {const {slug,domain,@@ -17,50 +16,27 @@ export default withProjectAuth(// PUT /api/projects/[slug]/domains/[domain]/links/[key] - edit a linkif (req.method === "PUT") {- let { key, url, title, timestamp, description, image } = req.body;- if (!key || !url || !title || !timestamp) {+ let { key, url } = req.body;+ if (!key || !url) {return res.status(400).json({ error: "Missing key or url or title or timestamp" });}- if (image) {- const { secure_url } = await cloudinary.v2.uploader.upload(image, {- public_id: key,- folder: domain,- overwrite: true,- invalidate: true,- });- image = secure_url;- if (key !== oldKey) {- await cloudinary.v2.uploader.destroy(`${domain}/${oldKey}`, {- invalidate: true,- });- }- }- const [response, _] = await Promise.all([- editLink(domain, oldKey, {- key,- url,- title,- timestamp,- description,- image,- }),- fetch(- `https://dub.sh/api/projects/${slug}/domains/${domain}/links/${oldKey}/revalidate?secret=${process.env.REVALIDATE_TOKEN}`,- ),- ]);+ const response = await editLink(+ {+ domain,+ ...req.body,+ userId: session.user.id,+ },+ oldKey,+ slug,+ );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 Promise.all([- deleteLink(domain, oldKey),- cloudinary.v2.uploader.destroy(`${domain}/${oldKey}`, {- invalidate: true,- }),- ]);+ const response = await deleteLink(domain, oldKey);return res.status(200).json(response);} else {res.setHeader("Allow", ["POST", "DELETE"]);diff --git a/pages/api/projects/[slug]/domains/[domain]/links/index.ts b/pages/api/projects/[slug]/domains/[domain]/links/index.tsindex 9e83b6996c..1a891702bc 100644--- a/pages/api/projects/[slug]/domains/[domain]/links/index.ts+++ b/pages/api/projects/[slug]/domains/[domain]/links/index.ts@@ -1,42 +1,30 @@import { NextApiRequest, NextApiResponse } from "next";-import cloudinary from "cloudinary";+import { addLink, getLinksForProject } from "@/lib/api/links";import { withProjectAuth } from "@/lib/auth";-import { addLink, getLinksForProject } from "@/lib/upstash";export default withProjectAuth(- async (req: NextApiRequest, res: NextApiResponse) => {+ async (req: NextApiRequest, res: NextApiResponse, _, session) => {// GET /api/projects/[slug]/domains/[domain]/links - Get all links for a projectif (req.method === "GET") {const { domain } = req.query as { domain: string };- const links = await getLinksForProject(domain);+ const links = await getLinksForProject({ domain });return res.status(200).json(links);// POST /api/projects/[slug]/domains/[domain]/links – create a new link} else if (req.method === "POST") {const { domain } = req.query as { domain: string };- let { key, url, title, description, image } = req.body;- if (!domain || !url) {- return res.status(400).json({ error: "Missing domain or url" });+ let { key, url } = req.body;+ if (!domain || !key || !url) {+ return res.status(400).json({ error: "Missing domain or url or key" });}- if (image) {- const { secure_url } = await cloudinary.v2.uploader.upload(image, {- folder: domain,- overwrite: true,- invalidate: true,- });- image = secure_url;- }- const response = await addLink(domain, {- url,- key,- title,- description,- image,+ const response = await addLink({+ ...req.body,+ userId: session.user.id,});if (response === null) {return res.status(400).json({ error: "Key already exists" });}- return res.status(200).json({ key, url, title });+ return res.status(200).json(response);} else {res.setHeader("Allow", ["GET", "POST"]);return resdiff --git a/pages/auth/[domain]/[key].tsx b/pages/auth/[domain]/[key].tsxindex 14b4068eab..1d2e2d66f0 100644--- a/pages/auth/[domain]/[key].tsx+++ b/pages/auth/[domain]/[key].tsx@@ -4,7 +4,6 @@ import { useState } from "react";import BlurImage from "@/components/shared/blur-image";import { AlertCircleFill, LoadingDots } from "@/components/shared/icons";import { FAVICON_FOLDER } from "@/lib/constants";-import prisma from "@/lib/prisma";const title = "Password Required";const description =@@ -21,6 +20,8 @@ export default function PasswordProtectedLinkPage() {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} />@@ -127,47 +128,3 @@ export default function PasswordProtectedLinkPage() {</>);}--export function getStaticPaths() {- return {- paths: [],- fallback: "blocking",- };-}--export async function getStaticProps(ctx) {- const { domain, key } = ctx.params as { domain: string; key: string };- const link = await prisma.link.findUnique({- where: {- domain_key: {- domain,- key,- },- },- select: {- url: true,- passwordHash: true,- },- });-- const { url, passwordHash } = link || {};-- if (!url) {- return {- notFound: true,- revalidate: 1,- };- } else if (!passwordHash) {- return {- redirect: {- destination: url,- },- revalidate: 1,- };- }-- return {- props: {},- revalidate: 1,- };-}diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex cde62883b4..72fb691230 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -149,12 +149,12 @@ model Link {@@unique([domain, key])// indices for links per domain/project- @@index([domain, createdAt(sort: Desc)])- @@index([domain, clicks(sort: Desc)])+ @@index([domain, archived, createdAt(sort: Desc)])+ @@index([domain, archived, clicks(sort: Desc)])- // indices for links per domain/project specific to a user (only for dub.sh)- @@index([domain, userId, createdAt(sort: Desc)])- @@index([domain, userId, clicks(sort: Desc)])+ // indices for links per domain/project specific to a user+ @@index([domain, archived, userId, createdAt(sort: Desc)])+ @@index([domain, archived, userId, clicks(sort: Desc)])// TODO: might wanna add indices for utm_source, utm_medium, utm_campaign}\ No newline at end of file