The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Pin Content-Type and size on signed R2 uploads. (#4482)
Kiran Kbd69439da068
diff --git a/apps/web/app/(ee)/api/embed/referrals/bounties/[bountyId]/upload/route.ts b/apps/web/app/(ee)/api/embed/referrals/bounties/[bountyId]/upload/route.tsindex 8a42cbf977..63ed7b15e6 100644--- a/apps/web/app/(ee)/api/embed/referrals/bounties/[bountyId]/upload/route.ts+++ b/apps/web/app/(ee)/api/embed/referrals/bounties/[bountyId]/upload/route.ts@@ -2,13 +2,13 @@ import { parseRequestBody } from "@/lib/api/utils";import { getBountySubmissionUploadUrl } from "@/lib/bounty/api/get-bounty-submission-upload-url";import { withReferralsEmbedToken } from "@/lib/embed/referrals/auth";import { prisma } from "@/lib/prisma";+import { signedUploadInputSchema } from "@/lib/storage/schemas";import { NextResponse } from "next/server";import * as z from "zod/v4";const bodySchema = z.object({fileName: z.string().trim().min(1),- contentType: z.string().trim().min(1),- contentLength: z.number().int().positive(),+ ...signedUploadInputSchema.shape,});// POST /api/embed/referrals/bounties/[bountyId]/upload – get a signed R2 upload URL for a bounty submissiondiff --git a/apps/web/app/(ee)/api/intercom/webhook/process/conversation-admin-replied.ts b/apps/web/app/(ee)/api/intercom/webhook/process/conversation-admin-replied.tsindex 18866c9fd4..08903919f4 100644--- a/apps/web/app/(ee)/api/intercom/webhook/process/conversation-admin-replied.ts+++ b/apps/web/app/(ee)/api/intercom/webhook/process/conversation-admin-replied.ts@@ -9,13 +9,13 @@ import {IntercomCredentials,intercomCredentialsSchema,} from "@/lib/integrations/intercom/schema";-import { PROGRAM_ALLOWED_ATTACHMENT_TYPES } from "@/lib/messages/constants";import {mapMessageAttachmentsForCreate,sanitizeFileName,} from "@/lib/messages/utils";import { prisma } from "@/lib/prisma";import { storage } from "@/lib/storage";+import { UPLOAD_POLICIES } from "@/lib/storage/upload-policies";import {APP_DOMAIN_WITH_NGROK,fetchWithTimeout,@@ -288,9 +288,24 @@ async function uploadIntercomAttachments({>[] = [];const externalAttachments: { name: string; url: string }[] = [];+ const attachmentPolicy = UPLOAD_POLICIES.programMessageAttachments;+ const attachmentTypes = attachmentPolicy.contentTypes as readonly string[];+ const maxBytes = attachmentPolicy.maxBytes;for (const attachment of attachments) {try {+ if (!attachmentTypes.includes(attachment.content_type)) {+ throw new Error(+ `Unsupported attachment type: ${attachment.content_type}`,+ );+ }++ if (attachment.filesize > maxBytes) {+ throw new Error(+ `Attachment exceeds maximum size of ${maxBytes / 1024 / 1024}MB`,+ );+ }+const response = await fetchWithTimeout(attachment.url,{@@ -299,22 +314,18 @@ async function uploadIntercomAttachments({30000,);- if (- !PROGRAM_ALLOWED_ATTACHMENT_TYPES.includes(- attachment.content_type as (typeof PROGRAM_ALLOWED_ATTACHMENT_TYPES)[number],- )- ) {- throw new Error(- `Unsupported attachment type: ${attachment.content_type}`,- );- }-if (!response.ok) {throw new Error(`Failed to fetch attachment: ${response.status}`);}const blob = await response.blob();+ if (blob.size > maxBytes) {+ throw new Error(+ `Attachment exceeds maximum size of ${maxBytes / 1024 / 1024}MB`,+ );+ }+const name = (attachment.name.trim() || "attachment").slice(0, 191);const storageKey = `messages/${programId}/${nanoid(10)}/${sanitizeFileName(name)}`;@@ -330,7 +341,7 @@ async function uploadIntercomAttachments({storedAttachments.push({name: attachment.name?.trim() || "attachment",type: attachment.content_type,- size: attachment.filesize,+ size: blob.size,storageKey,});} catch (error) {diff --git a/apps/web/app/(ee)/app.dub.co/(new-program)/[slug]/program/new/form.tsx b/apps/web/app/(ee)/app.dub.co/(new-program)/[slug]/program/new/form.tsxindex 608bb40eb7..4827dbc513 100644--- a/apps/web/app/(ee)/app.dub.co/(new-program)/[slug]/program/new/form.tsx+++ b/apps/web/app/(ee)/app.dub.co/(new-program)/[slug]/program/new/form.tsx@@ -1,10 +1,12 @@"use client";import { onboardProgramAction } from "@/lib/actions/partners/onboard-program";+import { UPLOAD_POLICIES } from "@/lib/storage/upload-policies";import useWorkspace from "@/lib/swr/use-workspace";import { ProgramData } from "@/lib/types";import { ProgramLinkConfiguration } from "@/ui/partners/program-link-configuration";import { Button, FileUpload, Input, useMediaQuery } from "@dub/ui";+import { toErrorMessage } from "@dub/utils";import { Plus } from "lucide-react";import { useAction } from "next-safe-action/hooks";import { useRouter } from "next/navigation";@@ -12,6 +14,9 @@ import { useState } from "react";import { Controller, useFormContext } from "react-hook-form";import { toast } from "sonner";+const { contentTypes, maxBytes } = UPLOAD_POLICIES.programLogos;+const maxFileSizeMB = maxBytes / (1024 * 1024);+export function Form() {const router = useRouter();const { isMobile } = useMediaQuery();@@ -61,14 +66,20 @@ export function Form() {`/api/workspaces/${workspaceId}/upload-url`,{method: "POST",+ headers: {+ "Content-Type": "application/json",+ },body: JSON.stringify({- folder: "program-logos",+ folder: "programLogos",+ contentType: file.type,+ contentLength: file.size,}),},);if (!response.ok) {- throw new Error("Failed to get signed URL for upload.");+ const { error } = await response.json();+ throw new Error(toErrorMessage(error));}const { signedUrl, destinationUrl } = await response.json();@@ -89,7 +100,7 @@ export function Form() {setValue("logo", destinationUrl, { shouldDirty: true });toast.success("Program logo uploaded!");} catch (e) {- toast.error("Failed to upload logo");+ toast.error(toErrorMessage(e));} finally {setIsUploading(false);}@@ -138,7 +149,7 @@ export function Form() {rules={{ required: true }}render={({ field }) => (<FileUpload- accept="images"+ acceptedFileTypes={contentTypes}className="size-14 rounded-lg"iconClassName="size-4 text-neutral-800"icon={Plus}@@ -148,7 +159,7 @@ export function Form() {readFileonChange={({ file }) => handleUpload(file)}content={null}- maxFileSizeMB={2}+ maxFileSizeMB={maxFileSizeMB}/>)}/>diff --git a/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submission-fields.tsx b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submission-fields.tsxindex 4c115764bf..bcf0a61554 100644--- a/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submission-fields.tsx+++ b/apps/web/app/(ee)/app.dub.co/embed/referrals/bounties/submission-fields.tsx@@ -6,6 +6,7 @@ import {BOUNTY_MAX_SUBMISSION_URLS,} from "@/lib/bounty/constants";import { resolveBountyDetails } from "@/lib/bounty/utils";+import { UPLOAD_POLICIES } from "@/lib/storage/upload-policies";import { PartnerBountyProps, PartnerPlatformProps } from "@/lib/types";import { evaluateSocialContentRequirements } from "@/ui/partners/bounties/evaluate-social-content-requirements";import { X } from "@/ui/shared/icons";@@ -17,7 +18,7 @@ import {LoadingSpinner,Trash,} from "@dub/ui";-import { cn, formatDate } from "@dub/utils";+import { cn, formatDate, toErrorMessage } from "@dub/utils";import { AlertTriangle } from "lucide-react";import { useEffect, useId, useState } from "react";import ReactTextareaAutosize from "react-textarea-autosize";@@ -85,7 +86,8 @@ export function EmbedImagesField({);if (!uploadUrlRes.ok) {- toast.error("Failed to get signed upload URL.");+ const { error } = await uploadUrlRes.json();+ toast.error(toErrorMessage(error, "Failed to get signed upload URL."));setFiles((prev) => {const updated = prev.filter((f) => f.id !== newFile.id);onUploadingChange(updated.some((f) => f.uploading));@@ -106,7 +108,14 @@ export function EmbedImagesField({});if (!uploadResponse.ok) {- toast.error("Failed to upload screenshot.");+ let errorMessage = "Failed to upload screenshot.";+ try {+ const res = await uploadResponse.json();+ errorMessage = toErrorMessage(res.error, errorMessage);+ } catch {+ // ignore JSON parse errors; use the default message+ }+ toast.error(errorMessage);setFiles((prev) => {const updated = prev.filter((f) => f.id !== newFile.id);onUploadingChange(updated.some((f) => f.uploading));@@ -125,10 +134,8 @@ export function EmbedImagesField({onUploadingChange(updated.some((f) => f.uploading));return updated;});- } catch {- toast.error(- "An unexpected error occurred while uploading. Please try again.",- );+ } catch (e) {+ toast.error(toErrorMessage(e));setFiles((prev) => {const updated = prev.filter((f) => f.id !== newFile.id);onUploadingChange(updated.some((f) => f.uploading));@@ -186,19 +193,21 @@ export function EmbedImagesField({))}<FileUpload- accept="images"+ acceptedFileTypes={+ UPLOAD_POLICIES.bountySubmissionImages.contentTypes+ }className={cn("border-border-subtle h-full w-auto rounded-md border",files.length > 0 ? "aspect-square" : "aspect-[unset] w-full",)}iconClassName="size-5 shrink-0"variant="plain"- content={- files.length > 0 ? null : "SVG, JPG, PNG or WEBP\nMax size 5MB"- }+ content={files.length > 0 ? null : "JPG, PNG or WEBP\nMax size 5MB"}onChange={async ({ file }) => await handleUpload(file)}disabled={files.length >= maxFiles}- maxFileSizeMB={5}+ maxFileSizeMB={+ UPLOAD_POLICIES.bountySubmissionImages.maxBytes / (1024 * 1024)+ }/></div></div>diff --git a/apps/web/app/(ee)/partners.dub.co/(dashboard)/messages/[programSlug]/page.tsx b/apps/web/app/(ee)/partners.dub.co/(dashboard)/messages/[programSlug]/page.tsxindex 1219432b96..5f0b025821 100644--- a/apps/web/app/(ee)/partners.dub.co/(dashboard)/messages/[programSlug]/page.tsx+++ b/apps/web/app/(ee)/partners.dub.co/(dashboard)/messages/[programSlug]/page.tsx@@ -1,12 +1,12 @@"use client";import { parseActionError } from "@/lib/actions/parse-action-errors";-import { PARTNER_ALLOWED_ATTACHMENT_TYPES } from "@/lib/messages/constants";import { useProgramMessages } from "@/lib/messages/hooks/use-program-messages";import { markProgramMessagesReadAction } from "@/lib/messages/mark-program-messages-read";import { messageProgramAction } from "@/lib/messages/message-program";import { uploadPartnerMessageAttachmentAction } from "@/lib/messages/upload-partner-message-attachment";import { constructPartnerLink } from "@/lib/partners/construct-partner-link";+import { UPLOAD_POLICIES } from "@/lib/storage/upload-policies";import { mutatePrefix } from "@/lib/swr/mutate";import usePartnerAnalytics from "@/lib/swr/use-partner-analytics";import usePartnerProfile from "@/lib/swr/use-partner-profile";@@ -177,8 +177,7 @@ export default function PartnerMessagesProgramPage() {const result = await uploadAttachment({programSlug,fileName: file.name,- contentType:- file.type as (typeof PARTNER_ALLOWED_ATTACHMENT_TYPES)[number],+ contentType: file.type,contentLength: file.size,});@@ -304,7 +303,9 @@ export default function PartnerMessagesProgramPage() {pendingAttachments={pendingAttachments}onAddFiles={handleAddFiles}onRemoveAttachment={handleRemoveAttachment}- allowedFileTypes={PARTNER_ALLOWED_ATTACHMENT_TYPES}+ allowedFileTypes={+ UPLOAD_POLICIES.partnerMessageAttachments.contentTypes+ }{...(shouldShowExternalSupportEmptyState && messages?.length? {footerSlot: (diff --git a/apps/web/app/api/workspaces/[idOrSlug]/upload-url/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/upload-url/route.tsindex e10c266d9f..ce81a31d4c 100644--- a/apps/web/app/api/workspaces/[idOrSlug]/upload-url/route.ts+++ b/apps/web/app/api/workspaces/[idOrSlug]/upload-url/route.ts@@ -1,27 +1,52 @@import { withWorkspace } from "@/lib/auth";-import { storage } from "@/lib/storage";-import { nanoid, R2_URL } from "@dub/utils";+import { createSignedUploadUrl } from "@/lib/storage/create-signed-upload-url";+import { signedUploadInputSchema } from "@/lib/storage/schemas";+import { validateSignedUpload } from "@/lib/storage/validate-signed-upload";+import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";+import { nanoid } from "@dub/utils";import { NextResponse } from "next/server";import * as z from "zod/v4";-const schema = z.object({- folder: z.enum(["integration-screenshots", "program-logos"]),+const schema = signedUploadInputSchema.extend({+ folder: z.enum(["integrationScreenshots", "programLogos"]),});// POST /api/workspaces/[idOrSlug]/upload-url – get a signed URL to upload a file to a workspaceexport const POST = withWorkspace(- async ({ req }) => {- const { folder } = schema.parse(await req.json());+ async ({ req, workspace, session }) => {+ const {+ folder: policy,+ contentType,+ contentLength,+ } = schema.parse(await req.json());- const key = `${folder}/${nanoid(16)}`;- const signedUrl = await storage.getSignedUploadUrl({+ const key =+ policy === "integrationScreenshots"+ ? `integration-screenshots/${nanoid(10)}`+ : `program-logos/${nanoid(10)}`;++ validateSignedUpload({+ contentLength,+ contentType,+ policy,+ });++ await assertRateLimit({+ policy: RATELIMIT_POLICIES.workspaceFileUpload,+ identifier: [workspace.id, session.user.id],+ });++ const { signedUrl, destinationUrl } = await createSignedUploadUrl({key,+ contentType,+ contentLength,});return NextResponse.json({key,signedUrl,- destinationUrl: `${R2_URL}/${key}`,+ destinationUrl,});},{diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsxindex f3f3262190..f9e6f08cfa 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/campaigns/[campaignId]/campaign-editor.tsx@@ -1,3 +1,4 @@+import { parseActionError } from "@/lib/actions/parse-action-errors";import { uploadCampaignImageAction } from "@/lib/actions/partners/upload-campaign-image";import { CAMPAIGN_READONLY_STATUSES } from "@/lib/api/campaigns/constants";import { checkWorkflowConditions } from "@/lib/api/workflows/check-workflow-conditions";@@ -5,6 +6,7 @@ import {formatCampaignFromAddress,parseCampaignFromAddress,} from "@/lib/email/parse-campaign-from-address";+import { UPLOAD_POLICIES } from "@/lib/storage/upload-policies";import { useApiMutation } from "@/lib/swr/use-api-mutation";import { useEmailDomains } from "@/lib/swr/use-email-domains";import useProgram from "@/lib/swr/use-program";@@ -30,7 +32,7 @@ import {TooltipContent,useKeyboardShortcut,} from "@dub/ui";-import { capitalize, cn, pluck } from "@dub/utils";+import { capitalize, cn, pluck, toErrorMessage } from "@dub/utils";import { CampaignStatus } from "@prisma/client";import slugify from "@sindresorhus/slugify";import { motion } from "motion/react";@@ -741,14 +743,34 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {variables={[...EMAIL_TEMPLATE_VARIABLES]}variableInfo={EMAIL_TEMPLATE_VARIABLE_INFO}editable={!isLocked}+ imageAccept={UPLOAD_POLICIES.programCampaignImages.contentTypes.join(+ ",",+ )}uploadImage={async (file) => {try {+ const { maxBytes } =+ UPLOAD_POLICIES.programCampaignImages;+ const maxFileSizeMB = maxBytes / (1024 * 1024);++ if (file.size > maxBytes) {+ throw new Error(+ `File size too big (max ${maxFileSizeMB} MB)`,+ );+ }+const result = await executeImageUpload({workspaceId: workspaceId!,+ contentType: file.type,+ contentLength: file.size,});if (!result?.data) {- throw new Error("Failed to get signed upload URL");+ throw new Error(+ parseActionError(+ result ?? {},+ "Failed to get signed upload URL",+ ),+ );}const { signedUrl, destinationUrl } = result.data;@@ -769,7 +791,7 @@ export function CampaignEditor({ campaign }: { campaign: Campaign }) {return destinationUrl;} catch (e) {console.error("Failed to upload image", e);- toast.error("Failed to upload image");+ toast.error(toErrorMessage(e));}return null;diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/messages/[partnerId]/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/messages/[partnerId]/page-client.tsxindex b2fd7bbf89..9ea68c30a7 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/messages/[partnerId]/page-client.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/messages/[partnerId]/page-client.tsx@@ -1,11 +1,11 @@"use client";import { parseActionError } from "@/lib/actions/parse-action-errors";-import { PROGRAM_ALLOWED_ATTACHMENT_TYPES } from "@/lib/messages/constants";import { usePartnerMessages } from "@/lib/messages/hooks/use-partner-messages";import { markPartnerMessagesReadAction } from "@/lib/messages/mark-partner-messages-read";import { messagePartnerAction } from "@/lib/messages/message-partner";import { uploadMessageAttachmentAction } from "@/lib/messages/upload-message-attachment";+import { UPLOAD_POLICIES } from "@/lib/storage/upload-policies";import { mutatePrefix } from "@/lib/swr/mutate";import usePartner from "@/lib/swr/use-partner";import useProgram from "@/lib/swr/use-program";@@ -117,8 +117,7 @@ export function ProgramMessagesPartnerPageClient() {const result = await uploadAttachment({workspaceId: workspaceId!,fileName: file.name,- contentType:- file.type as (typeof PROGRAM_ALLOWED_ATTACHMENT_TYPES)[number],+ contentType: file.type,contentLength: file.size,});@@ -228,7 +227,9 @@ export function ProgramMessagesPartnerPageClient() {pendingAttachments={pendingAttachments}onAddFiles={handleAddFiles}onRemoveAttachment={handleRemoveAttachment}- allowedFileTypes={PROGRAM_ALLOWED_ATTACHMENT_TYPES}+ allowedFileTypes={+ UPLOAD_POLICIES.programMessageAttachments.contentTypes+ }defaultValue={defaultMessage}onSendMessage={async (message, attachments) => {const createdAt = new Date();diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/use-upload-program-resource.ts b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/use-upload-program-resource.tsindex d1bc9457ec..59fd054ff2 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/use-upload-program-resource.ts+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/(ee)/program/resources/program-brand-assets/use-upload-program-resource.ts@@ -1,5 +1,6 @@"use client";+import { parseActionError } from "@/lib/actions/parse-action-errors";import { getProgramResourceUploadUrlAction } from "@/lib/actions/partners/program-resources/get-program-resource-upload-url";import { useAction } from "next-safe-action/hooks";@@ -19,27 +20,33 @@ export function useUploadProgramResource(workspaceId: string) {resourceType: opts.resourceType,name: opts.name,extension: opts.extension,- fileSize: opts.file.size,+ contentType: opts.file.type,+ contentLength: opts.file.size,});- if (!result?.data) throw new Error("Failed to get upload URL");-- const { signedUrl, key, fileSize } = result.data;-- const headers: Record<string, string> = {};- if (opts.resourceType === "logo" && opts.extension === "svg") {- headers["Content-Type"] = "image/svg+xml";+ if (!result?.data) {+ throw new Error(+ parseActionError(result ?? {}, "Failed to get upload URL"),+ );}+ const { signedUrl, key } = result.data;+const response = await fetch(signedUrl, {method: "PUT",- headers,+ headers: {+ "Content-Type": opts.file.type,+ "Content-Length": opts.file.size.toString(),+ },body: opts.file,});if (!response.ok) throw new Error(`Failed to upload ${opts.resourceType}`);- return { key, fileSize };+ return {+ key,+ fileSize: opts.file.size,+ };};return { upload };diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/program/form.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/program/form.tsxindex eb38b7bf5e..4c49314081 100644--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/program/form.tsx+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/program/form.tsx@@ -3,9 +3,11 @@import { parseActionError } from "@/lib/actions/parse-action-errors";import { onboardProgramAction } from "@/lib/actions/partners/onboard-program";import { testIds } from "@/lib/e2e/test-ids";+import { UPLOAD_POLICIES } from "@/lib/storage/upload-policies";import useWorkspace from "@/lib/swr/use-workspace";import { ProgramData } from "@/lib/types";import { Button, FileUpload, Input, useMediaQuery } from "@dub/ui";+import { toErrorMessage } from "@dub/utils";import { Plus } from "lucide-react";import { usePlausible } from "next-plausible";import { useAction } from "next-safe-action/hooks";@@ -14,6 +16,9 @@ import { Controller, useFormContext } from "react-hook-form";import { toast } from "sonner";import { useOnboardingProgress } from "../../use-onboarding-progress";+const { contentTypes, maxBytes } = UPLOAD_POLICIES.programLogos;+const maxFileSizeMB = maxBytes / (1024 * 1024);+export function Form() {const { isMobile } = useMediaQuery();const [isUploading, setIsUploading] = useState(false);@@ -74,14 +79,20 @@ export function Form() {`/api/workspaces/${workspaceId}/upload-url`,{method: "POST",+ headers: {+ "Content-Type": "application/json",+ },body: JSON.stringify({- folder: "program-logos",+ folder: "programLogos",+ contentType: file.type,+ contentLength: file.size,}),},);if (!response.ok) {- throw new Error("Failed to get signed URL for upload.");+ const { error } = await response.json();+ throw new Error(toErrorMessage(error));}const { signedUrl, destinationUrl } = await response.json();@@ -104,7 +115,7 @@ export function Form() {testId: testIds.onboarding.programLogoUploaded,});} catch (e) {- toast.error("Failed to upload logo");+ toast.error(toErrorMessage(e));} finally {setIsUploading(false);}@@ -155,7 +166,7 @@ export function Form() {rules={{ required: true }}render={({ field }) => (<FileUpload- accept="images"+ acceptedFileTypes={contentTypes}className="size-14 rounded-lg"iconClassName="size-4 text-neutral-800"icon={Plus}@@ -165,7 +176,7 @@ export function Form() {readFileonChange={({ file }) => handleUpload(file)}content={null}- maxFileSizeMB={2}+ maxFileSizeMB={maxFileSizeMB}data-testid={testIds.onboarding.programLogo}/>)}diff --git a/apps/web/lib/actions/partners/program-resources/get-program-resource-upload-url.ts b/apps/web/lib/actions/partners/program-resources/get-program-resource-upload-url.tsindex 1259f02ecb..329e45e291 100644--- a/apps/web/lib/actions/partners/program-resources/get-program-resource-upload-url.ts+++ b/apps/web/lib/actions/partners/program-resources/get-program-resource-upload-url.ts@@ -2,14 +2,14 @@import { createId } from "@/lib/api/create-id";import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";-import { prisma } from "@/lib/prisma";-import { storage } from "@/lib/storage";-import { nanoid, R2_URL } from "@dub/utils";+import { createSignedUploadUrl } from "@/lib/storage/create-signed-upload-url";+import { signedUploadInputSchema } from "@/lib/storage/schemas";+import { validateSignedUpload } from "@/lib/storage/validate-signed-upload";+import { nanoid } from "@dub/utils";import slugify from "@sindresorhus/slugify";import * as z from "zod/v4";import { authActionClient } from "../../safe-action";import { throwIfNoPermission } from "../../throw-if-no-permission";-import { MAX_PROGRAM_RESOURCE_FILE_SIZE_BYTES } from "./constants";const schema = z.object({workspaceId: z.string(),@@ -19,57 +19,50 @@ const schema = z.object({.string().regex(/^[a-zA-Z0-9_-]+$/, "Invalid file extension").nullish(),- fileSize: z.number().int().positive(),+ ...signedUploadInputSchema.shape,});export const getProgramResourceUploadUrlAction = authActionClient.inputSchema(schema).action(async ({ ctx, parsedInput }) => {const { workspace } = ctx;- const { resourceType, name, extension, fileSize } = parsedInput;+ const { resourceType, name, extension, contentType, contentLength } =+ parsedInput;throwIfNoPermission({role: workspace.role,requiredRoles: ["owner", "member"],});- if (fileSize > MAX_PROGRAM_RESOURCE_FILE_SIZE_BYTES) {- throw new Error(- `File size exceeds the maximum allowed size of ${MAX_PROGRAM_RESOURCE_FILE_SIZE_BYTES / 1024 / 1024}MB`,- );- }-const programId = getDefaultProgramIdOrThrow(workspace);-- const program = await prisma.program.findUnique({- where: {- id: programId,- workspaceId: workspace.id,- },- select: {- id: true,- },- });-- if (!program) throw new Error("Program not found");-const resourceId = createId({ prefix: "pgr_" });+const sanitizedExtension = extension? extension.replace(/^\.+/, "").replace(/[^a-zA-Z0-9_-]/g, ""): null;- const key = `programs/${program.id}/${resourceType}s/${slugify(name || resourceType)}-${nanoid(4)}${sanitizedExtension ? `.${sanitizedExtension}` : ""}`;+ const key = `programs/${programId}/${resourceType}s/${slugify(name || resourceType)}-${nanoid(4)}${sanitizedExtension ? `.${sanitizedExtension}` : ""}`;++ const uploadPolicy =+ resourceType === "logo"+ ? ("programResourceLogos" as const)+ : ("programResourceFiles" as const);++ validateSignedUpload({+ contentLength,+ contentType,+ policy: uploadPolicy,+ });- const signedUrl = await storage.getSignedUploadUrl({+ const { signedUrl, destinationUrl } = await createSignedUploadUrl({key,- expiresIn: 300,- contentLength: fileSize,+ contentType,+ contentLength,});return {signedUrl,- destinationUrl: `${R2_URL}/${key}`,+ destinationUrl,resourceId,key,- fileSize,};});diff --git a/apps/web/lib/actions/partners/upload-bounty-submission-file.ts b/apps/web/lib/actions/partners/upload-bounty-submission-file.tsindex 897a803f53..5bf6e62517 100644--- a/apps/web/lib/actions/partners/upload-bounty-submission-file.ts+++ b/apps/web/lib/actions/partners/upload-bounty-submission-file.ts@@ -2,6 +2,7 @@import { getProgramEnrollmentOrThrow } from "@/lib/api/programs/get-program-enrollment-or-throw";import { getBountySubmissionUploadUrl } from "@/lib/bounty/api/get-bounty-submission-upload-url";+import { signedUploadInputSchema } from "@/lib/storage/schemas";import * as z from "zod/v4";import { authPartnerActionClient } from "../safe-action";@@ -9,8 +10,7 @@ const schema = z.object({programId: z.string(),bountyId: z.string(),fileName: z.string().trim().min(1),- contentType: z.string().trim().min(1),- contentLength: z.number().int().positive(),+ ...signedUploadInputSchema.shape,});export const uploadBountySubmissionFileAction = authPartnerActionClientdiff --git a/apps/web/lib/actions/partners/upload-campaign-image.ts b/apps/web/lib/actions/partners/upload-campaign-image.tsindex d6ac083978..da2a8a5964 100644--- a/apps/web/lib/actions/partners/upload-campaign-image.ts+++ b/apps/web/lib/actions/partners/upload-campaign-image.ts@@ -1,20 +1,24 @@"use server";import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";-import { storage } from "@/lib/storage";-import { nanoid, R2_URL } from "@dub/utils";+import { createSignedUploadUrl } from "@/lib/storage/create-signed-upload-url";+import { signedUploadInputSchema } from "@/lib/storage/schemas";+import { validateSignedUpload } from "@/lib/storage/validate-signed-upload";+import { nanoid } from "@dub/utils";import * as z from "zod/v4";import { authActionClient } from "../safe-action";import { throwIfNoPermission } from "../throw-if-no-permission";-const schema = z.object({+const inputSchema = z.object({workspaceId: z.string(),+ ...signedUploadInputSchema.shape,});export const uploadCampaignImageAction = authActionClient- .inputSchema(schema)- .action(async ({ ctx }) => {+ .inputSchema(inputSchema)+ .action(async ({ ctx, parsedInput }) => {const { workspace } = ctx;+ const { contentType, contentLength } = parsedInput;throwIfNoPermission({role: workspace.role,@@ -23,18 +27,21 @@ export const uploadCampaignImageAction = authActionClientconst programId = getDefaultProgramIdOrThrow(workspace);- try {- const key = `programs/${programId}/emails/image_${nanoid(7)}`;- const signedUrl = await storage.getSignedUploadUrl({- key,- });-- return {- key,- signedUrl,- destinationUrl: `${R2_URL}/${key}`,- };- } catch (e) {- throw new Error("Failed to get signed URL for upload.");- }+ validateSignedUpload({+ contentLength,+ contentType,+ policy: "programCampaignImages",+ });++ const { key, signedUrl, destinationUrl } = await createSignedUploadUrl({+ key: `programs/${programId}/emails/image_${nanoid(10)}`,+ contentType,+ contentLength,+ });++ return {+ key,+ signedUrl,+ destinationUrl,+ };});diff --git a/apps/web/lib/actions/partners/upload-lander-image.ts b/apps/web/lib/actions/partners/upload-lander-image.tsindex 9465bd04e7..afac2e1d0c 100644--- a/apps/web/lib/actions/partners/upload-lander-image.ts+++ b/apps/web/lib/actions/partners/upload-lander-image.ts@@ -1,20 +1,24 @@"use server";import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";-import { storage } from "@/lib/storage";-import { nanoid, R2_URL } from "@dub/utils";+import { createSignedUploadUrl } from "@/lib/storage/create-signed-upload-url";+import { signedUploadInputSchema } from "@/lib/storage/schemas";+import { validateSignedUpload } from "@/lib/storage/validate-signed-upload";+import { nanoid } from "@dub/utils";import * as z from "zod/v4";import { authActionClient } from "../safe-action";import { throwIfNoPermission } from "../throw-if-no-permission";-const schema = z.object({+const inputSchema = z.object({workspaceId: z.string(),+ ...signedUploadInputSchema.shape,});export const uploadLanderImageAction = authActionClient- .inputSchema(schema)- .action(async ({ ctx }) => {+ .inputSchema(inputSchema)+ .action(async ({ ctx, parsedInput }) => {const { workspace } = ctx;+ const { contentType, contentLength } = parsedInput;throwIfNoPermission({role: workspace.role,@@ -23,19 +27,21 @@ export const uploadLanderImageAction = authActionClientconst programId = getDefaultProgramIdOrThrow(workspace);- try {- const key = `programs/${programId}/lander/image_${nanoid(7)}`;-- const signedUrl = await storage.getSignedUploadUrl({- key,- });-- return {- key,- signedUrl,- destinationUrl: `${R2_URL}/${key}`,- };- } catch (e) {- throw new Error("Failed to get signed URL for upload.");- }+ validateSignedUpload({+ contentLength,+ contentType,+ policy: "programLanderImages",+ });++ const { key, signedUrl, destinationUrl } = await createSignedUploadUrl({+ key: `programs/${programId}/lander/image_${nanoid(10)}`,+ contentType,+ contentLength,+ });++ return {+ key,+ signedUrl,+ destinationUrl,+ };});diff --git a/apps/web/lib/actions/partners/upload-program-application-image.ts b/apps/web/lib/actions/partners/upload-program-application-image.tsindex cd0cb881be..4b94debed4 100644--- a/apps/web/lib/actions/partners/upload-program-application-image.ts+++ b/apps/web/lib/actions/partners/upload-program-application-image.ts@@ -2,36 +2,35 @@import { getIP } from "@/lib/api/utils/get-ip";import { prisma } from "@/lib/prisma";-import { storage } from "@/lib/storage";-import { ratelimit } from "@/lib/upstash";+import { createSignedUploadUrl } from "@/lib/storage/create-signed-upload-url";+import { signedUploadInputSchema } from "@/lib/storage/schemas";+import { validateSignedUpload } from "@/lib/storage/validate-signed-upload";+import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";-import { nanoid, R2_URL } from "@dub/utils";+import { nanoid } from "@dub/utils";import * as z from "zod/v4";import { actionClient } from "../safe-action";const inputSchema = z.object({programSlug: z.string().trim().toLowerCase().min(1),+ ...signedUploadInputSchema.shape,});-const rateLimitPolicy = RATELIMIT_POLICIES.programImageUpload;-export const uploadProgramApplicationImageAction = actionClient.inputSchema(inputSchema).action(async ({ parsedInput }) => {- const { programSlug } = parsedInput;-- const ipAddress = await getIP();+ const { programSlug, contentType, contentLength } = parsedInput;- const { success } = await ratelimit(- rateLimitPolicy.attempts,- rateLimitPolicy.window,- ).limit(`${rateLimitPolicy.keyPrefix}:${ipAddress}`);+ validateSignedUpload({+ contentLength,+ contentType,+ policy: "programApplicationImages",+ });- if (!success) {- throw new Error(- "You've reached the maximum number of attempts to upload images for this application. Please try again later.",- );- }+ await assertRateLimit({+ policy: RATELIMIT_POLICIES.programImageUpload,+ identifier: await getIP(),+ });const program = await prisma.program.findUniqueOrThrow({where: {@@ -42,13 +41,14 @@ export const uploadProgramApplicationImageAction = actionClient},});- const key = `programs/${program.id}/applications/${nanoid(10)}`;- const signedUrl = await storage.getSignedUploadUrl({- key,+ const { signedUrl, destinationUrl } = await createSignedUploadUrl({+ key: `programs/${program.id}/applications/${nanoid(10)}`,+ contentType,+ contentLength,});return {signedUrl,- destinationUrl: `${R2_URL}/${key}`,+ destinationUrl,};});diff --git a/apps/web/lib/bounty/api/get-bounty-submission-upload-url.ts b/apps/web/lib/bounty/api/get-bounty-submission-upload-url.tsindex 216a5d02c3..836ae448fa 100644--- a/apps/web/lib/bounty/api/get-bounty-submission-upload-url.ts+++ b/apps/web/lib/bounty/api/get-bounty-submission-upload-url.ts@@ -1,24 +1,25 @@import { DubApiError } from "@/lib/api/errors";-import { storage } from "@/lib/storage";-import { ratelimit } from "@/lib/upstash";+import { createSignedUploadUrl } from "@/lib/storage/create-signed-upload-url";+import { signedUploadInputSchema } from "@/lib/storage/schemas";+import { validateSignedUpload } from "@/lib/storage/validate-signed-upload";+import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";+import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";import { submissionRequirementsSchema } from "@/lib/zod/schemas/bounties";import { ACTIVE_ENROLLMENT_STATUSES } from "@/lib/zod/schemas/partners";-import { nanoid, R2_URL } from "@dub/utils";+import { nanoid } from "@dub/utils";import { ProgramEnrollment, ProgramPartnerTag } from "@prisma/client";+import * as z from "zod/v4";import {bountyEligibilityIncludes,canPartnerSubmitBounty,} from "./bounty-availability";import { getBountyOrThrow } from "./get-bounty-or-throw";-const MAX_ATTEMPTS = 25;-const CACHE_KEY_PREFIX = "bounty:submission:file:upload";--type GetBountySubmissionUploadUrlParams = {+type GetBountySubmissionUploadUrlParams = z.infer<+ typeof signedUploadInputSchema+> & {bountyId: string;fileName: string;- contentType: string;- contentLength: number;programEnrollment: Pick<ProgramEnrollment,"programId" | "partnerId" | "groupId" | "status" | "createdAt"@@ -27,14 +28,6 @@ type GetBountySubmissionUploadUrlParams = {};};-const MAX_UPLOAD_SIZE_BYTES = 5 * 1024 * 1024;-const ALLOWED_IMAGE_CONTENT_TYPES = new Set([- "image/jpeg",- "image/png",- "image/webp",- "image/svg+xml",-]);-export async function getBountySubmissionUploadUrl({bountyId,fileName,@@ -58,35 +51,16 @@ export async function getBountySubmissionUploadUrl({});}- if (!ALLOWED_IMAGE_CONTENT_TYPES.has(contentType)) {- throw new DubApiError({- code: "unprocessable_entity",- message: "Unsupported file type. Please upload SVG, JPG, PNG, or WEBP.",- });- }-- if (- !Number.isInteger(contentLength) ||- contentLength <= 0 ||- contentLength > MAX_UPLOAD_SIZE_BYTES- ) {- throw new DubApiError({- code: "unprocessable_entity",- message: "File size exceeds maximum of 5MB.",- });- }-- const { success } = await ratelimit(MAX_ATTEMPTS, "24 h").limit(- `${CACHE_KEY_PREFIX}:${bountyId}:${partnerId}`,- );+ validateSignedUpload({+ contentLength,+ contentType,+ policy: "bountySubmissionImages",+ });- if (!success) {- throw new DubApiError({- code: "rate_limit_exceeded",- message:- "You've reached the maximum number of attempts to upload a file for this bounty.",- });- }+ await assertRateLimit({+ policy: RATELIMIT_POLICIES.bountySubmissionUpload,+ identifier: [bountyId, partnerId],+ });const bounty = await getBountyOrThrow({bountyId,@@ -138,18 +112,21 @@ export async function getBountySubmissionUploadUrl({}try {- const key = `programs/${programId}/bounties/${bountyId}/submissions/${partnerId}/${nanoid(7)}`;- const signedUrl = await storage.getSignedUploadUrl({- key,- contentLength,+ const { signedUrl, destinationUrl } = await createSignedUploadUrl({+ key: `programs/${programId}/bounties/${bountyId}/submissions/${partnerId}/${nanoid(10)}`,contentType,+ contentLength,});return {signedUrl,- destinationUrl: `${R2_URL}/${key}`,+ destinationUrl,};} catch (e) {+ if (e instanceof DubApiError) {+ throw e;+ }+throw new DubApiError({code: "internal_server_error",message: "Failed to get signed URL for upload.",diff --git a/apps/web/lib/jobs/handlers/process-shopify-order-job.ts b/apps/web/lib/jobs/handlers/process-shopify-order-job.tsindex dc369276ec..bf13e9f273 100644--- a/apps/web/lib/jobs/handlers/process-shopify-order-job.ts+++ b/apps/web/lib/jobs/handlers/process-shopify-order-job.ts@@ -46,12 +46,6 @@ export const processShopifyOrderJob = defineJob({clickId,});- // Keep this for a while to help us debug issues with the job.- logger.info("shopify.order.processed", {- ...result,- workspaceId: workspace.id,- });-await logger.flush();await captureWebhookLog({@@ -68,11 +62,6 @@ export const processShopifyOrderJob = defineJob({responseBody: serializeError(error),});- logger.error("shopify.order.failed", {- error: serializeError(error),- workspaceId: workspace.id,- });-await logger.flush();}},diff --git a/apps/web/lib/messages/constants.ts b/apps/web/lib/messages/constants.tsindex c4f25206a0..8d0c248d27 100644--- a/apps/web/lib/messages/constants.ts+++ b/apps/web/lib/messages/constants.ts@@ -2,30 +2,8 @@ export const MAX_MESSAGE_LENGTH = 2000;export const MAX_ATTACHMENTS_PER_MESSAGE = 5;-export const MAX_ATTACHMENT_SIZE_BYTES = 10 * 1024 * 1024; // 10MB-export const MAX_ATTACHMENT_NAME_LENGTH = 255;-export const PROGRAM_ALLOWED_ATTACHMENT_TYPES = [- "image/png",- "image/jpeg",- "image/webp",- "application/pdf",-] as const;--export const PARTNER_ALLOWED_ATTACHMENT_TYPES = [- "image/png",- "image/jpeg",- "image/webp",-] as const;--export const ATTACHMENT_MIME_TYPE_LABELS: Record<string, string> = {- "application/pdf": "PDF",- "image/png": "PNG",- "image/jpeg": "JPG",- "image/webp": "WEBP",-};-// MIME types that are safe to render as inline image previews.export const PREVIEWABLE_IMAGE_TYPES = new Set(["image/png",diff --git a/apps/web/lib/messages/schemas.ts b/apps/web/lib/messages/schemas.tsindex 6e1672c648..6a5222991d 100644--- a/apps/web/lib/messages/schemas.ts+++ b/apps/web/lib/messages/schemas.ts@@ -1,8 +1,8 @@import {- MAX_ATTACHMENT_SIZE_BYTES,MAX_ATTACHMENTS_PER_MESSAGE,MAX_MESSAGE_LENGTH,} from "@/lib/messages/constants";+import { UPLOAD_POLICIES } from "@/lib/storage/upload-policies";import { MessageType } from "@prisma/client";import * as z from "zod/v4";import { PartnerSchema } from "../zod/schemas/partners";@@ -22,12 +22,27 @@ export const MessageAttachmentSchema = z.object({createdAt: z.date(),});-export const messageAttachmentInputSchema = z.object({- storageKey: z.string().min(1),- name: z.string().min(1).max(255),- size: z.number().int().positive().max(MAX_ATTACHMENT_SIZE_BYTES),- type: z.string().min(1),-});+const createMessageAttachmentInputSchema = (maxBytes: number) =>+ z.object({+ storageKey: z.string().min(1),+ name: z.string().min(1).max(255),+ size: z.number().int().positive().max(maxBytes),+ type: z.string().min(1),+ });++export const programMessageAttachmentInputSchema =+ createMessageAttachmentInputSchema(+ UPLOAD_POLICIES.programMessageAttachments.maxBytes,+ );++export const partnerMessageAttachmentInputSchema =+ createMessageAttachmentInputSchema(+ UPLOAD_POLICIES.partnerMessageAttachments.maxBytes,+ );++export type MessageAttachmentInput = z.infer<+ typeof programMessageAttachmentInputSchema+>;export const MessageSchema = z.object({id: z.string(),@@ -81,7 +96,7 @@ export const messagePartnerSchema = z.object({partnerId: z.string(),text: messageTextSchema,attachments: z- .array(messageAttachmentInputSchema)+ .array(programMessageAttachmentInputSchema).max(MAX_ATTACHMENTS_PER_MESSAGE).default([]),});@@ -110,7 +125,7 @@ export const messageProgramSchema = z.object({programSlug: z.string(),text: messageTextSchema,attachments: z- .array(messageAttachmentInputSchema)+ .array(partnerMessageAttachmentInputSchema).max(MAX_ATTACHMENTS_PER_MESSAGE).default([]),});diff --git a/apps/web/lib/messages/upload-message-attachment.ts b/apps/web/lib/messages/upload-message-attachment.tsindex 11512bb930..1d0b1b09f4 100644--- a/apps/web/lib/messages/upload-message-attachment.ts+++ b/apps/web/lib/messages/upload-message-attachment.ts@@ -1,14 +1,12 @@"use server";import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";-import {- MAX_ATTACHMENT_NAME_LENGTH,- MAX_ATTACHMENT_SIZE_BYTES,- PROGRAM_ALLOWED_ATTACHMENT_TYPES,-} from "@/lib/messages/constants";+import { MAX_ATTACHMENT_NAME_LENGTH } from "@/lib/messages/constants";import { sanitizeFileName } from "@/lib/messages/utils";-import { storage } from "@/lib/storage";-import { ratelimit } from "@/lib/upstash";+import { createSignedUploadUrl } from "@/lib/storage/create-signed-upload-url";+import { signedUploadInputSchema } from "@/lib/storage/schemas";+import { validateSignedUpload } from "@/lib/storage/validate-signed-upload";+import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";import { nanoid } from "@dub/utils";import * as z from "zod/v4";@@ -18,12 +16,9 @@ import { throwIfNoPermission } from "../actions/throw-if-no-permission";const schema = z.object({workspaceId: z.string(),fileName: z.string().trim().min(1).max(MAX_ATTACHMENT_NAME_LENGTH),- contentType: z.enum(PROGRAM_ALLOWED_ATTACHMENT_TYPES),- contentLength: z.number().int().positive().max(MAX_ATTACHMENT_SIZE_BYTES),+ ...signedUploadInputSchema.shape,});-const rateLimitPolicy = RATELIMIT_POLICIES.messageAttachmentUpload;-export const uploadMessageAttachmentAction = authActionClient.inputSchema(schema).action(async ({ ctx, parsedInput }) => {@@ -37,26 +32,25 @@ export const uploadMessageAttachmentAction = authActionClientconst programId = getDefaultProgramIdOrThrow(workspace);- const { success } = await ratelimit(- rateLimitPolicy.attempts,- rateLimitPolicy.window,- ).limit(`${rateLimitPolicy.keyPrefix}:${user.id}`);-- if (!success) {- throw new Error("Too many file uploads. Please try again later.");- }+ validateSignedUpload({+ contentLength,+ contentType,+ policy: "programMessageAttachments",+ });- const storageKey = `messages/${programId}/${nanoid(10)}/${sanitizeFileName(fileName)}`;+ await assertRateLimit({+ policy: RATELIMIT_POLICIES.messageAttachmentUpload,+ identifier: user.id,+ });- const signedUrl = await storage.getSignedUploadUrl({- key: storageKey,+ const { key, signedUrl } = await createSignedUploadUrl({+ key: `messages/${programId}/${nanoid(10)}/${sanitizeFileName(fileName)}`,bucket: "private",contentLength,contentType,});-return {signedUrl,- storageKey,+ storageKey: key,};});diff --git a/apps/web/lib/messages/upload-partner-message-attachment.ts b/apps/web/lib/messages/upload-partner-message-attachment.tsindex 9d6e0c4cfa..21d9efae1a 100644--- a/apps/web/lib/messages/upload-partner-message-attachment.ts+++ b/apps/web/lib/messages/upload-partner-message-attachment.ts@@ -1,14 +1,12 @@"use server";-import {- MAX_ATTACHMENT_NAME_LENGTH,- MAX_ATTACHMENT_SIZE_BYTES,- PARTNER_ALLOWED_ATTACHMENT_TYPES,-} from "@/lib/messages/constants";+import { MAX_ATTACHMENT_NAME_LENGTH } from "@/lib/messages/constants";import { sanitizeFileName } from "@/lib/messages/utils";import { prisma } from "@/lib/prisma";-import { storage } from "@/lib/storage";-import { ratelimit } from "@/lib/upstash";+import { createSignedUploadUrl } from "@/lib/storage/create-signed-upload-url";+import { signedUploadInputSchema } from "@/lib/storage/schemas";+import { validateSignedUpload } from "@/lib/storage/validate-signed-upload";+import { assertRateLimit } from "@/lib/upstash/assert-rate-limit";import { RATELIMIT_POLICIES } from "@/lib/upstash/ratelimit-policies";import { nanoid } from "@dub/utils";import * as z from "zod/v4";@@ -18,11 +16,10 @@ import { COMMISSION_ELIGIBLE_ENROLLMENT_STATUSES } from "../zod/schemas/partnersconst schema = z.object({programSlug: z.string(),fileName: z.string().trim().min(1).max(MAX_ATTACHMENT_NAME_LENGTH),- contentType: z.enum(PARTNER_ALLOWED_ATTACHMENT_TYPES),- contentLength: z.number().int().positive().max(MAX_ATTACHMENT_SIZE_BYTES),+ ...signedUploadInputSchema.shape,});-const rateLimitPolicy = RATELIMIT_POLICIES.messageAttachmentUpload;+const uploadPolicy = "partnerMessageAttachments" as const;export const uploadPartnerMessageAttachmentAction = authPartnerActionClient.inputSchema(schema)@@ -30,14 +27,16 @@ export const uploadPartnerMessageAttachmentAction = authPartnerActionClientconst { partner } = ctx;const { programSlug, fileName, contentType, contentLength } = parsedInput;- const { success } = await ratelimit(- rateLimitPolicy.attempts,- rateLimitPolicy.window,- ).limit(`${rateLimitPolicy.keyPrefix}:${partner.id}`);+ validateSignedUpload({+ contentLength,+ contentType,+ policy: uploadPolicy,+ });- if (!success) {- throw new Error("Too many file uploads. Please try again later.");- }+ await assertRateLimit({+ policy: RATELIMIT_POLICIES.messageAttachmentUpload,+ identifier: partner.id,+ });const program = await prisma.program.findFirst({select: {@@ -79,10 +78,8 @@ export const uploadPartnerMessageAttachmentAction = authPartnerActionClientthrow new Error("You are not able to message this program.");}- const storageKey = `messages/${program.id}/${nanoid(10)}/${sanitizeFileName(fileName)}`;-- const signedUrl = await storage.getSignedUploadUrl({- key: storageKey,+ const { key, signedUrl } = await createSignedUploadUrl({+ key: `messages/${program.id}/${nanoid(10)}/${sanitizeFileName(fileName)}`,bucket: "private",contentLength,contentType,@@ -90,6 +87,6 @@ export const uploadPartnerMessageAttachmentAction = authPartnerActionClientreturn {signedUrl,- storageKey,+ storageKey: key,};});diff --git a/apps/web/lib/messages/utils.ts b/apps/web/lib/messages/utils.tsindex 591a706c83..3d93c63427 100644--- a/apps/web/lib/messages/utils.ts+++ b/apps/web/lib/messages/utils.ts@@ -1,8 +1,5 @@import { createId } from "@/lib/api/create-id";-import {- ATTACHMENT_MIME_TYPE_LABELS,- PREVIEWABLE_IMAGE_TYPES,-} from "./constants";+import { PREVIEWABLE_IMAGE_TYPES } from "./constants";export const messageAttachmentsOrderBy = { createdAt: "asc" } as const;@@ -46,14 +43,6 @@ export function sanitizeFileName(name: string): string {.replace(/[\x00-\x1F\x7F/\\?#%]/g, (ch) => encodeURIComponent(ch));}-export function getAttachmentTypeLabel(mimeType: string): string {- return (- ATTACHMENT_MIME_TYPE_LABELS[mimeType] ||- mimeType.split("/").pop()?.toUpperCase() ||- "FILE"- );-}-export function isPreviewableImageType(mimeType: string): boolean {return PREVIEWABLE_IMAGE_TYPES.has(mimeType);}diff --git a/apps/web/lib/storage/create-signed-upload-url.ts b/apps/web/lib/storage/create-signed-upload-url.tsnew file mode 100644index 0000000000..3e89ee5342--- /dev/null+++ b/apps/web/lib/storage/create-signed-upload-url.ts@@ -0,0 +1,27 @@+import { storage } from "@/lib/storage";+import { R2_URL } from "@dub/utils";+import * as z from "zod/v4";+import { signedUploadInputSchema } from "./schemas";++export async function createSignedUploadUrl({+ key,+ contentLength,+ contentType,+ bucket = "public",+}: z.infer<typeof signedUploadInputSchema> & {+ key: string;+ bucket?: "public" | "private";+}) {+ const signedUrl = await storage.getSignedUploadUrl({+ key,+ bucket,+ contentLength,+ contentType,+ });++ return {+ key,+ signedUrl,+ destinationUrl: `${R2_URL}/${key}`,+ };+}diff --git a/apps/web/lib/storage/schemas.ts b/apps/web/lib/storage/schemas.tsnew file mode 100644index 0000000000..4fff18eac7--- /dev/null+++ b/apps/web/lib/storage/schemas.ts@@ -0,0 +1,6 @@+import * as z from "zod/v4";++export const signedUploadInputSchema = z.object({+ contentType: z.string().trim().min(1),+ contentLength: z.number().int().positive(),+});diff --git a/apps/web/lib/storage/upload-policies.ts b/apps/web/lib/storage/upload-policies.tsnew file mode 100644index 0000000000..640fcdd254--- /dev/null+++ b/apps/web/lib/storage/upload-policies.ts@@ -0,0 +1,106 @@+const RASTER_IMAGE_CONTENT_TYPES = [+ "image/jpeg",+ "image/png",+ "image/webp",+ "image/gif",+ "image/avif",+] as const;++const PROGRAM_RESOURCE_LOGO_CONTENT_TYPES = [+ "image/png",+ "image/jpeg",+ "image/webp",+ "image/svg+xml",+ "image/avif",+] as const;++const PROGRAM_RESOURCE_FILE_CONTENT_TYPES = [+ ...PROGRAM_RESOURCE_LOGO_CONTENT_TYPES,+ "application/pdf",+ "text/plain",+ "application/msword",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document",+ "application/vnd.ms-excel",+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",+ "text/csv",+ "application/zip",+] as const;++// Human-readable labels for MIME types used across upload policies.+const MIME_TYPE_LABELS: Record<string, string> = {+ "image/jpeg": "JPG",+ "image/png": "PNG",+ "image/webp": "WEBP",+ "image/gif": "GIF",+ "image/avif": "AVIF",+ "image/svg+xml": "SVG",+ "application/pdf": "PDF",+ "text/plain": "TXT",+ "application/msword": "DOC",+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document":+ "DOCX",+ "application/vnd.ms-excel": "XLS",+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "XLSX",+ "text/csv": "CSV",+ "application/zip": "ZIP",+};++export const UPLOAD_POLICIES = {+ integrationScreenshots: {+ contentTypes: RASTER_IMAGE_CONTENT_TYPES,+ maxBytes: 5 * 1024 * 1024,+ },++ programLogos: {+ contentTypes: RASTER_IMAGE_CONTENT_TYPES,+ maxBytes: 5 * 1024 * 1024,+ },++ programApplicationImages: {+ contentTypes: RASTER_IMAGE_CONTENT_TYPES,+ maxBytes: 5 * 1024 * 1024,+ },++ programCampaignImages: {+ contentTypes: RASTER_IMAGE_CONTENT_TYPES,+ maxBytes: 5 * 1024 * 1024,+ },++ programLanderImages: {+ contentTypes: PROGRAM_RESOURCE_LOGO_CONTENT_TYPES,+ maxBytes: 5 * 1024 * 1024,+ },++ programMessageAttachments: {+ contentTypes: ["image/png", "image/jpeg", "image/webp", "application/pdf"],+ maxBytes: 10 * 1024 * 1024,+ },++ partnerMessageAttachments: {+ contentTypes: ["image/png", "image/jpeg", "image/webp"],+ maxBytes: 10 * 1024 * 1024,+ },++ programResourceLogos: {+ contentTypes: PROGRAM_RESOURCE_LOGO_CONTENT_TYPES,+ maxBytes: 10 * 1024 * 1024,+ },++ programResourceFiles: {+ contentTypes: PROGRAM_RESOURCE_FILE_CONTENT_TYPES,+ maxBytes: 10 * 1024 * 1024,+ },++ bountySubmissionImages: {+ contentTypes: ["image/jpeg", "image/png", "image/webp"] as const,+ maxBytes: 5 * 1024 * 1024,+ },+} as const;++export function getMimeTypeLabel(mimeType: string): string {+ return (+ MIME_TYPE_LABELS[mimeType] ||+ mimeType.split("/").pop()?.toUpperCase() ||+ "FILE"+ );+}diff --git a/apps/web/lib/storage/validate-signed-upload.ts b/apps/web/lib/storage/validate-signed-upload.tsnew file mode 100644index 0000000000..f2ecd940a4--- /dev/null+++ b/apps/web/lib/storage/validate-signed-upload.ts@@ -0,0 +1,48 @@+import { DubApiError } from "@/lib/api/errors";+import { UPLOAD_POLICIES } from "./upload-policies";++export function validateSignedUpload({+ contentLength,+ contentType,+ policy,+}: {+ contentLength: number;+ contentType: string;+ policy: keyof typeof UPLOAD_POLICIES;+}) {+ const uploadPolicy = UPLOAD_POLICIES[policy];++ if (!uploadPolicy) {+ throw new DubApiError({+ code: "bad_request",+ message: `Invalid policy: ${policy}`,+ });+ }++ const allowedContentTypes = uploadPolicy.contentTypes as readonly string[];++ if (!allowedContentTypes.includes(contentType)) {+ throw new DubApiError({+ code: "unprocessable_entity",+ message: `Invalid content type. Must be one of: ${uploadPolicy.contentTypes.join(", ")}`,+ });+ }++ if (!Number.isInteger(contentLength) || contentLength <= 0) {+ throw new DubApiError({+ code: "unprocessable_entity",+ message: "contentLength must be a positive integer.",+ });+ }++ if (contentLength > uploadPolicy.maxBytes) {+ throw new DubApiError({+ code: "unprocessable_entity",+ message: `File size exceeds the maximum allowed size of ${+ uploadPolicy.maxBytes / 1024 / 1024+ }MB`,+ });+ }++ return uploadPolicy;+}diff --git a/apps/web/lib/upstash/ratelimit-policies.ts b/apps/web/lib/upstash/ratelimit-policies.tsindex 5ef9524a9a..34cfc59acc 100644--- a/apps/web/lib/upstash/ratelimit-policies.ts+++ b/apps/web/lib/upstash/ratelimit-policies.ts@@ -2,17 +2,17 @@ import { ratelimit } from "./ratelimit";type RatelimitWindow = Parameters<typeof ratelimit>[1] & string;+export type RatelimitMessageContext = {+ retryAfter: string;+ attempts: number;+ window: string;+};+export type RatelimitPolicy = {attempts: number;window: RatelimitWindow;keyPrefix: string;- message?:- | string- | ((ctx: {- retryAfter: string;- attempts: number;- window: string;- }) => string);+ message?: string | ((ctx: RatelimitMessageContext) => string);};export const RATELIMIT_POLICIES = {@@ -76,12 +76,31 @@ export const RATELIMIT_POLICIES = {attempts: 10,window: "24 h",keyPrefix: "rl:program:application:image:upload",+ message:+ "You've reached the maximum number of attempts to upload images for this application. Please try again later.",},messageAttachmentUpload: {attempts: 20,window: "1 h",keyPrefix: "rl:message:attachment:upload",+ message: "Too many file uploads. Please try again later.",+ },++ bountySubmissionUpload: {+ attempts: 25,+ window: "24 h",+ keyPrefix: "bounty:submission:file:upload",+ message:+ "You've reached the maximum number of attempts to upload a file for this bounty.",+ },++ // Keyed on workspace + user so one member cannot exhaust the workspace upload budget+ workspaceFileUpload: {+ attempts: 20,+ window: "1 h",+ keyPrefix: "rl:workspace:file:upload",+ message: "Too many file uploads. Please try again later.",},partnerProfileInvite: {diff --git a/apps/web/tests/misc/create-signed-upload-url.test.ts b/apps/web/tests/misc/create-signed-upload-url.test.tsnew file mode 100644index 0000000000..9474e8ed25--- /dev/null+++ b/apps/web/tests/misc/create-signed-upload-url.test.ts@@ -0,0 +1,289 @@+import { DubApiError } from "@/lib/api/errors";+import { storage } from "@/lib/storage";+import { createSignedUploadUrl } from "@/lib/storage/create-signed-upload-url";+import { UPLOAD_POLICIES } from "@/lib/storage/upload-policies";+import { validateSignedUpload } from "@/lib/storage/validate-signed-upload";+import { R2_URL } from "@dub/utils";+import { beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("server-only", () => ({}));++vi.mock("@/lib/storage", () => ({+ storage: {+ getSignedUploadUrl: vi.fn(),+ },+}));++const getSignedUploadUrlMock = vi.mocked(storage.getSignedUploadUrl);++describe("createSignedUploadUrl", () => {+ const key = "programs/prog_123/lander/image_abc";+ const signedUrl = "https://signed.example.test/upload";++ beforeEach(() => {+ getSignedUploadUrlMock.mockReset();+ getSignedUploadUrlMock.mockResolvedValue(signedUrl);+ });++ it("returns a signed URL and destination URL", async () => {+ const result = await createSignedUploadUrl({+ key,+ contentType: "image/png",+ contentLength: 1024,+ });++ expect(result).toEqual({+ key,+ signedUrl,+ destinationUrl: `${R2_URL}/${key}`,+ });+ expect(getSignedUploadUrlMock).toHaveBeenCalledWith({+ key,+ bucket: "public",+ contentType: "image/png",+ contentLength: 1024,+ });+ });++ it("forwards the private bucket to the signer", async () => {+ await createSignedUploadUrl({+ key: "messages/prog_123/file.pdf",+ contentType: "application/pdf",+ contentLength: 2048,+ bucket: "private",+ });++ expect(getSignedUploadUrlMock).toHaveBeenCalledWith({+ key: "messages/prog_123/file.pdf",+ bucket: "private",+ contentType: "application/pdf",+ contentLength: 2048,+ });+ });++ it.each([+ "integrationScreenshots",+ "programLogos",+ "programApplicationImages",+ "programCampaignImages",+ "programLanderImages",+ "programResourceLogos",+ "programResourceFiles",+ "bountySubmissionImages",+ ] as const satisfies ReadonlyArray<keyof typeof UPLOAD_POLICIES>)(+ "pins Content-Type and Content-Length into the signer for %s",+ async (policy) => {+ const contentType = UPLOAD_POLICIES[policy].contentTypes[0];+ const contentLength = 2048;++ await createSignedUploadUrl({+ key: `public/${policy}/ok`,+ contentType,+ contentLength,+ });++ expect(getSignedUploadUrlMock).toHaveBeenCalledWith({+ key: `public/${policy}/ok`,+ bucket: "public",+ contentType,+ contentLength,+ });+ },+ );+});++describe("validateSignedUpload", () => {+ it("accepts an allowed upload", () => {+ expect(+ validateSignedUpload({+ policy: "programLanderImages",+ contentType: "image/png",+ contentLength: 1024,+ }),+ ).toEqual(UPLOAD_POLICIES.programLanderImages);+ });++ it("rejects image/svg+xml for bounty submission images", () => {+ expect(() =>+ validateSignedUpload({+ policy: "bountySubmissionImages",+ contentType: "image/svg+xml",+ contentLength: 1024,+ }),+ ).toThrow(+ expect.objectContaining({+ code: "unprocessable_entity",+ message: expect.stringContaining("Invalid content type"),+ } satisfies Partial<DubApiError>),+ );+ });++ it("rejects content types not allowed by the policy", () => {+ expect(() =>+ validateSignedUpload({+ policy: "programLogos",+ contentType: "image/svg+xml",+ contentLength: 1024,+ }),+ ).toThrow(+ expect.objectContaining({+ code: "unprocessable_entity",+ message: expect.stringContaining("Invalid content type"),+ } satisfies Partial<DubApiError>),+ );+ });++ it("rejects an empty content type", () => {+ expect(() =>+ validateSignedUpload({+ policy: "programLogos",+ contentType: "",+ contentLength: 1024,+ }),+ ).toThrow(DubApiError);+ });++ it("rejects non-positive and non-integer content lengths", () => {+ for (const contentLength of [0, -1, 1.5, Number.NaN]) {+ expect(() =>+ validateSignedUpload({+ policy: "programLogos",+ contentType: "image/png",+ contentLength,+ }),+ ).toThrow(+ expect.objectContaining({+ code: "unprocessable_entity",+ message: "contentLength must be a positive integer.",+ }),+ );+ }+ });++ it("rejects files larger than the policy max", () => {+ const maxBytes = UPLOAD_POLICIES.programLogos.maxBytes;++ expect(() =>+ validateSignedUpload({+ policy: "programLogos",+ contentType: "image/png",+ contentLength: maxBytes + 1,+ }),+ ).toThrow(+ expect.objectContaining({+ code: "unprocessable_entity",+ message: "File size exceeds the maximum allowed size of 5MB",+ }),+ );+ });++ it("allows uploads at the exact policy size limit", () => {+ const maxBytes = UPLOAD_POLICIES.programLogos.maxBytes;++ expect(+ validateSignedUpload({+ policy: "programLogos",+ contentType: "image/avif",+ contentLength: maxBytes,+ }),+ ).toEqual(UPLOAD_POLICIES.programLogos);+ });++ // Stored XSS on dubassets.com: unsigned Content-Type let clients PUT text/html.+ describe("Content-Type pinning (XSS regression)", () => {+ const publicPolicies = [+ "integrationScreenshots",+ "programLogos",+ "programApplicationImages",+ "programCampaignImages",+ "programLanderImages",+ "programResourceLogos",+ "programResourceFiles",+ "bountySubmissionImages",+ ] as const satisfies ReadonlyArray<keyof typeof UPLOAD_POLICIES>;++ const xssContentTypes = [+ "text/html",+ "text/html;charset=utf-8",+ "application/xhtml+xml",+ "image/svg+xml", // only some policies allow SVG; still XSS-capable when allowed+ ] as const;++ it("never allowlists text/html (or HTML charset variants) on any policy", () => {+ for (const [name, policy] of Object.entries(UPLOAD_POLICIES)) {+ expect(+ policy.contentTypes,+ `${name} must not allow text/html`,+ ).not.toContain("text/html");+ expect(+ policy.contentTypes.some((type) =>+ type.toLowerCase().startsWith("text/html"),+ ),+ `${name} must not allow text/html*`,+ ).toBe(false);+ }+ });++ it.each(publicPolicies)(+ "rejects text/html for public policy %s",+ (policy) => {+ expect(() =>+ validateSignedUpload({+ policy,+ contentType: "text/html",+ contentLength: 128,+ }),+ ).toThrow(+ expect.objectContaining({+ code: "unprocessable_entity",+ message: expect.stringContaining("Invalid content type"),+ } satisfies Partial<DubApiError>),+ );+ },+ );++ it("rejects text/html for private message attachment policies", () => {+ for (const policy of [+ "programMessageAttachments",+ "partnerMessageAttachments",+ ] as const) {+ expect(() =>+ validateSignedUpload({+ policy,+ contentType: "text/html",+ contentLength: 128,+ }),+ ).toThrow(+ expect.objectContaining({+ code: "unprocessable_entity",+ message: expect.stringContaining("Invalid content type"),+ } satisfies Partial<DubApiError>),+ );+ }+ });++ it("rejects HTML/scriptable types that are outside each public policy allowlist", () => {+ for (const policy of publicPolicies) {+ const allowed = new Set<string>(UPLOAD_POLICIES[policy].contentTypes);++ for (const contentType of xssContentTypes) {+ if (allowed.has(contentType)) {+ continue;+ }++ expect(() =>+ validateSignedUpload({+ policy,+ contentType,+ contentLength: 128,+ }),+ ).toThrow(+ expect.objectContaining({+ code: "unprocessable_entity",+ } satisfies Partial<DubApiError>),+ );+ }+ }+ });+ });+});diff --git a/apps/web/ui/messages/message-attachments.tsx b/apps/web/ui/messages/message-attachments.tsxindex e966467aa2..c7785d5067 100644--- a/apps/web/ui/messages/message-attachments.tsx+++ b/apps/web/ui/messages/message-attachments.tsx@@ -1,10 +1,10 @@"use client";import {- getAttachmentTypeLabel,isPreviewableImageType,sortMessageAttachments,} from "@/lib/messages/utils";+import { getMimeTypeLabel } from "@/lib/storage/upload-policies";import { MessageAttachment } from "@/lib/types";import { formatFileSize } from "@dub/utils";import { cn } from "@dub/utils/src";@@ -148,7 +148,7 @@ function FileTypeBadge({ type }: { type: string }) {)}><File className="size-3 shrink-0" />- <span>{getAttachmentTypeLabel(type)}</span>+ <span>{getMimeTypeLabel(type)}</span></div>);}diff --git a/apps/web/ui/oauth-apps/add-edit-app-form.tsx b/apps/web/ui/oauth-apps/add-edit-app-form.tsxindex 2581a26067..07c56c9a9e 100644--- a/apps/web/ui/oauth-apps/add-edit-app-form.tsx+++ b/apps/web/ui/oauth-apps/add-edit-app-form.tsx@@ -1,6 +1,7 @@"use client";import { clientAccessCheck } from "@/lib/client-access-check";+import { UPLOAD_POLICIES } from "@/lib/storage/upload-policies";import useWorkspace from "@/lib/swr/use-workspace";import {NewOAuthApp,@@ -19,7 +20,7 @@ import {Switch,useEnterSubmit,} from "@dub/ui";-import { cn, nanoid } from "@dub/utils";+import { cn, nanoid, toErrorMessage } from "@dub/utils";import slugify from "@sindresorhus/slugify";import { Paperclip, Trash2 } from "lucide-react";import { Reorder } from "motion/react";@@ -29,6 +30,9 @@ import TextareaAutosize from "react-textarea-autosize";import { toast } from "sonner";import { mutate } from "swr";+const { contentTypes, maxBytes } = UPLOAD_POLICIES.integrationScreenshots;+const maxFileSizeMB = maxBytes / (1024 * 1024);+const defaultValues: NewOAuthApp = {name: "",slug: "",@@ -166,43 +170,64 @@ export default function AddOAuthAppForm({const handleUpload = async (file: File) => {setScreenshots((prev) => [...prev, { file, uploading: true }]);- const response = await fetch(`/api/workspaces/${workspaceId}/upload-url`, {- method: "POST",- body: JSON.stringify({- folder: "integration-screenshots",- }),- });-- if (!response.ok) {- toast.error("Failed to get signed URL for screenshot upload.");- return;- }+ const removePendingScreenshot = () => {+ setScreenshots((prev) =>+ prev.filter((screenshot) => screenshot.file !== file),+ );+ };++ try {+ const response = await fetch(+ `/api/workspaces/${workspaceId}/upload-url`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ folder: "integrationScreenshots",+ contentType: file.type,+ contentLength: file.size,+ }),+ },+ );- const { signedUrl, key } = await response.json();+ if (!response.ok) {+ const { error } = await response.json();+ toast.error(toErrorMessage(error));+ removePendingScreenshot();+ return;+ }- const uploadResponse = await fetch(signedUrl, {- method: "PUT",- body: file,- headers: {- "Content-Type": file.type,- "Content-Length": file.size.toString(),- },- });+ const { key, signedUrl } = await response.json();++ const uploadResponse = await fetch(signedUrl, {+ method: "PUT",+ body: file,+ headers: {+ "Content-Type": file.type,+ "Content-Length": file.size.toString(),+ },+ });++ if (!uploadResponse.ok) {+ toast.error("Failed to upload screenshot.");+ removePendingScreenshot();+ return;+ }- if (!uploadResponse.ok) {- const result = await uploadResponse.json();- toast.error(result.error.message || "Failed to upload screenshot.");- return;+ toast.success(`${file.name} uploaded!`);+ setScreenshots((prev) =>+ prev.map((screenshot) =>+ screenshot.file === file+ ? { ...screenshot, uploading: false, key }+ : screenshot,+ ),+ );+ } catch (e) {+ toast.error(toErrorMessage(e));+ removePendingScreenshot();}-- toast.success(`${file.name} uploaded!`);- setScreenshots((prev) =>- prev.map((screenshot) =>- screenshot.file === file- ? { ...screenshot, uploading: false, key }- : screenshot,- ),- );};const {@@ -233,7 +258,7 @@ export default function AddOAuthAppForm({><div><FileUpload- accept="images"+ acceptedFileTypes={contentTypes}className="h-24 w-24 rounded-full border border-neutral-300"iconClassName="w-5 h-5"variant="plain"@@ -244,7 +269,7 @@ export default function AddOAuthAppForm({}onChange={({ src }) => setData({ ...data, logo: src })}content={null}- maxFileSizeMB={2}+ maxFileSizeMB={maxFileSizeMB}disabled={!canManageApp}/></div>@@ -410,14 +435,14 @@ export default function AddOAuthAppForm({</Reorder.Group><FileUpload- accept="images"+ acceptedFileTypes={contentTypes}className="mt-2 aspect-[5/1] w-full rounded-md border border-dashed border-neutral-300"iconClassName="w-5 h-5"variant="plain"onChange={async ({ file }) => await handleUpload(file)}content="Drag and drop or click to upload screenshots"disabled={!canManageApp || screenshots.length >= 4}- maxFileSizeMB={2}+ maxFileSizeMB={maxFileSizeMB}/></div>diff --git a/apps/web/ui/oauth-apps/add-edit-integration-form.tsx b/apps/web/ui/oauth-apps/add-edit-integration-form.tsxindex 8c912d1219..4004fd737e 100644--- a/apps/web/ui/oauth-apps/add-edit-integration-form.tsx+++ b/apps/web/ui/oauth-apps/add-edit-integration-form.tsx@@ -3,6 +3,7 @@import { addEditIntegration } from "@/lib/actions/add-edit-integration";import { normalizeWorkspaceId } from "@/lib/api/workspaces/workspace-id";import { clientAccessCheck } from "@/lib/client-access-check";+import { UPLOAD_POLICIES } from "@/lib/storage/upload-policies";import useWorkspace from "@/lib/swr/use-workspace";import { NewOrExistingIntegration } from "@/lib/types";import {@@ -15,7 +16,7 @@ import {RichTextToolbar,useEnterSubmit,} from "@dub/ui";-import { cn } from "@dub/utils";+import { cn, toErrorMessage } from "@dub/utils";import slugify from "@sindresorhus/slugify";import { Paperclip, Trash2 } from "lucide-react";import { Reorder } from "motion/react";@@ -24,6 +25,9 @@ import { useEffect, useRef, useState } from "react";import TextareaAutosize from "react-textarea-autosize";import { toast } from "sonner";+const { contentTypes, maxBytes } = UPLOAD_POLICIES.integrationScreenshots;+const maxFileSizeMB = maxBytes / (1024 * 1024);+export default function AddEditIntegrationForm({integration,}: {@@ -65,43 +69,64 @@ export default function AddEditIntegrationForm({const handleUpload = async (file: File) => {setScreenshots((prev) => [...prev, { file, uploading: true }]);- const response = await fetch(`/api/workspaces/${workspaceId}/upload-url`, {- method: "POST",- body: JSON.stringify({- folder: "integration-screenshots",- }),- });+ const removePendingScreenshot = () => {+ setScreenshots((prev) =>+ prev.filter((screenshot) => screenshot.file !== file),+ );+ };- if (!response.ok) {- toast.error("Failed to get signed URL for screenshot upload.");- return;- }+ try {+ const response = await fetch(+ `/api/workspaces/${workspaceId}/upload-url`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ folder: "integrationScreenshots",+ contentType: file.type,+ contentLength: file.size,+ }),+ },+ );- const { signedUrl, key } = await response.json();+ if (!response.ok) {+ const { error } = await response.json();+ toast.error(toErrorMessage(error));+ removePendingScreenshot();+ return;+ }- const uploadResponse = await fetch(signedUrl, {- method: "PUT",- body: file,- headers: {- "Content-Type": file.type,- "Content-Length": file.size.toString(),- },- });+ const { key, signedUrl } = await response.json();- if (!uploadResponse.ok) {- const result = await uploadResponse.json();- toast.error(result.error.message || "Failed to upload screenshot.");- return;- }+ const uploadResponse = await fetch(signedUrl, {+ method: "PUT",+ body: file,+ headers: {+ "Content-Type": file.type,+ "Content-Length": file.size.toString(),+ },+ });++ if (!uploadResponse.ok) {+ toast.error("Failed to upload screenshot.");+ removePendingScreenshot();+ return;+ }- toast.success(`${file.name} uploaded!`);- setScreenshots((prev) =>- prev.map((screenshot) =>- screenshot.file === file- ? { ...screenshot, uploading: false, key }- : screenshot,- ),- );+ toast.success(`${file.name} uploaded!`);+ setScreenshots((prev) =>+ prev.map((screenshot) =>+ screenshot.file === file+ ? { ...screenshot, uploading: false, key }+ : screenshot,+ ),+ );+ } catch (e) {+ toast.error(toErrorMessage(e));+ removePendingScreenshot();+ }};const { name, slug, description, readme, developer, website, logo } = data;@@ -139,7 +164,7 @@ export default function AddEditIntegrationForm({><div><FileUpload- accept="images"+ acceptedFileTypes={contentTypes}className="h-24 w-24 rounded-full border border-neutral-300"iconClassName="w-5 h-5"variant="plain"@@ -150,7 +175,7 @@ export default function AddEditIntegrationForm({}onChange={({ src }) => setData({ ...data, logo: src })}content={null}- maxFileSizeMB={2}+ maxFileSizeMB={maxFileSizeMB}disabled={!canManageApp}/></div>@@ -258,7 +283,7 @@ export default function AddEditIntegrationForm({><divclassName={cn(- "border-border-subtle overflow-hidden rounded-md border border-neutral-300 shadow-sm focus-within:border-neutral-500 focus-within:ring-1 focus-within:ring-neutral-500",+ "border-border-subtle overflow-hidden rounded-md border shadow-sm focus-within:border-neutral-500 focus-within:ring-1 focus-within:ring-neutral-500",!canManageApp && "cursor-not-allowed bg-neutral-50",)}>@@ -316,14 +341,14 @@ export default function AddEditIntegrationForm({</Reorder.Group><FileUpload- accept="images"+ acceptedFileTypes={contentTypes}className="mt-2 aspect-[5/1] w-full rounded-md border border-dashed border-neutral-300"iconClassName="w-5 h-5"variant="plain"onChange={async ({ file }) => await handleUpload(file)}content="Drag and drop or click to upload screenshots"disabled={!canManageApp || screenshots.length >= 4}- maxFileSizeMB={2}+ maxFileSizeMB={maxFileSizeMB}/></div>diff --git a/apps/web/ui/partners/bounties/claim-bounty-sheet.tsx b/apps/web/ui/partners/bounties/claim-bounty-sheet.tsxindex 73a86d2b65..04971051bd 100644--- a/apps/web/ui/partners/bounties/claim-bounty-sheet.tsx+++ b/apps/web/ui/partners/bounties/claim-bounty-sheet.tsx@@ -1,5 +1,6 @@"use client";+import { parseActionError } from "@/lib/actions/parse-action-errors";import { createBountySubmissionAction } from "@/lib/actions/partners/create-bounty-submission";import { uploadBountySubmissionFileAction } from "@/lib/actions/partners/upload-bounty-submission-file";import {@@ -9,6 +10,7 @@ import {} from "@/lib/bounty/constants";import { getPeriodLabel } from "@/lib/bounty/periods";import { resolveBountyDetails } from "@/lib/bounty/utils";+import { UPLOAD_POLICIES } from "@/lib/storage/upload-policies";import { mutatePrefix } from "@/lib/swr/mutate";import useProgramEnrollment from "@/lib/swr/use-program-enrollment";import { PartnerBountyProps } from "@/lib/types";@@ -22,7 +24,7 @@ import {Sheet,Trash,} from "@dub/ui";-import { cn } from "@dub/utils";+import { cn, toErrorMessage } from "@dub/utils";import { useAction } from "next-safe-action/hooks";import { Dispatch, SetStateAction, useEffect, useRef, useState } from "react";import { FormProvider, useForm } from "react-hook-form";@@ -101,7 +103,9 @@ function ImagesField({});if (!result?.data) {- toast.error("Failed to get signed upload URL.");+ toast.error(+ parseActionError(result ?? {}, "Failed to get signed upload URL."),+ );setFiles((prev) => {const updated = prev.filter((f) => f.id !== newFile.id);onUploadingChange(updated.some((f) => f.uploading));@@ -152,10 +156,8 @@ function ImagesField({syncToForm(updated);return updated;});- } catch {- toast.error(- "An unexpected error occurred while uploading. Please try again.",- );+ } catch (e) {+ toast.error(toErrorMessage(e));setFiles((prev) => {const updated = prev.filter((f) => f.id !== newFile.id);onUploadingChange(updated.some((f) => f.uploading));@@ -213,19 +215,21 @@ function ImagesField({))}<FileUpload- accept="images"+ acceptedFileTypes={+ UPLOAD_POLICIES.bountySubmissionImages.contentTypes+ }className={cn("border-border-subtle h-full w-auto rounded-md border",files.length > 0 ? "aspect-square" : "aspect-[unset] w-full",)}iconClassName="size-5 shrink-0"variant="plain"- content={- files.length > 0 ? null : "SVG, JPG, PNG or WEBP\nMax size 5MB"- }+ content={files.length > 0 ? null : "JPG, PNG or WEBP\nMax size 5MB"}onChange={async ({ file }) => await handleUpload(file)}disabled={files.length >= maxFiles}- maxFileSizeMB={5}+ maxFileSizeMB={+ UPLOAD_POLICIES.bountySubmissionImages.maxBytes / (1024 * 1024)+ }/></div></div>diff --git a/apps/web/ui/partners/groups/design/application-form/fields/image-upload-field.tsx b/apps/web/ui/partners/groups/design/application-form/fields/image-upload-field.tsxindex bf336f783e..23cceee7c3 100644--- a/apps/web/ui/partners/groups/design/application-form/fields/image-upload-field.tsx+++ b/apps/web/ui/partners/groups/design/application-form/fields/image-upload-field.tsx@@ -47,7 +47,11 @@ function ImageUploadFieldContent({controllerField: { value: any; onChange: (value: any) => void };maxImages: number;error: boolean;- uploadFile: (params: { programSlug: string }) => Promise<any>;+ uploadFile: (params: {+ programSlug: string;+ contentType: string;+ contentLength: number;+ }) => Promise<any>;onStatusChange?: (loading: boolean) => void;}) {const currentValue = controllerField.value || [];@@ -173,10 +177,17 @@ function ImageUploadFieldContent({try {const result = await uploadFile({programSlug,+ contentType: file.type,+ contentLength: file.size,});if (!result?.data) {- toast.error("Failed to upload image. Please try again.");+ toast.error(+ parseActionError(+ result ?? {},+ "Failed to upload image. Please try again.",+ ),+ );setFiles((prev) => prev.filter((f) => f.id !== newFile.id));return;}diff --git a/apps/web/ui/partners/groups/design/lander/modals/image-block-modal.tsx b/apps/web/ui/partners/groups/design/lander/modals/image-block-modal.tsxindex b0bdd19153..5d16fb0e98 100644--- a/apps/web/ui/partners/groups/design/lander/modals/image-block-modal.tsx+++ b/apps/web/ui/partners/groups/design/lander/modals/image-block-modal.tsx@@ -1,8 +1,9 @@+import { parseActionError } from "@/lib/actions/parse-action-errors";import { uploadLanderImageAction } from "@/lib/actions/partners/upload-lander-image";import useWorkspace from "@/lib/swr/use-workspace";import { programLanderImageBlockSchema } from "@/lib/zod/schemas/program-lander";import { Button, FileUpload, Modal } from "@dub/ui";-import { cn } from "@dub/utils";+import { cn, toErrorMessage } from "@dub/utils";import { useAction } from "next-safe-action/hooks";import { Dispatch, SetStateAction, useId, useState } from "react";import { Controller, useForm } from "react-hook-form";@@ -56,9 +57,15 @@ function ImageBlockModalInner({try {const result = await executeAsync({workspaceId: workspaceId!,+ contentType: file.type,+ contentLength: file.size,});- if (!result?.data) throw new Error("Failed to get signed upload URL");+ if (!result?.data) {+ throw new Error(+ parseActionError(result ?? {}, "Failed to get signed upload URL"),+ );+ }const { signedUrl, destinationUrl } = result.data;@@ -75,7 +82,7 @@ function ImageBlockModalInner({setValue("url", destinationUrl, { shouldDirty: true });} catch (e) {- toast.error("Failed to upload image");+ toast.error(toErrorMessage(e));console.error("Failed to upload image", e);} finally {setIsUploading(false);@@ -141,7 +148,7 @@ function ImageBlockModalInner({readFileloading={isUploading}onChange={({ file }) => handleUpload(file)}- content="SVG, JPG, PNG, or WEBP, max size of 5MB"+ content="SVG, JPG, PNG, WEBP, or AVIF, max size of 5MB"maxFileSizeMB={5}/>)}diff --git a/apps/web/ui/shared/message-input.tsx b/apps/web/ui/shared/message-input.tsxindex 630a7cbada..4a6ec4e09f 100644--- a/apps/web/ui/shared/message-input.tsx+++ b/apps/web/ui/shared/message-input.tsx@@ -3,11 +3,9 @@ import {MAX_ATTACHMENTS_PER_MESSAGE,MAX_MESSAGE_LENGTH,} from "@/lib/messages/constants";-import { messageAttachmentInputSchema } from "@/lib/messages/schemas";-import {- getAttachmentTypeLabel,- isPreviewableImageType,-} from "@/lib/messages/utils";+import { type MessageAttachmentInput } from "@/lib/messages/schemas";+import { isPreviewableImageType } from "@/lib/messages/utils";+import { getMimeTypeLabel } from "@/lib/storage/upload-policies";import useWorkspace from "@/lib/swr/use-workspace";import {ArrowTurnLeft,@@ -33,14 +31,10 @@ import {type RefObject,} from "react";import { toast } from "sonner";-import * as z from "zod/v4";import { ATTACHMENT_MIME_TYPE_COLOR } from "../messages/message-attachments";import { EmojiPicker } from "../shared/emoji-picker";-export type PendingAttachment = Omit<- z.infer<typeof messageAttachmentInputSchema>,- "storageKey"-> & {+export type PendingAttachment = Omit<MessageAttachmentInput, "storageKey"> & {id: string;file: File;storageKey?: string;@@ -63,7 +57,7 @@ export function MessageInput({}: {onSendMessage: (message: string,- attachments: z.infer<typeof messageAttachmentInputSchema>[],+ attachments: MessageAttachmentInput[],) => void | false;defaultValue?: string;onCancel?: () => void;@@ -390,7 +384,7 @@ function getUnsupportedFileTypeMessage(allowedFileTypes: readonly string[]) {}const allowedLabels = formatList(- allowedFileTypes.map((type) => getAttachmentTypeLabel(type)),+ allowedFileTypes.map((type) => getMimeTypeLabel(type)),);return `File type not supported. Upload a ${allowedLabels}.`;@@ -465,7 +459,7 @@ function AttachmentChip({)}><File className="size-3 shrink-0" />- <span>{getAttachmentTypeLabel(attachment.type)}</span>+ <span>{getMimeTypeLabel(attachment.type)}</span></div><div className="flex min-w-0 max-w-[120px] flex-col">diff --git a/packages/ui/src/file-upload.tsx b/packages/ui/src/file-upload.tsxindex 0497fe7b7d..48bea7e358 100644--- a/packages/ui/src/file-upload.tsx+++ b/packages/ui/src/file-upload.tsx@@ -28,6 +28,7 @@ const imageExtensionMimeTypes: Record<string, string> = {jpeg: "image/jpeg",webp: "image/webp",avif: "image/avif",+ svg: "image/svg+xml",};const acceptFileTypes: Record<@@ -107,7 +108,11 @@ type FileUploadReadFileProps =export type FileUploadProps = FileUploadReadFileProps & {id?: string;- accept: AcceptedFileFormats;+ accept?: AcceptedFileFormats;+ /**+ * When set, overrides the MIME types from the `accept` preset.+ */+ acceptedFileTypes?: readonly string[];className?: string;iconClassName?: string;previewClassName?: string;@@ -174,6 +179,7 @@ export function FileUpload({icon: Icon = CloudUpload,customPreview,accept = "any",+ acceptedFileTypes,imageSrc,loading = false,clickToUpload = true,@@ -193,6 +199,9 @@ export function FileUpload({setImageError(false);}, [imageSrc]);+ const resolvedAcceptedTypes =+ acceptedFileTypes ?? acceptFileTypes[accept].types;+const onFileChange = async (e: React.ChangeEvent<HTMLInputElement> | DragEvent,) => {@@ -209,16 +218,18 @@ export function FileUpload({return;}- const acceptedTypes = acceptFileTypes[accept].types;const extension = file.name.split(".").pop()?.toLowerCase();const mimeType =- file.type ||- (extension ? imageExtensionMimeTypes[extension] : "") ||- "";+ file.type || (extension ? imageExtensionMimeTypes[extension] : "") || "";- if (acceptedTypes.length && !acceptedTypes.includes(mimeType)) {+ if (+ resolvedAcceptedTypes.length &&+ !resolvedAcceptedTypes.includes(mimeType)+ ) {toast.error(- acceptFileTypes[accept].errorMessage ?? "File type not supported",+ acceptedFileTypes+ ? "File type not supported"+ : acceptFileTypes[accept].errorMessage ?? "File type not supported",);return;}@@ -356,7 +367,7 @@ export function FileUpload({id={id}key={fileName} // Gets us a fresh input every time a file is uploadedtype="file"- accept={acceptFileTypes[accept].types.join(",")}+ accept={resolvedAcceptedTypes.join(",")}onChange={onFileChange}disabled={disabled}data-testid={dataTestId}diff --git a/packages/ui/src/rich-text-area/rich-text-provider.tsx b/packages/ui/src/rich-text-area/rich-text-provider.tsxindex fd8daa4402..d1b9f51568 100644--- a/packages/ui/src/rich-text-area/rich-text-provider.tsx+++ b/packages/ui/src/rich-text-area/rich-text-provider.tsx@@ -67,6 +67,7 @@ type RichTextProviderProps = PropsWithChildren<{style?: keyof typeof PROSE_STYLES;onChange?: (editor: Editor) => void;uploadImage?: (file: File) => Promise<string | null>;+ imageAccept?: string;variables?: string[];variableInfo?: Record<string, RichTextVariableInfo>;editable?: boolean;@@ -86,7 +87,7 @@ export type RichTextLinkModalState = {export const RichTextContext = createContext<| (Pick<RichTextProviderProps,- "features" | "markdown" | "variables" | "editable"+ "features" | "markdown" | "variables" | "editable" | "imageAccept"> & {editor: Editor | null;isUploading: boolean;@@ -116,6 +117,7 @@ export const RichTextProvider = forwardRef<style = "default",placeholder = "Start typing...",uploadImage,+ imageAccept,editable,autoFocus,variables,@@ -384,6 +386,7 @@ export const RichTextProvider = forwardRef<markdown,editable,variables,+ imageAccept,editor,isUploading,handleImageUpload,diff --git a/packages/ui/src/rich-text-area/rich-text-toolbar.tsx b/packages/ui/src/rich-text-area/rich-text-toolbar.tsxindex a19a7ea8fc..5d9b7d3d34 100644--- a/packages/ui/src/rich-text-area/rich-text-toolbar.tsx+++ b/packages/ui/src/rich-text-area/rich-text-toolbar.tsx@@ -29,7 +29,7 @@ export function RichTextToolbar({toolsEnd?: ReactNode;className?: string;}) {- const { editor, features, handleImageUpload, isUploading } =+ const { editor, features, handleImageUpload, isUploading, imageAccept } =useRichTextContext();const editorState = useEditorState({@@ -171,6 +171,7 @@ export function RichTextToolbar({<inputref={inputImageRef}type="file"+ accept={imageAccept}className="hidden"onChange={(e) => {const file = e.target.files?.[0];diff --git a/packages/utils/src/functions/index.ts b/packages/utils/src/functions/index.tsindex ac84a30363..24f815dc7d 100644--- a/packages/utils/src/functions/index.ts+++ b/packages/utils/src/functions/index.ts@@ -42,6 +42,7 @@ export * from "./stable-sort";export * from "./text-fetcher";export * from "./time-ago";export * from "./to-cents-number";+export * from "./to-error-message";export * from "./trim";export * from "./truncate";export * from "./unique";diff --git a/packages/utils/src/functions/to-error-message.ts b/packages/utils/src/functions/to-error-message.tsnew file mode 100644index 0000000000..53326b6174--- /dev/null+++ b/packages/utils/src/functions/to-error-message.ts@@ -0,0 +1,22 @@+export function toErrorMessage(+ error: unknown,+ fallback = "Something went wrong.",+): string {+ if (error instanceof Error) {+ return error.message || fallback;+ }++ if (typeof error === "string" && error) {+ return error;+ }++ if (typeof error === "object" && error !== null && "message" in error) {+ const { message } = error;++ if (typeof message === "string" && message) {+ return message;+ }+ }++ return fallback;+}