The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Convert Redis from string to hash
Steven Tey5cf2576bd34b
diff --git a/apps/web/app/api/cron/links/event/route.ts b/apps/web/app/api/cron/links/event/route.tsindex 2ef675fdc1..678ae8493d 100644--- a/apps/web/app/api/cron/links/event/route.ts+++ b/apps/web/app/api/cron/links/event/route.ts@@ -1,6 +1,7 @@import { limiter, qstash, receiver } from "@/lib/cron";import prisma from "@/lib/prisma";import { ProjectProps } from "@/lib/types";+import { getRedisLink, redis } from "@/lib/upstash";import {APP_DOMAIN_WITH_NGROK,GOOGLE_FAVICON_URL,@@ -66,16 +67,22 @@ export async function POST(req: Request) {// increment links usage and send alert if neededif (type === "create" && link.projectId) {- const project = await prisma.project.update({- where: {- id: link.projectId,- },- data: {- linksUsage: {- increment: 1,+ const [project, _redisLink] = await Promise.all([+ prisma.project.update({+ where: {+ id: link.projectId,},- },- });+ data: {+ linksUsage: {+ increment: 1,+ },+ },+ }),+ // set the index in redis again cause we don't have the linkId the first time+ redis.hset(link.domain, {+ [link.key.toLowerCase()]: await getRedisLink(link),+ }),+ ]);const percentage = Math.round((project.linksUsage / project.linksLimit) * 100,diff --git a/apps/web/app/banned/[domain]/[key]/page.tsx b/apps/web/app/banned/[domain]/[key]/page.tsxindex c6e7772ad2..aed8c78cf4 100644--- a/apps/web/app/banned/[domain]/[key]/page.tsx+++ b/apps/web/app/banned/[domain]/[key]/page.tsx@@ -1,8 +1,6 @@-import { getLinkViaEdge } from "@/lib/planetscale";import { Background, Footer, Nav } from "@dub/ui";import { constructMetadata } from "@dub/utils";import { ShieldBan } from "lucide-react";-import { notFound } from "next/navigation";export const runtime = "edge";@@ -12,21 +10,7 @@ export const metadata = constructMetadata({noIndex: true,});-export default async function BannedPage({- params,-}: {- params: { domain: string; key: string };-}) {- const domain = params.domain;- const key = decodeURIComponent(params.key);-- const data = await getLinkViaEdge(domain, key);-- // if the link doesn't exist- if (!data) {- notFound();- }-+export default async function BannedPage() {return (<main className="flex min-h-screen flex-col justify-between"><Nav />diff --git a/apps/web/app/expired/[domain]/[key]/page.tsx b/apps/web/app/expired/[domain]/[key]/page.tsxindex b9c99c24a1..0367679e91 100644--- a/apps/web/app/expired/[domain]/[key]/page.tsx+++ b/apps/web/app/expired/[domain]/[key]/page.tsx@@ -1,8 +1,6 @@-import { getLinkViaEdge } from "@/lib/planetscale";import { Background, Footer, Nav } from "@dub/ui";import { constructMetadata } from "@dub/utils";import { TimerOff } from "lucide-react";-import { notFound } from "next/navigation";export const runtime = "edge";@@ -13,21 +11,7 @@ export const metadata = constructMetadata({noIndex: true,});-export default async function ExpiredPage({- params,-}: {- params: { domain: string; key: string };-}) {- const domain = params.domain;- const key = decodeURIComponent(params.key);-- const data = await getLinkViaEdge(domain, key);-- // if the link doesn't exist- if (!data) {- notFound();- }-+export default async function ExpiredPage() {return (<main className="flex min-h-screen flex-col justify-between"><Nav />diff --git a/apps/web/app/inspect/[domain]/[key]/page.tsx b/apps/web/app/inspect/[domain]/[key]/page.tsxindex 1d6c7fa98c..1d9a60e075 100644--- a/apps/web/app/inspect/[domain]/[key]/page.tsx+++ b/apps/web/app/inspect/[domain]/[key]/page.tsx@@ -6,10 +6,16 @@ import {LinkPreviewPlaceholder,Nav,} from "@dub/ui";-import { HOME_DOMAIN, constructMetadata } from "@dub/utils";+import {+ GOOGLE_FAVICON_URL,+ HOME_DOMAIN,+ constructMetadata,+ getApexDomain,+} from "@dub/utils";import { notFound } from "next/navigation";import LinkInspectorCard from "./card";import { Suspense } from "react";+import { unescape } from "html-escaper";export const runtime = "edge";@@ -27,11 +33,13 @@ export async function generateMetadata({return;}+ const apexDomain = getApexDomain(data.url);+return constructMetadata({- title:- "Link Inspector - Inspect a Short Link on Dub to Make Sure It's Safe",- description:- "Dub's Link Inspector is a simple tool for inspecting short links on Dub to make sure it's safe to click on. If you think this link is malicious, please report it.",+ title: unescape(data.title),+ description: unescape(data.description),+ image: unescape(data.image),+ icons: `${GOOGLE_FAVICON_URL}${unescape(apexDomain)}`,noIndex: true,});}diff --git a/apps/web/app/protected/[domain]/[key]/action.ts b/apps/web/app/protected/[domain]/[key]/action.tsindex 50fa304739..9362db66c3 100644--- a/apps/web/app/protected/[domain]/[key]/action.ts+++ b/apps/web/app/protected/[domain]/[key]/action.ts@@ -1,4 +1,5 @@"use server";+import { getLinkViaEdge } from "@/lib/planetscale";import prisma from "@/lib/prisma";import { linkConstructor } from "@dub/utils";import { redirect } from "next/navigation";@@ -9,10 +10,7 @@ export async function verifyPassword(data: FormData) {const key = decodeURIComponent(rawKey);const password = data.get("password") as string;- const link = await prisma.link.findUnique({- where: { domain_key: { domain, key } },- select: { url: true, password: true },- });+ const link = await getLinkViaEdge(domain, key);if (!link) {return { error: "Link not found" };}diff --git a/apps/web/lib/api/domains.ts b/apps/web/lib/api/domains.tsindex ba2f0b14da..680d991c67 100644--- a/apps/web/lib/api/domains.ts+++ b/apps/web/lib/api/domains.ts@@ -3,10 +3,10 @@ import { redis } from "@/lib/upstash";import {getApexDomain,getDomainWithoutWWW,+ isIframeable,validDomainRegex,} from "@dub/utils";import cloudinary from "cloudinary";-import { isIframeable } from "../middleware/utils";export const validateDomain = async (domain: string) => {if (!domain || typeof domain !== "string") {diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.tsindex f286ca7c92..335f976502 100644--- a/apps/web/lib/api/links.ts+++ b/apps/web/lib/api/links.ts@@ -5,7 +5,7 @@ import {isReservedUsername,} from "@/lib/edge-config";import prisma from "@/lib/prisma";-import { redis } from "@/lib/upstash";+import { getRedisLink, redis } from "@/lib/upstash";import {DEFAULT_REDIRECTS,DUB_DOMAINS,@@ -14,14 +14,14 @@ import {getParamsFromURL,getUrlFromString,isDubDomain,+ isIframeable,linkConstructor,nanoid,truncate,validKeyRegex,} from "@dub/utils";import cloudinary from "cloudinary";-import { isIframeable } from "../middleware/utils";-import { LinkProps, ProjectProps } from "../types";+import { LinkProps, ProjectProps, RedisLinkProps } from "../types";import { Session } from "../auth";import { getLinkViaEdge } from "../planetscale";@@ -436,25 +436,7 @@ export async function addLink(link: LinkProps) {geo: geo || undefined,},}),- redis.set(- `${domain}:${key}`,- {- url: encodeURIComponent(url),- password: hasPassword,- proxy,- ...(rewrite && {- rewrite: true,- iframeable: await isIframeable({ url, requestDomain: domain }),- }),- ...(expiresAt && { expiresAt }),- ...(ios && { ios }),- ...(android && { android }),- ...(geo && { geo }),- },- {- nx: true,- },- ),+ redis.hsetnx(domain, key.toLowerCase(), await getRedisLink(link)),]);if (proxy && image) {@@ -484,20 +466,23 @@ export async function addLink(link: LinkProps) {export async function bulkCreateLinks(links: LinkProps[]) {if (links.length === 0) return [];++ // split links into domains+ const linksByDomain: Record<string, Record<string, RedisLinkProps>> = {};+ links.forEach(async (link) => {+ const { domain, key } = link;++ if (!linksByDomain[domain]) {+ linksByDomain[domain] = {};+ }+ // this technically will be a synchronous function since isIframeable won't be run for bulk link creation+ linksByDomain[domain][key.toLowerCase()] = await getRedisLink(link);+ });+const pipeline = redis.pipeline();- links.forEach(({ domain, key, url, password, expiresAt }) => {- const hasPassword = password && password.length > 0 ? true : false;- pipeline.set(- `${domain}:${key}`,- {- url: encodeURIComponent(url),- password: hasPassword,- ...(expiresAt && { expiresAt }),- },- {- nx: true,- },- );++ Object.entries(linksByDomain).forEach(([domain, links]) => {+ pipeline.hset(domain, links);});await Promise.all([@@ -617,18 +602,8 @@ export async function editLink({: cloudinary.v2.uploader.destroy(`${domain}/${key}`, {invalidate: true,}),- redis.set(`${domain}:${key}`, {- url: encodeURIComponent(url),- password: hasPassword,- proxy,- ...(rewrite && {- rewrite: true,- iframeable: await isIframeable({ url, requestDomain: domain }),- }),- ...(expiresAt && { expiresAt }),- ...(ios && { ios }),- ...(android && { android }),- ...(geo && { geo }),+ redis.hset(domain, {+ [key.toLowerCase()]: await getRedisLink(updatedLink),}),// if key is changed: rename resource in Cloudinary, delete the old key in Redis and change the clicks key name...(changedDomain || changedKeydiff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.tsindex 1ba5d13489..e619c85c19 100644--- a/apps/web/lib/middleware/link.ts+++ b/apps/web/lib/middleware/link.ts@@ -1,7 +1,12 @@import { detectBot, getFinalUrl, parse } from "@/lib/middleware/utils";import { recordClick } from "@/lib/tinybird";-import { ratelimit, redis } from "@/lib/upstash";-import { DUB_HEADERS, LOCALHOST_GEO_DATA, LOCALHOST_IP } from "@dub/utils";+import { getRedisLink, ratelimit, redis } from "@/lib/upstash";+import {+ DUB_HEADERS,+ LEGAL_PROJECT_ID,+ LOCALHOST_GEO_DATA,+ LOCALHOST_IP,+} from "@dub/utils";import { ipAddress } from "@vercel/edge";import {NextFetchEvent,@@ -11,18 +16,21 @@ import {} from "next/server";import { isBlacklistedReferrer } from "../edge-config";import { getLinkViaEdge } from "../planetscale";-import { RedisLinkProps } from "../types";+import { LinkProps, RedisDomainMetadataProps, RedisLinkProps } from "../types";export default async function LinkMiddleware(req: NextRequest,ev: NextFetchEvent,) {- const { domain, fullKey: key } = parse(req);+ let { domain, fullKey: key } = parse(req);if (!domain || !key) {return NextResponse.next();}+ // links on Dub are case insensitive by default+ key = key.toLowerCase();+if (process.env.NODE_ENV !== "development" &&domain === "dub.sh" &&@@ -42,13 +50,50 @@ export default async function LinkMiddleware(}const inspectMode = key.endsWith("+");+ if (inspectMode) {+ key = key.slice(0, -1);+ }- const response = await redis.get<RedisLinkProps>(+ const response = await redis.hmget<+ Record<string, RedisDomainMetadataProps | RedisLinkProps>+ >(+ domain,+ "_metadata",// if inspect mode is enabled, remove the trailing `+` from the key- `${domain}:${inspectMode ? key.slice(0, -1) : key}`,+ key,);+ let metadata = response+ ? (response._metadata as RedisDomainMetadataProps)+ : null;++ let link = response ? (response[key] as RedisLinkProps) : null;++ if (!metadata || !link) {+ const linkData = await getLinkViaEdge(domain, key);++ if (!linkData) {+ // short link not found, redirect to root+ return NextResponse.redirect(new URL("/", req.url), DUB_HEADERS);+ }++ let setMetadata = false;+ if (!metadata) {+ setMetadata = true;+ metadata = {+ projectId: linkData.projectId,+ };+ }+ link = await getRedisLink(linkData as any);++ await redis.hset(domain, {+ ...(setMetadata && { _metadata: metadata }),+ [key]: link,+ });+ }+const {+ id,url: target,password,proxy,@@ -58,98 +103,88 @@ export default async function LinkMiddleware(ios,android,geo,- banned,- } = response || {};+ } = link;- if (target) {- // only show inspect modal if the link is not password protected- if (inspectMode && !password) {- return NextResponse.rewrite(- new URL(`/inspect/${domain}/${encodeURIComponent(key)}`, req.url),- );- }+ // only show inspect modal if the link is not password protected+ if (inspectMode && !password) {+ return NextResponse.rewrite(+ new URL(`/inspect/${domain}/${encodeURIComponent(key)}+`, req.url),+ );+ }- // if the link is password protected- if (password) {- const pw = req.nextUrl.searchParams.get("pw");-- // rewrite to auth page (/protected/[domain]/[key]) if:- // - no `pw` param is provided- // - the `pw` param is incorrect- // this will also ensure that no clicks are tracked unless the password is correct- if (!pw || (await getLinkViaEdge(domain, key))?.password !== pw) {- return NextResponse.rewrite(- new URL(`/protected/${domain}/${encodeURIComponent(key)}`, req.url),- );- } else if (pw) {- // strip it from the URL if it's correct- req.nextUrl.searchParams.delete("pw");- }- }+ // if the link is password protected+ if (password) {+ const pw = req.nextUrl.searchParams.get("pw");- // if the link is banned- if (banned) {+ // rewrite to auth page (/protected/[domain]/[key]) if:+ // - no `pw` param is provided+ // - the `pw` param is incorrect+ // this will also ensure that no clicks are tracked unless the password is correct+ if (!pw || (await getLinkViaEdge(domain, key))?.password !== pw) {return NextResponse.rewrite(- new URL(`/banned/${domain}/${encodeURIComponent(key)}`, req.url),+ new URL(`/protected/${domain}/${encodeURIComponent(key)}`, req.url),);+ } else if (pw) {+ // strip it from the URL if it's correct+ req.nextUrl.searchParams.delete("pw");}+ }- // if the link has expired- if (expiresAt && new Date(expiresAt) < new Date()) {- return NextResponse.rewrite(- new URL(`/expired/${domain}/${encodeURIComponent(key)}`, req.url),- );- }+ // if the link is banned+ if (metadata.projectId === LEGAL_PROJECT_ID) {+ return NextResponse.rewrite(new URL("/banned", req.url));+ }- // only track the click when there is no `dub-no-track` header- if (!req.headers.get("dub-no-track")) {- ev.waitUntil(recordClick({ req, domain, key }));- }+ // if the link has expired+ if (expiresAt && new Date(expiresAt) < new Date()) {+ return NextResponse.rewrite(new URL("/expired", req.url));+ }- const isBot = detectBot(req);+ // only track the click when there is no `dub-no-track` header+ if (!req.headers.get("dub-no-track")) {+ ev.waitUntil(recordClick({ req, id, domain, key }));+ }- const { country } =- process.env.VERCEL === "1" && req.geo ? req.geo : LOCALHOST_GEO_DATA;+ const isBot = detectBot(req);- // rewrite to proxy page (/_proxy/[domain]/[key]) if it's a bot and proxy is enabled- if (isBot && proxy) {- return NextResponse.rewrite(- new URL(`/proxy/${domain}/${encodeURIComponent(key)}`, req.url),- );+ const { country } =+ process.env.VERCEL === "1" && req.geo ? req.geo : LOCALHOST_GEO_DATA;- // rewrite to target URL if link cloaking is enabled- } else if (rewrite) {- if (iframeable) {- return NextResponse.rewrite(- new URL(`/rewrite/${target}`, req.url),- DUB_HEADERS,- );- } else {- // if link is not iframeable, use Next.js rewrite instead- return NextResponse.rewrite(decodeURIComponent(target), DUB_HEADERS);- }-- // redirect to iOS link if it is specified and the user is on an iOS device- } else if (ios && userAgent(req).os?.name === "iOS") {- return NextResponse.redirect(getFinalUrl(ios, { req }), DUB_HEADERS);-- // redirect to Android link if it is specified and the user is on an Android device- } else if (android && userAgent(req).os?.name === "Android") {- return NextResponse.redirect(getFinalUrl(android, { req }), DUB_HEADERS);-- // redirect to geo-specific link if it is specified and the user is in the specified country- } else if (geo && country && country in geo) {- return NextResponse.redirect(- getFinalUrl(geo[country], { req }),+ // rewrite to proxy page (/_proxy/[domain]/[key]) if it's a bot and proxy is enabled+ if (isBot && proxy) {+ return NextResponse.rewrite(+ new URL(`/proxy/${domain}/${encodeURIComponent(key)}`, req.url),+ );++ // rewrite to target URL if link cloaking is enabled+ } else if (rewrite) {+ if (iframeable) {+ return NextResponse.rewrite(+ new URL(`/rewrite/${target}`, req.url),DUB_HEADERS,);-- // regular redirect} else {- return NextResponse.redirect(getFinalUrl(target, { req }), DUB_HEADERS);+ // if link is not iframeable, use Next.js rewrite instead+ return NextResponse.rewrite(decodeURIComponent(target), DUB_HEADERS);}++ // redirect to iOS link if it is specified and the user is on an iOS device+ } else if (ios && userAgent(req).os?.name === "iOS") {+ return NextResponse.redirect(getFinalUrl(ios, { req }), DUB_HEADERS);++ // redirect to Android link if it is specified and the user is on an Android device+ } else if (android && userAgent(req).os?.name === "Android") {+ return NextResponse.redirect(getFinalUrl(android, { req }), DUB_HEADERS);++ // redirect to geo-specific link if it is specified and the user is in the specified country+ } else if (geo && country && country in geo) {+ return NextResponse.redirect(+ getFinalUrl(geo[country], { req }),+ DUB_HEADERS,+ );++ // regular redirect} else {- // short link not found, redirect to root- return NextResponse.redirect(new URL("/", req.url), DUB_HEADERS);+ return NextResponse.redirect(getFinalUrl(target, { req }), DUB_HEADERS);}}diff --git a/apps/web/lib/middleware/utils.ts b/apps/web/lib/middleware/utils.tsindex 5c030286d9..dfe736afe9 100644--- a/apps/web/lib/middleware/utils.ts+++ b/apps/web/lib/middleware/utils.ts@@ -64,45 +64,3 @@ export const detectBot = (req: NextRequest) => {}return false;};--// check if a link can be displayed in an iframe-export const isIframeable = async ({- url,- requestDomain,-}: {- url: string;- requestDomain: string;-}) => {- const res = await fetch(url, {- headers: {- "User-Agent": "dub-bot/1.0",- },- });-- // if the request throws a status that's not 200, then it's not iframeable- if (!res.ok) {- return false;- }-- const xFrameOptions = res.headers.get("X-Frame-Options"); // returns null if there is no `X-Frame-Options` header- if (xFrameOptions) {- return false;- }-- const cspHeader = res.headers.get("content-security-policy");- if (!cspHeader) {- return true;- }-- const frameAncestorsMatch = cspHeader.match(- /frame-ancestors\s+([\s\S]+?)(?=;|$)/i,- );- if (frameAncestorsMatch) {- const allowedOrigins = frameAncestorsMatch[1].split(/\s+/);- if (allowedOrigins.includes(requestDomain)) {- return true;- }- }-- return false;-};diff --git a/apps/web/lib/planetscale.ts b/apps/web/lib/planetscale.tsindex 5554f204e5..c6bd17c015 100644--- a/apps/web/lib/planetscale.ts+++ b/apps/web/lib/planetscale.ts@@ -1,4 +1,5 @@import { connect } from "@planetscale/database";+import { DomainProps } from "./types";export const pscale_config = {url: process.env.DATABASE_URL,@@ -11,22 +12,39 @@ export const getLinkViaEdge = async (domain: string, key: string) => {const { rows } =(await conn.execute(- "SELECT `key`, url, password, proxy, title, description, image, clicks, userId, publicStats FROM Link WHERE domain = ? AND `key` = ?",+ "SELECT * FROM Link WHERE domain = ? AND `key` = ?",[domain, decodeURIComponent(key)], // we need to make sure that the key is always decoded (cause that's how we store it in MySQL))) || {};return rows && Array.isArray(rows) && rows.length > 0? (rows[0] as {+ id: string;+ domain: string;key: string;url: string;- password: string | null;proxy: number;title: string;description: string;image: string;- clicks: number;- userId: number;+ rewrite: number;+ password: string | null;+ expiresAt: string | null;+ ios: string | null;+ android: string | null;+ geo: object | null;+ projectId: string;publicStats: number;}): null;};++export const getDomainViaEdge = async (domain: string) => {+ if (!process.env.DATABASE_URL) return null;++ const { rows } =+ (await conn.execute("SELECT * FROM Domain WHERE slug = ?", [domain])) || {};++ return rows && Array.isArray(rows) && rows.length > 0+ ? (rows[0] as DomainProps)+ : null;+};diff --git a/apps/web/lib/tinybird.ts b/apps/web/lib/tinybird.tsindex 1e4f65fa03..596468c2a7 100644--- a/apps/web/lib/tinybird.ts+++ b/apps/web/lib/tinybird.ts@@ -16,10 +16,12 @@ import { detectBot } from "./middleware/utils";**/export async function recordClick({req,+ id,domain,key,}: {req: NextRequest;+ id?: string;domain: string;key?: string;}) {diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex 64cd694ce5..78f30677d9 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -13,7 +13,13 @@ export interface QRLinkProps {url?: string;}+export interface RedisDomainMetadataProps {+ projectId: string;+ redirectRules?: Record<string, string>;+}+export interface RedisLinkProps {+ id: string;url: string;password?: boolean;proxy?: boolean;@@ -23,7 +29,6 @@ export interface RedisLinkProps {ios?: string;android?: string;geo?: object;- banned?: boolean;}export interface TagProps {diff --git a/apps/web/lib/upstash.ts b/apps/web/lib/upstash.tsindex 6ba9a8c5e8..87815d1c5b 100644--- a/apps/web/lib/upstash.ts+++ b/apps/web/lib/upstash.ts@@ -1,6 +1,7 @@-import { getDomainWithoutWWW, nanoid } from "@dub/utils";+import { getDomainWithoutWWW, isIframeable } from "@dub/utils";import { Ratelimit } from "@upstash/ratelimit";import { Redis } from "@upstash/redis";+import { LinkProps, RedisLinkProps } from "./types";// Initiate Redis instance by connecting to REST URLexport const redis = new Redis({@@ -54,3 +55,34 @@ export async function recordMetatags(url: string, error: boolean) {const domain = getDomainWithoutWWW(url);return await ratelimitRedis.zincrby("metatags-zset", 1, domain);}++export async function getRedisLink(link: LinkProps): Promise<RedisLinkProps> {+ const {+ id,+ domain,+ url,+ password,+ proxy,+ rewrite,+ expiresAt,+ ios,+ android,+ geo,+ } = link;+ const hasPassword = password && password.length > 0 ? true : false;++ return {+ id,+ url: encodeURIComponent(url),+ ...(hasPassword && { password: true }),+ ...(proxy && { proxy: true }),+ ...(rewrite && {+ rewrite: true,+ iframeable: await isIframeable({ url, requestDomain: domain }),+ }),+ ...(expiresAt && { expiresAt: new Date(expiresAt) }),+ ...(ios && { ios }),+ ...(android && { android }),+ ...(geo && { geo: geo as object }),+ };+}diff --git a/packages/utils/src/functions/index.ts b/packages/utils/src/functions/index.tsindex aff360c3ed..a866b92bff 100644--- a/packages/utils/src/functions/index.ts+++ b/packages/utils/src/functions/index.ts@@ -8,6 +8,7 @@ export * from "./domains";export * from "./fetch-with-timeout";export * from "./fetcher";export * from "./hash";+export * from "./is-iframeable";export * from "./link-constructor";export * from "./log";export * from "./misc";diff --git a/packages/utils/src/functions/is-iframeable.ts b/packages/utils/src/functions/is-iframeable.tsnew file mode 100644index 0000000000..7b49b486f0--- /dev/null+++ b/packages/utils/src/functions/is-iframeable.ts@@ -0,0 +1,41 @@+// check if a link can be displayed in an iframe+export const isIframeable = async ({+ url,+ requestDomain,+}: {+ url: string;+ requestDomain: string;+}) => {+ const res = await fetch(url, {+ headers: {+ "User-Agent": "dub-bot/1.0",+ },+ });++ // if the request throws a status that's not 200, then it's not iframeable+ if (!res.ok) {+ return false;+ }++ const xFrameOptions = res.headers.get("X-Frame-Options"); // returns null if there is no `X-Frame-Options` header+ if (xFrameOptions) {+ return false;+ }++ const cspHeader = res.headers.get("content-security-policy");+ if (!cspHeader) {+ return true;+ }++ const frameAncestorsMatch = cspHeader.match(+ /frame-ancestors\s+([\s\S]+?)(?=;|$)/i,+ );+ if (frameAncestorsMatch) {+ const allowedOrigins = frameAncestorsMatch[1].split(/\s+/);+ if (allowedOrigins.includes(requestDomain)) {+ return true;+ }+ }++ return false;+};