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.

Added warning for changing short links and project domains

Steven Tey4ffb82918fbe
diff --git a/README.md b/README.md
index 1911367b5f..454481d346 100644
--- a/README.md
+++ b/README.md
@@ -68,6 +68,7 @@ You can deploy your own hosted version of Dub for greater privacy & control. Jus
- [Typescript](https://www.typescriptlang.org/) – language
- [Tailwind](https://tailwindcss.com/) – CSS
- [Upstash](https://upstash.com/) – redis
+- [Tinybird](https://tinybird.com/) – analytics
- [Planetscale](https://planetscale.com/) – database
- [NextAuth.js](https://next-auth.js.org/) – auth
- [Vercel](https://vercel.com/) – hosting
@@ -77,11 +78,9 @@ You can deploy your own hosted version of Dub for greater privacy & control. Jus
Dub is built as a standard Next.js application with [Middleware](https://nextjs.org/docs/advanced-features/middleware) to handle multi-tenancy, inspired by [the Vercel Platforms Starter Kit](https://github.com/vercel/platforms).
-[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:
+[Redis](https://redis.io/) is used as the caching layer for all short links.
-- `{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 domain (e.g. `dub.sh:root:clicks`)
+[Clickhouse](https://clickhouse.com/) ([Tinybird](https://tinybird.com/)) is used as the analytics database for storing link click data.
[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/modals/add-edit-link-modal/index.tsx b/components/app/modals/add-edit-link-modal/index.tsx
index d212e4d8a5..7aaf11976c 100644
--- a/components/app/modals/add-edit-link-modal/index.tsx
+++ b/components/app/modals/add-edit-link-modal/index.tsx
@@ -15,6 +15,7 @@ import {
AlertCircleFill,
LoadingCircle,
LoadingDots,
+ Lock,
Random,
X,
} from "@/components/shared/icons";
@@ -98,27 +99,6 @@ function AddEditLinkModal({
setGeneratingSlug(false);
}, []);
- // const onPaste = useCallback(
- // (e: React.ClipboardEvent<HTMLInputElement>) => {
- // if (props) return;
- // const url = e.clipboardData.getData("text");
- // setShowAddEditLinkModal(true);
- // try {
- // new URL(url);
- // console.log(url);
- // setData((prev) => ({ ...prev, url }));
- // } catch (e) {
- // console.log("not a valid url");
- // }
- // },
- // [props, showAddEditLinkModal, setData],
- // );
-
- // useEffect(() => {
- // window.addEventListener("paste", onPaste as any);
- // return () => window.removeEventListener("paste", onPaste as any);
- // }, [onPaste]);
-
const [generatingMetatags, setGeneratingMetatags] = useState(
props ? true : false,
);
@@ -230,6 +210,13 @@ function AddEditLinkModal({
const randomIdx = Math.floor(Math.random() * 100);
+ const [lockKey, setLockKey] = useState(false);
+ useEffect(() => {
+ if (props?.key) {
+ setLockKey(true);
+ }
+ }, [props?.key]);
+
return (
<Modal
showModal={showAddEditLinkModal}
@@ -359,45 +346,65 @@ function AddEditLinkModal({
>
Short Link
</label>
- <button
- className="flex items-center space-x-2 text-sm text-gray-500 transition-all duration-75 hover:text-black active:scale-95"
- onClick={generateRandomSlug}
- disabled={generatingSlug}
- type="button"
- >
- {generatingSlug ? (
- <LoadingCircle />
- ) : (
- <Random className="h-3 w-3" />
- )}
- <p>{generatingSlug ? "Generating" : "Randomize"}</p>
- </button>
+ {lockKey ? (
+ <button
+ className="flex items-center space-x-2 text-sm text-gray-500 transition-all duration-75 hover:text-black active:scale-95"
+ type="button"
+ onClick={() => {
+ window.confirm(
+ "Editing an existing short link will result in broken links and reset its analytics. Are you sure you want to continue?",
+ ) && setLockKey(false);
+ }}
+ >
+ <Lock className="h-3 w-3" />
+ <p>Unlock</p>
+ </button>
+ ) : (
+ <button
+ className="flex items-center space-x-2 text-sm text-gray-500 transition-all duration-75 hover:text-black active:scale-95"
+ onClick={generateRandomSlug}
+ disabled={generatingSlug}
+ type="button"
+ >
+ {generatingSlug ? (
+ <LoadingCircle />
+ ) : (
+ <Random className="h-3 w-3" />
+ )}
+ <p>{generatingSlug ? "Generating" : "Randomize"}</p>
+ </button>
+ )}
</div>
<div className="relative mt-1 flex rounded-md shadow-sm">
<span className="inline-flex items-center whitespace-nowrap rounded-l-md border border-r-0 border-gray-300 bg-gray-50 px-5 text-sm text-gray-500">
{domain || "dub.sh"}
</span>
- <input
- type="text"
- name="key"
- id={`key-${randomIdx}`}
- required
- autoFocus={false}
- 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
- ? "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);
- setData({ ...data, key: e.target.value });
- }}
- aria-invalid="true"
- aria-describedby="key-error"
- />
+ {lockKey ? (
+ <div className="block w-full cursor-not-allowed select-none rounded-r-md border border-gray-300 bg-gray-100 px-3 py-2 text-sm text-gray-500">
+ {props.key}
+ </div>
+ ) : (
+ <input
+ type="text"
+ 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)
+ className={`${
+ keyExistsError
+ ? "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);
+ setData({ ...data, key: e.target.value });
+ }}
+ aria-invalid="true"
+ aria-describedby="key-error"
+ />
+ )}
{keyExistsError && (
<div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
<AlertCircleFill
diff --git a/components/app/modals/edit-domain-modal.tsx b/components/app/modals/edit-domain-modal.tsx
index b71026042a..5b0805cfed 100644
--- a/components/app/modals/edit-domain-modal.tsx
+++ b/components/app/modals/edit-domain-modal.tsx
@@ -61,7 +61,7 @@ function EditDomainModal({
<h3 className="text-lg font-medium">Change Domain</h3>
<p className="text-center text-sm text-gray-500">
Warning: Changing your project's domain will break all existing
- short links.
+ short links and reset their analytics.
</p>
</div>
diff --git a/components/app/settings/custom-domain/domain-configuration.tsx b/components/app/settings/custom-domain/domain-configuration.tsx
index a065ff1973..3dea794721 100644
--- a/components/app/settings/custom-domain/domain-configuration.tsx
+++ b/components/app/settings/custom-domain/domain-configuration.tsx
@@ -25,12 +25,12 @@ export default function DomainConfiguration({
);
return (
<div className="border-t border-gray-200 pt-5">
- <p className="mb-5 text-sm">
+ <p className="text-sm">
Please set the following TXT record on{" "}
<InlineSnippet>{domainJson.apexName}</InlineSnippet> to prove
ownership of <InlineSnippet>{domainJson.name}</InlineSnippet>:
</p>
- <div className="flex items-start justify-start space-x-10 rounded-md bg-gray-50 p-2">
+ <div className="my-5 flex items-start justify-start space-x-10 rounded-md bg-gray-50 p-2">
<div>
<p className="text-sm font-bold">Type</p>
<p className="mt-2 font-mono text-sm">{txtVerification.type}</p>
@@ -51,6 +51,11 @@ export default function DomainConfiguration({
</p>
</div>
</div>
+ <p className="text-sm">
+ Warning: if you are using this domain for another site, setting this
+ TXT record will transfer domain ownership away from that site and
+ break it. Please exercise caution when setting this record.
+ </p>
</div>
);
}
@@ -118,7 +123,7 @@ export default function DomainConfiguration({
<p className="mt-2 font-mono text-sm">86400</p>
</div>
</div>
- <p className="mt-3 text-sm">
+ <p className="mt-5 text-sm">
Note: for TTL, if <InlineSnippet>86400</InlineSnippet> is not
available, set the highest value possible. Also, domain propagation
can take up to an hour.
diff --git a/lib/api/links.ts b/lib/api/links.ts
index f1f75bf5d0..8e9761b66d 100644
--- a/lib/api/links.ts
+++ b/lib/api/links.ts
@@ -4,7 +4,6 @@ import prisma from "@/lib/prisma";
import { LinkProps } from "@/lib/types";
import { redis } from "@/lib/upstash";
import { getParamsFromURL, nanoid, truncate } from "@/lib/utils";
-import { getLinksByClicks } from "../tinybird";
const getFiltersFromStatus = (status: string) => {
if (status === "all" || status === "none") {
@@ -277,9 +276,6 @@ export async function editLink(link: LinkProps, oldKey: string) {
})
.catch(() => {}),
redis.del(`${domain}:${oldKey}`),
- redis
- .rename(`${domain}:clicks:${oldKey}`, `${domain}:clicks:${key}`)
- .catch(() => {}),
]
: []),
]);
@@ -313,7 +309,6 @@ export async function deleteLink(domain: string, key: string) {
invalidate: true,
}),
redis.del(`${domain}:${key}`),
- redis.del(`${domain}:clicks:${key}`),
]);
}
@@ -349,10 +344,8 @@ export async function changeDomainForLinks(
},
});
const pipeline = redis.pipeline();
- pipeline.rename(`${domain}:root:clicks`, `${newDomain}:root:clicks`);
links.forEach(({ key }) => {
pipeline.rename(`${domain}:${key}`, `${newDomain}:${key}`);
- pipeline.rename(`${domain}:clicks:${key}`, `${newDomain}:clicks:${key}`);
});
try {
return await pipeline.exec();
@@ -401,10 +394,8 @@ export async function deleteProjectLinks(domain: string) {
},
});
const pipeline = redis.pipeline();
- pipeline.del(`${domain}:root:clicks`);
links.forEach(({ key }) => {
pipeline.del(`${domain}:${key}`);
- pipeline.del(`${domain}:clicks:${key}`);
});
try {
return await pipeline.exec();
diff --git a/lib/cron/domains.tsx b/lib/cron/domains.tsx
index 9c1cd078d3..408ccc5bc6 100644
--- a/lib/cron/domains.tsx
+++ b/lib/cron/domains.tsx
@@ -6,6 +6,7 @@ import { removeDomain } from "@/lib/domains";
import prisma from "@/lib/prisma";
import { deleteProjectLinks } from "@/lib/api/links";
import { redis } from "@/lib/upstash";
+import { getClicks } from "../tinybird";
export const handleDomainUpdates = async (
projectSlug: string,
@@ -42,13 +43,9 @@ export const handleDomainUpdates = async (
}
if (invalidDays >= 30) {
- const existingLinks = await prisma.link.findMany({
- where: {
- domain,
- },
- });
- if (existingLinks.length === 0) {
- // only delete if there are no resources recorded (links, stats, etc.)
+ const clicks = await getClicks({ domain });
+ if (clicks === 0) {
+ // only delete if there are no clicks recorded in Tinybird
const ownerEmail = await getProjectOwnerEmail(projectSlug);
return await Promise.all([
prisma.project.delete({
diff --git a/lib/tinybird.ts b/lib/tinybird.ts
index 99b1c7cb2d..d6c5fb8b1c 100644
--- a/lib/tinybird.ts
+++ b/lib/tinybird.ts
@@ -92,18 +92,3 @@ export async function getClicks({
}
return clicks;
}
-
-export async function getLinksByClicks(domain: string) {
- const response = await fetch(
- `https://api.us-east.tinybird.co/v0/pipes/links.json?domain=${domain}`,
- {
- headers: {
- Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,
- },
- },
- )
- .then((res) => res.json())
- .then((res) => res.data);
-
- return response;
-}
diff --git a/lib/upstash.ts b/lib/upstash.ts
index 0810680143..1bb22b8d8e 100644
--- a/lib/upstash.ts
+++ b/lib/upstash.ts
@@ -36,18 +36,6 @@ export async function setRandomKey(
// by the off chance that key already exists
return setRandomKey(url);
} else {
- const pipeline = redis.pipeline();
- pipeline.zadd(`dub.sh:clicks:${key}`, {
- score: Date.now(),
- member: {
- geo: LOCALHOST_GEO_DATA,
- ua: "Dub-Bot",
- referer: "https://dub.sh",
- timestamp: Date.now(),
- },
- });
- pipeline.expire(`dub.sh:clicks:${key}`, 30 * 60); // 30 minutes
- await pipeline.exec();
return { response, key };
}
}
@@ -66,10 +54,3 @@ export async function recordMetatags(url: string, error: boolean) {
});
}
}
-
-export async function getLinkClicksCount(domain: string, key: string) {
- const start = Date.now() - 2629746000; // 30 days ago
- return (
- (await redis.zcount(`${domain}:clicks:${key}`, start, Date.now())) || 0
- );
-}