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.

improve link cloaking UX

Steven Tey3efc4dc7a88e
diff --git a/apps/web/app/api/links/iframeable/route.ts b/apps/web/app/api/links/iframeable/route.ts
new file mode 100644
index 0000000000..a58ea20eae
--- /dev/null
+++ b/apps/web/app/api/links/iframeable/route.ts
@@ -0,0 +1,45 @@
+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { getIdentityHash } from "@/lib/edge";
+import { ratelimit } from "@/lib/upstash";
+import {
+ getDomainQuerySchema,
+ getUrlQuerySchema,
+} from "@/lib/zod/schemas/links";
+import { isIframeable } from "@dub/utils";
+import { getToken } from "next-auth/jwt";
+import { NextRequest, NextResponse } from "next/server";
+
+export const runtime = "edge";
+
+export async function GET(req: NextRequest) {
+ try {
+ const { url, domain } = getUrlQuerySchema.and(getDomainQuerySchema).parse({
+ url: req.nextUrl.searchParams.get("url"),
+ domain: req.nextUrl.searchParams.get("domain"),
+ });
+
+ // Rate limit if user is not logged in
+ const session = await getToken({
+ req,
+ secret: process.env.NEXTAUTH_SECRET,
+ });
+ if (!session?.email) {
+ const identity_hash = await getIdentityHash(req);
+ const { success } = await ratelimit().limit(
+ `iframeable:${identity_hash}`,
+ );
+ if (!success) {
+ throw new DubApiError({
+ code: "rate_limit_exceeded",
+ message: "Don't DDoS me pls 🥺",
+ });
+ }
+ }
+
+ const iframeable = await isIframeable({ url, requestDomain: domain });
+
+ return NextResponse.json({ iframeable });
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
+}
diff --git a/apps/web/app/api/metatags/route.ts b/apps/web/app/api/metatags/route.ts
index 74c8b18ac3..d8647a0b9f 100644
--- a/apps/web/app/api/metatags/route.ts
+++ b/apps/web/app/api/metatags/route.ts
@@ -1,21 +1,16 @@
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { getIdentityHash } from "@/lib/edge";
import { ratelimit } from "@/lib/upstash";
-import z from "@/lib/zod";
-import { isValidUrl } from "@dub/utils";
+import { getUrlQuerySchema } from "@/lib/zod/schemas/links";
import { getToken } from "next-auth/jwt";
-import { NextRequest } from "next/server";
+import { NextRequest, NextResponse } from "next/server";
import { getMetaTags } from "./utils";
-import { getIdentityHash } from "@/lib/edge";
-
-const getMetaTagQuerySchema = z.object({
- url: z.string().refine((v) => isValidUrl(v), { message: "Invalid URL" }),
-});
export const runtime = "edge";
export async function GET(req: NextRequest) {
try {
- const { url } = getMetaTagQuerySchema.parse({
+ const { url } = getUrlQuerySchema.parse({
url: req.nextUrl.searchParams.get("url"),
});
@@ -36,10 +31,8 @@ export async function GET(req: NextRequest) {
}
const metatags = await getMetaTags(url);
- return new Response(JSON.stringify(metatags), {
- status: 200,
+ return NextResponse.json(metatags, {
headers: {
- "Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
});
diff --git a/apps/web/app/api/providers/route.ts b/apps/web/app/api/providers/route.ts
index c3af32ad11..f794625f41 100644
--- a/apps/web/app/api/providers/route.ts
+++ b/apps/web/app/api/providers/route.ts
@@ -1,86 +1,90 @@
+import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { getIdentityHash } from "@/lib/edge";
import { ratelimit } from "@/lib/upstash";
-import { fetchWithTimeout, getUrlFromString } from "@dub/utils";
+import { getUrlQuerySchema } from "@/lib/zod/schemas/links";
+import { fetchWithTimeout } from "@dub/utils";
import { getToken } from "next-auth/jwt";
import { NextRequest, NextResponse } from "next/server";
export const runtime = "edge";
export async function GET(req: NextRequest) {
- // Rate limit if user is not logged in
- const session = await getToken({
- req,
- secret: process.env.NEXTAUTH_SECRET,
- });
- if (!session?.email) {
- const identity_hash = await getIdentityHash(req);
- const { success } = await ratelimit().limit(`providers:${identity_hash}`);
- if (!success) {
- return new Response("Don't DDoS me pls 🥺", { status: 429 });
- }
- }
-
- const urlParam = req.nextUrl.searchParams.get("url");
- const url = getUrlFromString(urlParam || "");
- if (!url) {
- return new Response("Invalid URL", { status: 400 });
- }
-
- const urlObject = new URL(url);
-
- const domain = urlObject.hostname;
- const dns = await fetchWithTimeout(
- `https://dns.google/resolve?name=${domain}`,
- )
- .then((r) => r.json())
- .catch(() => null);
+ try {
+ const { url } = getUrlQuerySchema.parse({
+ url: req.nextUrl.searchParams.get("url"),
+ });
- if (
- dns &&
- dns.Answer &&
- dns.Answer.length > 0 &&
- dns.Answer.some(
- (a: { data: string }) =>
- a.data === "cname.bitly.com" ||
- a.data === "67.199.248.12" ||
- a.data === "67.199.248.13",
- )
- ) {
- return NextResponse.json({
- provider: "bitly",
+ // Rate limit if user is not logged in
+ const session = await getToken({
+ req,
+ secret: process.env.NEXTAUTH_SECRET,
});
- }
+ if (!session?.email) {
+ const identity_hash = await getIdentityHash(req);
+ const { success } = await ratelimit().limit(`providers:${identity_hash}`);
+ if (!success) {
+ return new Response("Don't DDoS me pls 🥺", { status: 429 });
+ }
+ }
- urlObject.pathname = "/xyz";
+ const urlObject = new URL(url);
- const headers = await fetchWithTimeout(urlObject.toString(), {
- redirect: "manual",
- })
- .then((r) => ({
- engine: r.headers.get("engine"),
- poweredBy: r.headers.get("x-powered-by"),
- }))
- .catch(() => null);
+ const domain = urlObject.hostname;
+ const dns = await fetchWithTimeout(
+ `https://dns.google/resolve?name=${domain}`,
+ )
+ .then((r) => r.json())
+ .catch(() => null);
- if (headers) {
- if (headers.engine?.includes("Rebrandly")) {
+ if (
+ dns &&
+ dns.Answer &&
+ dns.Answer.length > 0 &&
+ dns.Answer.some(
+ (a: { data: string }) =>
+ a.data === "cname.bitly.com" ||
+ a.data === "67.199.248.12" ||
+ a.data === "67.199.248.13",
+ )
+ ) {
return NextResponse.json({
- provider: "rebrandly",
+ provider: "bitly",
});
}
- if (headers.poweredBy?.includes("Short.io")) {
- return NextResponse.json({
- provider: "short",
- });
- }
- if (headers.poweredBy?.includes("Dub.co")) {
- return NextResponse.json({
- provider: "dub",
- });
+
+ urlObject.pathname = "/xyz";
+
+ const headers = await fetchWithTimeout(urlObject.toString(), {
+ redirect: "manual",
+ })
+ .then((r) => ({
+ engine: r.headers.get("engine"),
+ poweredBy: r.headers.get("x-powered-by"),
+ }))
+ .catch(() => null);
+
+ if (headers) {
+ if (headers.engine?.includes("Rebrandly")) {
+ return NextResponse.json({
+ provider: "rebrandly",
+ });
+ }
+ if (headers.poweredBy?.includes("Short.io")) {
+ return NextResponse.json({
+ provider: "short",
+ });
+ }
+ if (headers.poweredBy?.includes("Dub.co")) {
+ return NextResponse.json({
+ provider: "dub",
+ });
+ }
}
- }
- return NextResponse.json({
- provider: "unknown",
- });
+ return NextResponse.json({
+ provider: "unknown",
+ });
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
}
diff --git a/apps/web/app/rewrite/[url]/page.tsx b/apps/web/app/cloaked/[url]/page.tsx
similarity index 100%
rename from apps/web/app/rewrite/[url]/page.tsx
rename to apps/web/app/cloaked/[url]/page.tsx
diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.ts
index 4632178e9b..08a113b38f 100644
--- a/apps/web/lib/api/links.ts
+++ b/apps/web/lib/api/links.ts
@@ -19,6 +19,7 @@ import {
getParamsFromURL,
getUrlFromString,
isDubDomain,
+ isValidUrl,
linkConstructor,
truncate,
validKeyRegex,
@@ -319,7 +320,7 @@ export async function processLink({
};
}
const processedUrl = getUrlFromString(url);
- if (!processedUrl) {
+ if (!isValidUrl(processedUrl)) {
return {
link: payload,
error: "Invalid destination url.",
diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.ts
index 5556a64b05..fb555e25d6 100644
--- a/apps/web/lib/middleware/link.ts
+++ b/apps/web/lib/middleware/link.ts
@@ -150,7 +150,7 @@ export default async function LinkMiddleware(
} else if (rewrite) {
if (iframeable) {
return NextResponse.rewrite(
- new URL(`/rewrite/${encodeURIComponent(url)}`, req.url),
+ new URL(`/cloaked/${encodeURIComponent(url)}`, req.url),
DUB_HEADERS,
);
} else {
diff --git a/apps/web/lib/middleware/root.ts b/apps/web/lib/middleware/root.ts
index 4bcdf361b1..0713886f14 100644
--- a/apps/web/lib/middleware/root.ts
+++ b/apps/web/lib/middleware/root.ts
@@ -49,7 +49,7 @@ export default async function RootMiddleware(
if (rewrite) {
if (iframeable) {
return NextResponse.rewrite(
- new URL(`/rewrite/${encodeURIComponent(url)}`, req.url),
+ new URL(`/cloaked/${encodeURIComponent(url)}`, req.url),
DUB_HEADERS,
);
} else {
diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.ts
index b3a52fcb20..31c9fd98ee 100644
--- a/apps/web/lib/zod/schemas/links.ts
+++ b/apps/web/lib/zod/schemas/links.ts
@@ -1,7 +1,22 @@
import z from "@/lib/zod";
+import { getUrlFromString, isValidUrl, validDomainRegex } from "@dub/utils";
import { booleanQuerySchema } from ".";
import { TagSchema } from "./tags";
+export const getUrlQuerySchema = z.object({
+ url: z
+ .string()
+ .transform((v) => getUrlFromString(v))
+ .refine((v) => isValidUrl(v), { message: "Invalid URL" }),
+});
+
+export const getDomainQuerySchema = z.object({
+ domain: z
+ .string()
+ .min(1, "Missing required `domain` query parameter.")
+ .refine((v) => validDomainRegex.test(v), { message: "Invalid domain" }),
+});
+
const LinksQuerySchema = z.object({
domain: z
.string()
diff --git a/apps/web/ui/modals/add-edit-domain-modal/domain-input.tsx b/apps/web/ui/modals/add-edit-domain-modal/domain-input.tsx
index 14f2b07a8d..fa3c5b9700 100644
--- a/apps/web/ui/modals/add-edit-domain-modal/domain-input.tsx
+++ b/apps/web/ui/modals/add-edit-domain-modal/domain-input.tsx
@@ -37,7 +37,7 @@ export default function DomainInput({
const [domainType, setDomainType] = useState<string | undefined>(undefined);
const apexDomain = useMemo(
- () => getApexDomain(getUrlFromString(domain) || ""),
+ () => getApexDomain(getUrlFromString(domain)),
[domain],
);
diff --git a/apps/web/ui/modals/add-edit-link-modal/cloaking-section.tsx b/apps/web/ui/modals/add-edit-link-modal/cloaking-section.tsx
new file mode 100644
index 0000000000..7ad577ac47
--- /dev/null
+++ b/apps/web/ui/modals/add-edit-link-modal/cloaking-section.tsx
@@ -0,0 +1,159 @@
+import useWorkspace from "@/lib/swr/use-workspace";
+import { LinkProps } from "@/lib/types";
+import { AlertCircleFill, CheckCircleFill } from "@/ui/shared/icons";
+import {
+ InfoTooltip,
+ LoadingSpinner,
+ SimpleTooltipContent,
+ Switch,
+ TooltipContent,
+ useRouterStuff,
+} from "@dub/ui";
+import { FADE_IN_ANIMATION_SETTINGS, HOME_DOMAIN, fetcher } from "@dub/utils";
+import { motion } from "framer-motion";
+import { Dispatch, SetStateAction, useEffect, useState } from "react";
+import useSWR from "swr";
+
+export default function CloakingSection({
+ data,
+ setData,
+}: {
+ data: LinkProps;
+ setData: Dispatch<SetStateAction<LinkProps>>;
+}) {
+ const { plan } = useWorkspace();
+ const { queryParams } = useRouterStuff();
+
+ const { rewrite } = data;
+ const [enabled, setEnabled] = useState(rewrite);
+ useEffect(() => {
+ if (enabled) {
+ // if enabling, set rewrite to true or props.rewrite
+ setData({
+ ...data,
+ rewrite: true,
+ });
+ } else {
+ // if disabling, set rewrite to false
+ setData({ ...data, rewrite: false });
+ }
+ }, [enabled]);
+
+ return (
+ <div className="relative border-b border-gray-200 pb-5">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center justify-between space-x-2">
+ <h2 className="text-sm font-medium text-gray-900">Link Cloaking</h2>
+ <InfoTooltip
+ content={
+ <SimpleTooltipContent
+ title="Mask your destination URL so your users only see the short link in the browser address bar."
+ cta="Learn more."
+ href={`${HOME_DOMAIN}/help/article/link-cloaking`}
+ />
+ }
+ />
+ </div>
+ <Switch
+ fn={() => setEnabled(!enabled)}
+ checked={enabled}
+ // link cloaking is only available on Dub's Pro plan
+ {...((!plan || plan === "free") && !enabled
+ ? {
+ disabledTooltip: (
+ <TooltipContent
+ title={`Link cloaking is only available on ${process.env.NEXT_PUBLIC_APP_NAME}'s Pro plan. Upgrade to Pro to use this feature.`}
+ cta="Upgrade to Pro"
+ {...(plan === "free"
+ ? {
+ onClick: () =>
+ queryParams({
+ set: {
+ upgrade: "pro",
+ },
+ }),
+ }
+ : {
+ href: `${HOME_DOMAIN}/pricing`,
+ })}
+ />
+ ),
+ }
+ : {})}
+ />
+ </div>
+
+ {enabled && (
+ <motion.div className="mt-3 grid gap-2" {...FADE_IN_ANIMATION_SETTINGS}>
+ <div className="relative mt-1 flex aspect-[1200/630] w-full cursor-pointer items-center justify-center overflow-hidden rounded-md border border-gray-300 bg-white shadow-sm transition-all hover:bg-gray-50">
+ <iframe src={data.url} className="absolute z-10 h-full w-full" />
+ <LoadingSpinner />
+ </div>
+ <IframeIndicator url={data.url} domain={data.domain} />
+ </motion.div>
+ )}
+ </div>
+ );
+}
+
+function IframeIndicator({ url, domain }: { url: string; domain: string }) {
+ const { data, isLoading } = useSWR<{ iframeable: boolean }>(
+ `/api/links/iframeable?url=${url}&domain=${domain}`,
+ fetcher,
+ );
+
+ return (
+ <div className="flex items-start space-x-2 rounded-md border border-gray-300 bg-white p-3">
+ <div className="flex-none">
+ {isLoading ? (
+ <LoadingSpinner className="h-5 w-5" />
+ ) : data?.iframeable ? (
+ <CheckCircleFill className="h-5 w-5 text-green-500" />
+ ) : (
+ <AlertCircleFill className="h-5 w-5 text-yellow-500" />
+ )}
+ </div>
+ <div className="flex flex-col space-y-0.5">
+ <p className="text-sm font-semibold text-gray-700">
+ {!data || isLoading
+ ? "Checking if URL is iFrameable..."
+ : data.iframeable
+ ? "URL is iFrameable"
+ : "URL is not iFrameable"}
+ </p>
+ {data &&
+ (data.iframeable ? (
+ <p className="text-sm text-gray-600">
+ It will be cloaked successfully.{" "}
+ <a
+ href="https://dub.co/help/article/link-cloaking"
+ target="_blank"
+ className="text-gray-500 underline underline-offset-2 hover:text-gray-700"
+ >
+ Learn more.
+ </a>
+ </p>
+ ) : (
+ <p className="text-sm text-gray-600">
+ We will try to cloak it with{" "}
+ <a
+ href="https://nextjs.org/docs/pages/api-reference/functions/next-response#rewrite"
+ target="_blank"
+ className="text-gray-500 underline underline-offset-2 hover:text-gray-700"
+ >
+ Next.js Rewrites
+ </a>
+ , but it might not work as expected.{" "}
+ <a
+ href="https://dub.co/help/article/link-cloaking"
+ target="_blank"
+ className="text-gray-500 underline underline-offset-2 hover:text-gray-700"
+ >
+ Learn more.
+ </a>
+ </p>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/ui/modals/add-edit-link-modal/index.tsx b/apps/web/ui/modals/add-edit-link-modal/index.tsx
index 33239eea62..c2969d2dcc 100644
--- a/apps/web/ui/modals/add-edit-link-modal/index.tsx
+++ b/apps/web/ui/modals/add-edit-link-modal/index.tsx
@@ -45,6 +45,7 @@ import { toast } from "sonner";
import { mutate } from "swr";
import { useDebounce } from "use-debounce";
import AndroidSection from "./android-section";
+import CloakingSection from "./cloaking-section";
import CommentsSection from "./comments-section";
import ExpirationSection from "./expiration-section";
import GeoSection from "./geo-section";
@@ -52,7 +53,6 @@ import IOSSection from "./ios-section";
import OGSection from "./og-section";
import PasswordSection from "./password-section";
import Preview from "./preview";
-import RewriteSection from "./rewrite-section";
import TagsSection from "./tags-section";
import UTMSection from "./utm-section";
@@ -580,7 +580,7 @@ function AddEditLinkModal({
{...{ props, data, setData }}
generatingMetatags={generatingMetatags}
/>
- <RewriteSection {...{ data, setData }} />
+ <CloakingSection {...{ data, setData }} />
<PasswordSection {...{ props, data, setData }} />
<ExpirationSection {...{ props, data, setData }} />
<IOSSection {...{ props, data, setData }} />
diff --git a/apps/web/ui/modals/add-edit-link-modal/rewrite-section.tsx b/apps/web/ui/modals/add-edit-link-modal/rewrite-section.tsx
deleted file mode 100644
index 980f9cf23d..0000000000
--- a/apps/web/ui/modals/add-edit-link-modal/rewrite-section.tsx
+++ /dev/null
@@ -1,83 +0,0 @@
-import useWorkspace from "@/lib/swr/use-workspace";
-import { LinkProps } from "@/lib/types";
-import {
- InfoTooltip,
- SimpleTooltipContent,
- Switch,
- TooltipContent,
- useRouterStuff,
-} from "@dub/ui";
-import { HOME_DOMAIN } from "@dub/utils";
-import { Dispatch, SetStateAction, useEffect, useState } from "react";
-
-export default function RewriteSection({
- data,
- setData,
-}: {
- data: LinkProps;
- setData: Dispatch<SetStateAction<LinkProps>>;
-}) {
- const { plan } = useWorkspace();
- const { queryParams } = useRouterStuff();
-
- const { rewrite } = data;
- const [enabled, setEnabled] = useState(rewrite);
- useEffect(() => {
- if (enabled) {
- // if enabling, set rewrite to true or props.rewrite
- setData({
- ...data,
- rewrite: true,
- });
- } else {
- // if disabling, set rewrite to false
- setData({ ...data, rewrite: false });
- }
- }, [enabled]);
-
- return (
- <div className="relative border-b border-gray-200 pb-5">
- <div className="flex items-center justify-between">
- <div className="flex items-center justify-between space-x-2">
- <h2 className="text-sm font-medium text-gray-900">Link Cloaking</h2>
- <InfoTooltip
- content={
- <SimpleTooltipContent
- title="Mask your destination URL so your users only see the short link in the browser address bar."
- cta="Learn more."
- href={`${HOME_DOMAIN}/help/article/link-cloaking`}
- />
- }
- />
- </div>
- <Switch
- fn={() => setEnabled(!enabled)}
- checked={enabled}
- // link cloaking is only available on Dub's Pro plan
- {...((!plan || plan === "free") && !enabled
- ? {
- disabledTooltip: (
- <TooltipContent
- title={`Link cloaking is only available on ${process.env.NEXT_PUBLIC_APP_NAME}'s Pro plan. Upgrade to Pro to use this feature.`}
- cta="Upgrade to Pro"
- {...(plan === "free"
- ? {
- onClick: () =>
- queryParams({
- set: {
- upgrade: "pro",
- },
- }),
- }
- : {
- href: `${HOME_DOMAIN}/pricing`,
- })}
- />
- ),
- }
- : {})}
- />
- </div>
- </div>
- );
-}
diff --git a/packages/utils/src/functions/is-iframeable.ts b/packages/utils/src/functions/is-iframeable.ts
index c034958233..d9d723091e 100644
--- a/packages/utils/src/functions/is-iframeable.ts
+++ b/packages/utils/src/functions/is-iframeable.ts
@@ -17,8 +17,8 @@ export const isIframeable = async ({
return false;
}
- const xFrameOptions = res.headers.get("X-Frame-Options"); // returns null if there is no `X-Frame-Options` header
- if (xFrameOptions) {
+ const xFrameOptions = res.headers.get("X-Frame-Options");
+ if (xFrameOptions === "DENY" || xFrameOptions === "SAMEORIGIN") {
return false;
}
diff --git a/packages/utils/src/functions/urls.ts b/packages/utils/src/functions/urls.ts
index ff43e27883..72132bed13 100644
--- a/packages/utils/src/functions/urls.ts
+++ b/packages/utils/src/functions/urls.ts
@@ -13,9 +13,8 @@ export const getUrlFromString = (str: string) => {
if (str.includes(".") && !str.includes(" ")) {
return new URL(`https://${str}`).toString();
}
- } catch (e) {
- return null;
- }
+ } catch (_) {}
+ return "";
};
export const getSearchParams = (url: string) => {