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.

fix image cache issue + add iframely to detectBot

Steven Tey9473bb69b1b7
diff --git a/apps/web/app/api/admin/ban/route.ts b/apps/web/app/api/admin/ban/route.ts
index 65c877ea20..ff8e6cfc4a 100644
--- a/apps/web/app/api/admin/ban/route.ts
+++ b/apps/web/app/api/admin/ban/route.ts
@@ -3,7 +3,8 @@ import { withAdmin } from "@/lib/auth";
import { updateConfig } from "@/lib/edge-config";
import { unsubscribe } from "@/lib/flodesk";
import { prisma } from "@/lib/prisma";
-import { storage } from "@/lib/storage";
+import { isStored, storage } from "@/lib/storage";
+import { R2_URL } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
@@ -58,8 +59,9 @@ export const POST = withAdmin(async ({ req }) => {
},
}),
// if the user has a custom avatar, delete it
- user.image?.startsWith(process.env.STORAGE_BASE_URL as string) &&
- storage.delete(`avatars/${user.id}`),
+ user.image &&
+ isStored(user.image) &&
+ storage.delete(user.image.replace(`${R2_URL}/`, "")),
unsubscribe(email),
updateConfig({
key: "emails",
diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.ts
index 86854d1b55..acc69176f2 100644
--- a/apps/web/app/api/links/[linkId]/route.ts
+++ b/apps/web/app/api/links/[linkId]/route.ts
@@ -113,8 +113,11 @@ export const PATCH = withWorkspace(
try {
const response = await updateLink({
- oldDomain: link.domain,
- oldKey: link.key,
+ oldLink: {
+ domain: link.domain,
+ key: link.key,
+ image: link.image,
+ },
updatedLink: processedLink,
});
diff --git a/apps/web/app/api/links/bulk/route.ts b/apps/web/app/api/links/bulk/route.ts
index 4c3bacacac..2f28dcf9b2 100644
--- a/apps/web/app/api/links/bulk/route.ts
+++ b/apps/web/app/api/links/bulk/route.ts
@@ -5,11 +5,14 @@ import { throwIfLinksUsageExceeded } from "@/lib/api/links/usage-checks";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
+import { isStored, storage } from "@/lib/storage";
import { NewLinkProps, ProcessedLinkProps } from "@/lib/types";
import {
bulkCreateLinksBodySchema,
bulkUpdateLinksBodySchema,
} from "@/lib/zod/schemas/links";
+import { R2_URL } from "@dub/utils";
+import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
// POST /api/links/bulk – bulk create up to 100 links
@@ -245,5 +248,16 @@ export const PATCH = withWorkspace(async ({ req, workspace, headers }) => {
})
: [];
+ waitUntil(
+ Promise.allSettled(
+ links.map(async (link) => {
+ // delete old proxy image urls if exist
+ if (link.image && isStored(link.image)) {
+ storage.delete(link.image.replace(`${R2_URL}/`, ""));
+ }
+ }),
+ ),
+ );
+
return NextResponse.json([...response, ...errorLinks], { headers });
});
diff --git a/apps/web/app/api/links/upsert/route.ts b/apps/web/app/api/links/upsert/route.ts
index 8363f6486c..d64f1cdfd5 100644
--- a/apps/web/app/api/links/upsert/route.ts
+++ b/apps/web/app/api/links/upsert/route.ts
@@ -97,8 +97,11 @@ export const PUT = withWorkspace(
try {
const response = await updateLink({
- oldDomain: link.domain,
- oldKey: link.key,
+ oldLink: {
+ domain: link.domain,
+ key: link.key,
+ image: link.image,
+ },
updatedLink: processedLink,
});
diff --git a/apps/web/app/api/user/route.ts b/apps/web/app/api/user/route.ts
index f41df1af4a..72db60d74e 100644
--- a/apps/web/app/api/user/route.ts
+++ b/apps/web/app/api/user/route.ts
@@ -1,9 +1,10 @@
import { withSession } from "@/lib/auth";
import { unsubscribe } from "@/lib/flodesk";
import { prisma } from "@/lib/prisma";
-import { storage } from "@/lib/storage";
+import { isStored, storage } from "@/lib/storage";
import { redis } from "@/lib/upstash";
-import { trim } from "@dub/utils";
+import { R2_URL, nanoid, trim } from "@dub/utils";
+import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
import { z } from "zod";
@@ -45,7 +46,10 @@ export const PATCH = withSession(async ({ req, session }) => {
try {
if (image) {
- const { url } = await storage.upload(`avatars/${session.user.id}`, image);
+ const { url } = await storage.upload(
+ `avatars/${session.user.id}_${nanoid(7)}`,
+ image,
+ );
image = url;
}
const response = await prisma.user.update({
@@ -60,6 +64,15 @@ export const PATCH = withSession(async ({ req, session }) => {
...(defaultWorkspace && { defaultWorkspace }),
},
});
+
+ waitUntil(
+ (async () => {
+ if (session.user.image && isStored(session.user.image)) {
+ await storage.delete(session.user.image.replace(`${R2_URL}/`, ""));
+ }
+ })(),
+ );
+
return NextResponse.json(response);
} catch (error) {
if (error.code === "P2002") {
@@ -101,8 +114,9 @@ export const DELETE = withSession(async ({ session }) => {
});
const response = await Promise.allSettled([
// if the user has a custom avatar, delete it
- user.image?.startsWith(process.env.STORAGE_BASE_URL as string) &&
- storage.delete(`avatars/${session.user.id}`),
+ user.image &&
+ isStored(user.image) &&
+ storage.delete(user.image.replace(`${R2_URL}/`, "")),
unsubscribe(session.user.email),
]);
return NextResponse.json(response);
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/logo/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/logo/route.ts
index 8bdba1388e..df58abedb6 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/logo/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/logo/route.ts
@@ -1,7 +1,9 @@
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
-import { storage } from "@/lib/storage";
+import { isStored, storage } from "@/lib/storage";
import z from "@/lib/zod";
+import { R2_URL, nanoid } from "@dub/utils";
+import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
const uploadLogoSchema = z.object({
@@ -13,13 +15,24 @@ export const POST = withWorkspace(
async ({ req, workspace }) => {
const { image } = uploadLogoSchema.parse(await req.json());
- const { url } = await storage.upload(`logos/${workspace.id}`, image);
+ const { url } = await storage.upload(
+ `logos/${workspace.id}_${nanoid(7)}`,
+ image,
+ );
const response = await prisma.project.update({
where: { id: workspace.id },
data: { logo: url },
});
+ waitUntil(
+ (async () => {
+ if (workspace.logo && isStored(workspace.logo)) {
+ await storage.delete(workspace.logo.replace(`${R2_URL}/`, ""));
+ }
+ })(),
+ );
+
return NextResponse.json(response);
},
{
diff --git a/apps/web/lib/api/domains/delete-domain-links.ts b/apps/web/lib/api/domains/delete-domain-links.ts
index b3ed4cef42..9a8c5363bd 100644
--- a/apps/web/lib/api/domains/delete-domain-links.ts
+++ b/apps/web/lib/api/domains/delete-domain-links.ts
@@ -1,7 +1,8 @@
import { prisma } from "@/lib/prisma";
import { redis } from "@/lib/upstash";
+import { R2_URL } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
-import { storage } from "../../storage";
+import { isStored, storage } from "../../storage";
import { recordLink } from "../../tinybird";
import { removeDomainFromVercel } from "./remove-domain-vercel";
@@ -64,8 +65,8 @@ export async function deleteDomainAndLinks(domain: string) {
})),
]),
...allLinks.map((link) => {
- if (link.image?.startsWith(process.env.STORAGE_BASE_URL as string)) {
- storage.delete(`images/${link.id}`);
+ if (link.image && isStored(link.image)) {
+ storage.delete(link.image.replace(`${R2_URL}/`, ""));
}
}),
// remove the domain from Vercel
diff --git a/apps/web/lib/api/links/bulk-update-links.ts b/apps/web/lib/api/links/bulk-update-links.ts
index 01a53fd488..eb1d9877e9 100644
--- a/apps/web/lib/api/links/bulk-update-links.ts
+++ b/apps/web/lib/api/links/bulk-update-links.ts
@@ -2,7 +2,7 @@ import { prisma } from "@/lib/prisma";
import { isStored, storage } from "@/lib/storage";
import z from "@/lib/zod";
import { bulkUpdateLinksBodySchema } from "@/lib/zod/schemas/links";
-import { getParamsFromURL, truncate } from "@dub/utils";
+import { R2_URL, getParamsFromURL, nanoid, truncate } from "@dub/utils";
import { Prisma } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import { propagateBulkLinkChanges } from "./propagate-bulk-link-changes";
@@ -29,6 +29,8 @@ export async function bulkUpdateLinks(
const combinedTagIds = combineTagIds({ tagId, tagIds });
+ const imageUrlNonce = nanoid(7);
+
const updatedLinks = await Promise.all(
linkIds.map((linkId) =>
prisma.link.update({
@@ -42,7 +44,7 @@ export async function bulkUpdateLinks(
description: truncate(description, 240),
image:
proxy && image && !isStored(image)
- ? `${process.env.STORAGE_BASE_URL}/images/${linkIds[0]}`
+ ? `${R2_URL}/images/${linkIds[0]}_${imageUrlNonce}`
: image,
expiresAt: expiresAt ? new Date(expiresAt) : null,
geo: geo || Prisma.JsonNull,
@@ -101,7 +103,7 @@ export async function bulkUpdateLinks(
proxy &&
image &&
!isStored(image) &&
- storage.upload(`images/${linkIds[0]}`, image, {
+ storage.upload(`images/${linkIds[0]}_${imageUrlNonce}`, image, {
width: 1200,
height: 630,
}),
diff --git a/apps/web/lib/api/links/create-link.ts b/apps/web/lib/api/links/create-link.ts
index 2f2c7c2447..02db4ae287 100644
--- a/apps/web/lib/api/links/create-link.ts
+++ b/apps/web/lib/api/links/create-link.ts
@@ -4,7 +4,12 @@ import { isStored, storage } from "@/lib/storage";
import { recordLink } from "@/lib/tinybird";
import { ProcessedLinkProps } from "@/lib/types";
import { formatRedisLink, redis } from "@/lib/upstash";
-import { APP_DOMAIN_WITH_NGROK, getParamsFromURL, truncate } from "@dub/utils";
+import {
+ APP_DOMAIN_WITH_NGROK,
+ R2_URL,
+ getParamsFromURL,
+ truncate,
+} from "@dub/utils";
import { Prisma } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import { updateLinksUsage } from "./update-links-usage";
@@ -78,7 +83,7 @@ export async function createLink(link: ProcessedLinkProps) {
},
});
- const uploadedImageUrl = `${process.env.STORAGE_BASE_URL}/images/${response.id}`;
+ const uploadedImageUrl = `${R2_URL}/images/${response.id}`;
waitUntil(
Promise.all([
@@ -96,8 +101,16 @@ export async function createLink(link: ProcessedLinkProps) {
workspace_id: response.projectId,
created_at: response.createdAt,
}),
- // if proxy image is set, upload image to R2 and update the link with the uploaded image URL
- ...(proxy && image && !isStored(image)
+ /* Upload image to R2 and update the link with the uploaded image URL when:
+ - proxy is enabled
+ - image is set and:
+ - image is not stored in R2
+ or
+ - image URL does not start with the R2 URL + image ID (could be duplicate link flow)
+ */
+ ...(proxy &&
+ image &&
+ (!isStored(image) || !image.startsWith(`${R2_URL}/images/${response.id}`))
? [
// upload image to R2
storage.upload(`images/${response.id}`, image, {
diff --git a/apps/web/lib/api/links/delete-link.ts b/apps/web/lib/api/links/delete-link.ts
index 4ab8f08855..885c2cc9bc 100644
--- a/apps/web/lib/api/links/delete-link.ts
+++ b/apps/web/lib/api/links/delete-link.ts
@@ -1,7 +1,8 @@
import { prisma } from "@/lib/prisma";
-import { storage } from "@/lib/storage";
+import { isStored, storage } from "@/lib/storage";
import { recordLink } from "@/lib/tinybird";
import { redis } from "@/lib/upstash";
+import { R2_URL } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
export async function deleteLink(linkId: string) {
@@ -16,9 +17,9 @@ export async function deleteLink(linkId: string) {
waitUntil(
Promise.allSettled([
// if the image is stored in Cloudflare R2, delete it
- link.proxy &&
- link.image?.startsWith(process.env.STORAGE_BASE_URL as string) &&
- storage.delete(`images/${link.id}`),
+ link.image &&
+ isStored(link.image) &&
+ storage.delete(link.image.replace(`${R2_URL}/`, "")),
redis.hdel(link.domain.toLowerCase(), link.key.toLowerCase()),
recordLink({
link_id: link.id,
diff --git a/apps/web/lib/api/links/update-link.ts b/apps/web/lib/api/links/update-link.ts
index 213439aa47..9f720e8c5d 100644
--- a/apps/web/lib/api/links/update-link.ts
+++ b/apps/web/lib/api/links/update-link.ts
@@ -3,18 +3,16 @@ import { isStored, storage } from "@/lib/storage";
import { recordLink } from "@/lib/tinybird";
import { LinkProps, ProcessedLinkProps } from "@/lib/types";
import { formatRedisLink, redis } from "@/lib/upstash";
-import { SHORT_DOMAIN, getParamsFromURL, truncate } from "@dub/utils";
+import { R2_URL, getParamsFromURL, nanoid, truncate } from "@dub/utils";
import { Prisma } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import { combineTagIds, transformLink } from "./utils";
export async function updateLink({
- oldDomain = SHORT_DOMAIN,
- oldKey,
+ oldLink,
updatedLink,
}: {
- oldDomain?: string;
- oldKey: string;
+ oldLink: { domain: string; key: string; image?: string | null };
updatedLink: ProcessedLinkProps &
Pick<LinkProps, "id" | "clicks" | "lastClicked" | "updatedAt">;
}) {
@@ -30,8 +28,8 @@ export async function updateLink({
proxy,
geo,
} = updatedLink;
- const changedKey = key.toLowerCase() !== oldKey.toLowerCase();
- const changedDomain = domain !== oldDomain;
+ const changedKey = key.toLowerCase() !== oldLink.key.toLowerCase();
+ const changedDomain = domain !== oldLink.domain;
const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =
getParamsFromURL(url);
@@ -50,6 +48,8 @@ export async function updateLink({
const combinedTagIds = combineTagIds({ tagId, tagIds });
+ const imageUrlNonce = nanoid(7);
+
const response = await prisma.link.update({
where: {
id,
@@ -61,7 +61,7 @@ export async function updateLink({
description: truncate(description, 240),
image:
proxy && image && !isStored(image)
- ? `${process.env.STORAGE_BASE_URL}/images/${id}`
+ ? `${R2_URL}/images/${id}_${imageUrlNonce}`
: image,
utm_source,
utm_medium,
@@ -132,15 +132,19 @@ export async function updateLink({
}),
// if key is changed: delete the old key in Redis
(changedDomain || changedKey) &&
- redis.hdel(oldDomain.toLowerCase(), oldKey.toLowerCase()),
+ redis.hdel(oldLink.domain.toLowerCase(), oldLink.key.toLowerCase()),
// if proxy is true and image is not stored in R2, upload image to R2
proxy &&
image &&
!isStored(image) &&
- storage.upload(`images/${id}`, image, {
+ storage.upload(`images/${id}_${imageUrlNonce}`, image, {
width: 1200,
height: 630,
}),
+ // if old link image is stored in R2, delete it
+ oldLink.image &&
+ isStored(oldLink.image) &&
+ storage.delete(oldLink.image.replace(`${R2_URL}/`, "")),
]),
);
diff --git a/apps/web/lib/api/workspaces.ts b/apps/web/lib/api/workspaces.ts
index bae2765cd4..ece699304d 100644
--- a/apps/web/lib/api/workspaces.ts
+++ b/apps/web/lib/api/workspaces.ts
@@ -1,11 +1,12 @@
import { deleteDomainAndLinks } from "@/lib/api/domains";
import { prisma } from "@/lib/prisma";
-import { storage } from "@/lib/storage";
+import { isStored, storage } from "@/lib/storage";
import { cancelSubscription } from "@/lib/stripe";
import {
DUB_DOMAINS_ARRAY,
LEGAL_USER_ID,
LEGAL_WORKSPACE_ID,
+ R2_URL,
} from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { recordLink } from "../tinybird";
@@ -92,17 +93,18 @@ export async function deleteWorkspace(
})),
),
// remove all images from R2
- ...defaultDomainLinks.map(({ id, proxy, image }) =>
- proxy && image?.startsWith(process.env.STORAGE_BASE_URL as string)
- ? storage.delete(`images/${id}`)
+ ...defaultDomainLinks.map(({ image }) =>
+ image && isStored(image)
+ ? storage.delete(image.replace(`${R2_URL}/`, ""))
: Promise.resolve(),
),
]);
await Promise.all([
// delete workspace logo if it's a custom logo stored in R2
- workspace.logo?.startsWith(process.env.STORAGE_BASE_URL as string) &&
- storage.delete(`logos/${workspace.id}`),
+ workspace.logo &&
+ isStored(workspace.logo) &&
+ storage.delete(workspace.logo.replace(`${R2_URL}/`, "")),
// if they have a Stripe subscription, cancel it
workspace.stripeId && cancelSubscription(workspace.stripeId),
// delete the workspace
@@ -159,8 +161,9 @@ export async function deleteWorkspaceAdmin(
const deleteWorkspaceResponse = await Promise.all([
// delete workspace logo if it's a custom logo stored in R2
- workspace.logo?.startsWith(process.env.STORAGE_BASE_URL as string) &&
- storage.delete(`logos/${workspace.id}`),
+ workspace.logo &&
+ isStored(workspace.logo) &&
+ storage.delete(workspace.logo.replace(`${R2_URL}/`, "")),
// if they have a Stripe subscription, cancel it
workspace.stripeId && cancelSubscription(workspace.stripeId),
// delete the workspace
diff --git a/apps/web/lib/middleware/utils/detect-bot.ts b/apps/web/lib/middleware/utils/detect-bot.ts
index 10fc4843d4..b7f1d36205 100644
--- a/apps/web/lib/middleware/utils/detect-bot.ts
+++ b/apps/web/lib/middleware/utils/detect-bot.ts
@@ -12,8 +12,9 @@ export const detectBot = (req: NextRequest) => {
* - WhatsApp is for WhatsApp crawler
* - MetaInspector is for https://metatags.io/
* - Go-http-client/1.1 is a bot: https://user-agents.net/string/go-http-client-1-1
+ * - iframely is for https://iframely.com/docs/about (used by Notion, Linear)
*/
- return /bot|chatgpt|facebookexternalhit|WhatsApp|google|baidu|bing|msn|duckduckbot|teoma|slurp|yandex|MetaInspector|Go-http-client/i.test(
+ return /bot|chatgpt|facebookexternalhit|WhatsApp|google|baidu|bing|msn|duckduckbot|teoma|slurp|yandex|MetaInspector|Go-http-client|iframely/i.test(
ua,
);
}
diff --git a/apps/web/lib/storage.ts b/apps/web/lib/storage.ts
index 90c155c35e..24fdc3de15 100644
--- a/apps/web/lib/storage.ts
+++ b/apps/web/lib/storage.ts
@@ -1,4 +1,4 @@
-import { fetchWithTimeout } from "@dub/utils";
+import { R2_URL, fetchWithTimeout } from "@dub/utils";
import { AwsClient } from "aws4fetch";
interface imageOptions {
@@ -46,7 +46,7 @@ class StorageClient {
});
return {
- url: `${process.env.STORAGE_BASE_URL}/${key}`,
+ url: `${R2_URL}/${key}`,
};
} catch (error) {
throw new Error(`Failed to upload file: ${error.message}`);
@@ -122,5 +122,5 @@ class StorageClient {
export const storage = new StorageClient();
export const isStored = (url: string) => {
- return url.startsWith(process.env.STORAGE_BASE_URL || "");
+ return url.startsWith(R2_URL);
};
diff --git a/packages/utils/src/constants/main.ts b/packages/utils/src/constants/main.ts
index ffb0e86588..25b07ea10e 100644
--- a/packages/utils/src/constants/main.ts
+++ b/packages/utils/src/constants/main.ts
@@ -54,3 +54,5 @@ export const DUB_THUMBNAIL = "https://assets.dub.co/thumbnail.jpg";
export const DUB_WORKSPACE_ID = "cl7pj5kq4006835rbjlt2ofka";
export const LEGAL_WORKSPACE_ID = "clrflia0j0000vs7sqfhz9c7q";
export const LEGAL_USER_ID = "clqei1lgc0000vsnzi01pbf47";
+
+export const R2_URL = process.env.STORAGE_BASE_URL as string;
diff --git a/packages/utils/src/functions/construct-metadata.ts b/packages/utils/src/functions/construct-metadata.ts
index 2883105e5e..77df7b7f80 100644
--- a/packages/utils/src/functions/construct-metadata.ts
+++ b/packages/utils/src/functions/construct-metadata.ts
@@ -41,11 +41,7 @@ export function constructMetadata({
title,
description,
...(image && {
- images: [
- {
- url: image,
- },
- ],
+ images: image,
}),
...(video && {
videos: video,