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 invalid link preview images (#3682)

Pedro Ladeira27bcf61cb27d
diff --git a/apps/web/app/api/links/metatags/utils.ts b/apps/web/app/api/links/metatags/utils.ts
index 04d1d17342..97e5705230 100644
--- a/apps/web/app/api/links/metatags/utils.ts
+++ b/apps/web/app/api/links/metatags/utils.ts
@@ -1,4 +1,5 @@
import { recordMetatags } from "@/lib/upstash";
+import { linkPreviewImageBase64PrefixRegex } from "@/lib/zod/schemas/images";
import { fetchWithTimeout, isValidUrl } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import he from "he";
@@ -62,12 +63,25 @@ export const getRelativeUrl = (url: string, imageUrl: string) => {
if (!imageUrl) {
return null;
}
- if (isValidUrl(imageUrl)) {
- return imageUrl;
+ let resolved: string;
+ try {
+ resolved = isValidUrl(imageUrl)
+ ? new URL(imageUrl).toString()
+ : (() => {
+ const { protocol, host } = new URL(url);
+ const baseURL = `${protocol}//${host}`;
+ return new URL(imageUrl, baseURL).toString();
+ })();
+ } catch {
+ return null;
+ }
+ if (
+ /^https?:\/\//i.test(resolved) ||
+ linkPreviewImageBase64PrefixRegex.test(resolved)
+ ) {
+ return resolved;
}
- const { protocol, host } = new URL(url);
- const baseURL = `${protocol}//${host}`;
- return new URL(imageUrl, baseURL).toString();
+ return null;
};
const generateFallbackMetadata = (url: string) => {
diff --git a/apps/web/app/api/user/route.ts b/apps/web/app/api/user/route.ts
index 9af116da41..d604bc1a39 100644
--- a/apps/web/app/api/user/route.ts
+++ b/apps/web/app/api/user/route.ts
@@ -2,7 +2,7 @@ import { DubApiError } from "@/lib/api/errors";
import { withSession } from "@/lib/auth";
import { confirmEmailChange } from "@/lib/auth/confirm-email-change";
import { storage } from "@/lib/storage";
-import { uploadedImageSchema } from "@/lib/zod/schemas/misc";
+import { uploadedImageSchema } from "@/lib/zod/schemas/images";
import { prisma } from "@dub/prisma";
import {
APP_DOMAIN,
diff --git a/apps/web/lib/actions/partners/update-partner-profile.ts b/apps/web/lib/actions/partners/update-partner-profile.ts
index 05a1a1448b..f89698aaab 100644
--- a/apps/web/lib/actions/partners/update-partner-profile.ts
+++ b/apps/web/lib/actions/partners/update-partner-profile.ts
@@ -21,7 +21,7 @@ import {
} from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import * as z from "zod/v4";
-import { uploadedImageSchema } from "../../zod/schemas/misc";
+import { uploadedImageSchema } from "../../zod/schemas/images";
import { authPartnerActionClient } from "../safe-action";
const updatePartnerProfileSchema = z
diff --git a/apps/web/lib/zod/schemas/domains.ts b/apps/web/lib/zod/schemas/domains.ts
index 3955c1195a..7846875106 100644
--- a/apps/web/lib/zod/schemas/domains.ts
+++ b/apps/web/lib/zod/schemas/domains.ts
@@ -1,10 +1,7 @@
import { normalizeWorkspaceId } from "@/lib/api/workspaces/workspace-id";
import * as z from "zod/v4";
-import {
- booleanQuerySchema,
- getPaginationQuerySchema,
- uploadedImageSchema,
-} from "./misc";
+import { uploadedImageSchema } from "./images";
+import { booleanQuerySchema, getPaginationQuerySchema } from "./misc";
import { parseUrlSchemaAllowEmpty } from "./utils";
export const RegisteredDomainSchema = z.object({
diff --git a/apps/web/lib/zod/schemas/images.ts b/apps/web/lib/zod/schemas/images.ts
new file mode 100644
index 0000000000..7474c3183f
--- /dev/null
+++ b/apps/web/lib/zod/schemas/images.ts
@@ -0,0 +1,103 @@
+import { GOOGLE_FAVICON_URL, R2_URL } from "@dub/utils";
+import { fileTypeFromBuffer } from "file-type";
+import * as z from "zod/v4";
+
+/** Raster data-URL prefix for link preview images (base64ImageSchema, preprocess, metatags). */
+export const linkPreviewImageBase64PrefixRegex =
+ /^data:image\/(png|jpeg|jpg|gif|webp);base64,/i;
+
+const allowedImageTypes = [
+ "image/png",
+ "image/jpeg",
+ "image/jpg",
+ "image/gif",
+ "image/webp",
+];
+
+// Base64 encoded image
+export const base64ImageSchema = z
+ .string()
+ .trim()
+ .regex(linkPreviewImageBase64PrefixRegex, {
+ message: "Invalid image format, supports only png, jpeg, jpg, gif, webp.",
+ })
+ .refine(
+ async (str) => {
+ const base64Data = str.split(",")[1];
+
+ if (!base64Data) {
+ return false;
+ }
+
+ try {
+ const buffer = new Uint8Array(Buffer.from(base64Data, "base64"));
+ const fileType = await fileTypeFromBuffer(buffer);
+
+ return fileType && allowedImageTypes.includes(fileType.mime);
+ } catch (e) {
+ return false;
+ }
+ },
+ {
+ message: "Invalid image format, supports only png, jpeg, jpg, gif, webp.",
+ },
+ )
+ .transform((v) => v || null);
+
+export const storedR2ImageUrlSchema = z
+ .url()
+ .trim()
+ .refine((url) => url.startsWith(R2_URL), {
+ message: `URL must start with ${R2_URL}`,
+ });
+
+// Google favicon URL schema - supports URLs starting with GOOGLE_FAVICON_URL
+export const googleFaviconUrlSchema = z
+ .url()
+ .trim()
+ .refine((url) => url.startsWith(GOOGLE_FAVICON_URL), {
+ message: `Image URL must start with ${GOOGLE_FAVICON_URL}`,
+ });
+
+// Google user content URL schema - supports URLs like https://lh3.googleusercontent.com/...
+// This is needed when users sign up via Google OAuth and want to use their Google profile image
+// as their workspace logo or avatar
+export const googleUserContentUrlSchema = z
+ .url()
+ .trim()
+ .refine((url) => url.startsWith("https://lh3.googleusercontent.com/"), {
+ message: "Image URL must be a valid Google user content URL",
+ });
+
+// Uploaded image could be any of the following:
+// - Base64 encoded image
+// - R2_URL
+// - Special case for GOOGLE_FAVICON_URL
+// This schema contains an async refinement check for base64 image validation,
+// which requires using parseAsync() instead of parse() when validating
+export const uploadedImageSchema = z
+ .union([base64ImageSchema, storedR2ImageUrlSchema, googleFaviconUrlSchema])
+ .transform((v) => v || null);
+
+export const publicHostedImageSchema = z
+ .url()
+ .trim()
+ .refine((url) => url.startsWith("http://") || url.startsWith("https://"), {
+ message: "Image URL must start with http:// or https://",
+ });
+
+/** Coerce unusable preview strings (e.g. data:favicons) to null before create/update link validation. */
+export function preprocessLinkPreviewImage(
+ val: unknown,
+): string | null | undefined {
+ if (val === undefined) return undefined;
+ if (val === null || val === "" || typeof val !== "string") return null;
+ const s = val.trim();
+ if (
+ s.startsWith("http://") ||
+ s.startsWith("https://") ||
+ linkPreviewImageBase64PrefixRegex.test(s)
+ )
+ return s;
+ return null;
+}
diff --git a/apps/web/lib/zod/schemas/integration.ts b/apps/web/lib/zod/schemas/integration.ts
index 5498ae5f02..177de53c90 100644
--- a/apps/web/lib/zod/schemas/integration.ts
+++ b/apps/web/lib/zod/schemas/integration.ts
@@ -1,6 +1,6 @@
import { R2_URL } from "@dub/utils";
import * as z from "zod/v4";
-import { uploadedImageSchema } from "./misc";
+import { uploadedImageSchema } from "./images";
export const integrationSchema = z.object({
id: z.string(),
diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.ts
index b027ecf060..cd543ea3fb 100644
--- a/apps/web/lib/zod/schemas/links.ts
+++ b/apps/web/lib/zod/schemas/links.ts
@@ -3,10 +3,13 @@ import { DUB_FOUNDING_DATE, formatDate, validDomainRegex } from "@dub/utils";
import * as z from "zod/v4";
import {
base64ImageSchema,
+ preprocessLinkPreviewImage,
+ publicHostedImageSchema,
+} from "./images";
+import {
booleanQuerySchema,
getCursorPaginationQuerySchema,
getPaginationQuerySchema,
- publicHostedImageSchema,
} from "./misc";
import { LinkTagSchema } from "./tags";
import {
@@ -550,7 +553,10 @@ export const createLinkBodySchema = z.object({
});
export const createLinkBodySchemaAsync = createLinkBodySchema.extend({
- image: z.union([base64ImageSchema, publicHostedImageSchema]).nullish(),
+ image: z.preprocess(
+ preprocessLinkPreviewImage,
+ z.union([base64ImageSchema, publicHostedImageSchema]).nullish(),
+ ),
});
export const updateLinkBodySchema = createLinkBodySchemaAsync
diff --git a/apps/web/lib/zod/schemas/misc.ts b/apps/web/lib/zod/schemas/misc.ts
index 946177bd90..36d331f5df 100644
--- a/apps/web/lib/zod/schemas/misc.ts
+++ b/apps/web/lib/zod/schemas/misc.ts
@@ -1,7 +1,5 @@
import { plans } from "@/lib/types";
import { WorkspaceRole } from "@dub/prisma/client";
-import { GOOGLE_FAVICON_URL, R2_URL } from "@dub/utils";
-import { fileTypeFromBuffer } from "file-type";
import * as z from "zod/v4";
export const RECURRING_MAX_DURATIONS = [0, 1, 3, 6, 12, 18, 24, 36, 48];
@@ -12,14 +10,6 @@ export const roleSchema = z
.enum(WorkspaceRole)
.describe("The role of the authenticated user in the workspace.");
-const allowedImageTypes = [
- "image/png",
- "image/jpeg",
- "image/jpg",
- "image/gif",
- "image/webp",
-];
-
export const booleanQuerySchema = z
.stringbool({
truthy: ["true"],
@@ -96,93 +86,3 @@ export const maxDurationSchema = z.coerce
message: `Max duration must be ${RECURRING_MAX_DURATIONS.join(", ")}`,
})
.nullish();
-
-// Base64 encoded image
-export const base64ImageSchema = z
- .string()
- .trim()
- .regex(/^data:image\/(png|jpeg|jpg|gif|webp);base64,/, {
- message: "Invalid image format, supports only png, jpeg, jpg, gif, webp.",
- })
- .refine(
- async (str) => {
- const base64Data = str.split(",")[1];
-
- if (!base64Data) {
- return false;
- }
-
- try {
- const buffer = new Uint8Array(Buffer.from(base64Data, "base64"));
- const fileType = await fileTypeFromBuffer(buffer);
-
- return fileType && allowedImageTypes.includes(fileType.mime);
- } catch (e) {
- return false;
- }
- },
- {
- message: "Invalid image format, supports only png, jpeg, jpg, gif, webp.",
- },
- )
- .transform((v) => v || null);
-
-// Base64 encoded raster image or SVG
-export const base64ImageAllowSVGSchema = z
- .string()
- .trim()
- .regex(/^data:image\/(png|jpeg|jpg|gif|webp|svg\+xml);base64,/, {
- message:
- "Invalid image format, supports only png, jpeg, jpg, gif, webp, svg.",
- })
- .transform((v) => v || null);
-
-export const storedR2ImageUrlSchema = z
- .url()
- .trim()
- .refine((url) => url.startsWith(R2_URL), {
- message: `URL must start with ${R2_URL}`,
- });
-
-// Google user content URL schema - supports URLs like https://lh3.googleusercontent.com/...
-// This is needed when users sign up via Google OAuth and want to use their Google profile image
-// as their workspace logo or avatar
-export const googleUserContentUrlSchema = z
- .url()
- .trim()
- .refine((url) => url.startsWith("https://lh3.googleusercontent.com/"), {
- message: "Image URL must be a valid Google user content URL",
- });
-
-// Google favicon URL schema - supports URLs starting with GOOGLE_FAVICON_URL
-export const googleFaviconUrlSchema = z
- .url()
- .trim()
- .refine((url) => url.startsWith(GOOGLE_FAVICON_URL), {
- message: `Image URL must start with ${GOOGLE_FAVICON_URL}`,
- });
-
-// Uploaded image could be any of the following:
-// - Base64 encoded image
-// - R2_URL
-// - Special case for GOOGLE_FAVICON_URL
-// - Google user content URLs (e.g., https://lh3.googleusercontent.com/...)
-// This schema contains an async refinement check for base64 image validation,
-// which requires using parseAsync() instead of parse() when validating
-export const uploadedImageSchema = z
- .union([base64ImageSchema, storedR2ImageUrlSchema, googleFaviconUrlSchema])
- .transform((v) => v || null);
-
-// Base64 encoded image/SVG or R2_URL
-// This schema contains an async refinement check for base64 image validation,
-// which requires using parseAsync() instead of parse() when validating
-export const uploadedImageAllowSVGSchema = z
- .union([base64ImageAllowSVGSchema, storedR2ImageUrlSchema])
- .transform((v) => v || null);
-
-export const publicHostedImageSchema = z
- .url()
- .trim()
- .refine((url) => url.startsWith("http://") || url.startsWith("https://"), {
- message: "Image URL must start with http:// or https://",
- });
diff --git a/apps/web/lib/zod/schemas/partners.ts b/apps/web/lib/zod/schemas/partners.ts
index b0367d9d6f..457810b0aa 100644
--- a/apps/web/lib/zod/schemas/partners.ts
+++ b/apps/web/lib/zod/schemas/partners.ts
@@ -15,15 +15,14 @@ import { COUNTRY_CODES } from "@dub/utils";
import * as z from "zod/v4";
import { analyticsQuerySchema } from "./analytics";
import { analyticsResponse } from "./analytics-response";
-import { createLinkBodySchema } from "./links";
import {
base64ImageSchema,
- booleanQuerySchema,
- getPaginationQuerySchema,
googleFaviconUrlSchema,
publicHostedImageSchema,
storedR2ImageUrlSchema,
-} from "./misc";
+} from "./images";
+import { createLinkBodySchema } from "./links";
+import { booleanQuerySchema, getPaginationQuerySchema } from "./misc";
import { ProgramEnrollmentSchema } from "./programs";
import { centsSchema, centsSchemaWithDefault, parseUrlSchema } from "./utils";
diff --git a/apps/web/lib/zod/schemas/program-application-form.ts b/apps/web/lib/zod/schemas/program-application-form.ts
index a4f071d40e..2832a9f6b7 100644
--- a/apps/web/lib/zod/schemas/program-application-form.ts
+++ b/apps/web/lib/zod/schemas/program-application-form.ts
@@ -1,5 +1,5 @@
import * as z from "zod/v4";
-import { storedR2ImageUrlSchema } from "./misc";
+import { storedR2ImageUrlSchema } from "./images";
// Common schema for all fields
export const programApplicationFormFieldCommonSchema = z.object({
diff --git a/apps/web/lib/zod/schemas/workspaces.ts b/apps/web/lib/zod/schemas/workspaces.ts
index 5862510191..44747f7f63 100644
--- a/apps/web/lib/zod/schemas/workspaces.ts
+++ b/apps/web/lib/zod/schemas/workspaces.ts
@@ -3,12 +3,8 @@ import { DEFAULT_REDIRECTS, RESERVED_SLUGS, validSlugRegex } from "@dub/utils";
import slugify from "@sindresorhus/slugify";
import * as z from "zod/v4";
import { DomainSchema } from "./domains";
-import {
- googleUserContentUrlSchema,
- planSchema,
- roleSchema,
- uploadedImageSchema,
-} from "./misc";
+import { googleUserContentUrlSchema, uploadedImageSchema } from "./images";
+import { planSchema, roleSchema } from "./misc";
export const workspaceIdSchema = z.object({
workspaceId: z
diff --git a/apps/web/tests/misc/base64.test.ts b/apps/web/tests/misc/base64.test.ts
index 71f0ce4600..1d6fce9b7f 100644
--- a/apps/web/tests/misc/base64.test.ts
+++ b/apps/web/tests/misc/base64.test.ts
@@ -1,4 +1,4 @@
-import { base64ImageSchema } from "@/lib/zod/schemas/misc";
+import { base64ImageSchema } from "@/lib/zod/schemas/images";
import { describe, expect, it } from "vitest";
describe("base64ImageSchema", () => {