Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
♻️ Asset storage abstraction: profiles, lifecycle, generic upload control (#2960)
Luke Vella8154f85c0233
diff --git a/apps/web/public/locales/en/app.json b/apps/web/public/locales/en/app.jsonindex 278bbb38c..b3fbb8a30 100644--- a/apps/web/public/locales/en/app.json+++ b/apps/web/public/locales/en/app.json@@ -68,6 +68,8 @@"applyToAllDates": "Apply to all dates","appName": "App name","areYouSure": "Are you sure?",+ "assetUploadError": "Failed to upload",+ "assetUploadErrorDescription": "There was an issue uploading your file. Please try again later.","attendeeCount": "{count, plural, =0 {No attendees} one {1 attendee} other {# attendees}}","attribution": "Attribution","attributionDescription": "Control the visibility of the attribution text",@@ -292,8 +294,6 @@"errors_notFoundTitle": "404 not found","errorTitle": "Something went wrong","errorTryAgain": "Try again",- "errorUploadPicture": "Failed to upload",- "errorUploadPictureDescription": "There was an issue uploading your picture. Please try again later.","event": "Event","eventHostDescription": "You are the creator of this poll","eventPageAbout": "About",@@ -322,7 +322,6 @@"feedback": "Feedback","feedbackDialogEnterFeedback": "Enter your feedback","fileTooLarge": "File too large",- "fileTooLargeDescription": "Please upload a file smaller than 2MB.","forgotPassword": "Forgot password?","forgotPasswordDescription": "Enter your email address and we'll send you a link to reset your password.","forgotPasswordFooter": "Remember your password? <a>Back to login</a>",@@ -350,15 +349,14 @@"homeActionsTitle": "Actions","ifNeedBe": "If need be","imageCropDialogTitle": "Crop image",- "imageUploadDescription": "Up to 2MB, JPG or PNG",- "imageUploadSvgDescription": "Up to 2MB, SVG, JPG or PNG",+ "imageUploadFileTooLargeDescription": "Please upload a file no larger than {size}.",+ "imageUploadHint": "Up to {size}, {formats}",+ "imageUploadInvalidFileTypeDescription": "Accepted formats: {formats}","inappropriateContent": "Inappropriate content","increaseSeats": "Increase seats","instanceSettingsDescription": "Configure your instance settings","invalidEmailAddress": "Please enter a valid email address","invalidFileType": "Invalid file type",- "invalidFileTypeDescription": "Please upload a JPG or PNG file.",- "invalidFileTypeSvgDescription": "Please upload an SVG, JPG or PNG file.","invalidSessionDescription": "Sign out and log in again to continue.","invalidSessionLabel": "Session","invalidSessionTitle": "Your session is no longer valid",diff --git a/apps/web/src/app/[locale]/(space)/settings/general/components/space-settings-form.tsx b/apps/web/src/app/[locale]/(space)/settings/general/components/space-settings-form.tsxindex 9c28d9c1e..922114c81 100644--- a/apps/web/src/app/[locale]/(space)/settings/general/components/space-settings-form.tsx+++ b/apps/web/src/app/[locale]/(space)/settings/general/components/space-settings-form.tsx@@ -19,8 +19,6 @@ import {ImageUploadControl,ImageUploadPreview,} from "@/components/image-upload";-import type { AllowedMimeType } from "@/components/image-upload/types";-import { rasterMimeTypes } from "@/components/image-upload/types";import { InputWithSaveButton } from "@/components/input-with-save-button";import {getSpaceImageUploadUrlAction,@@ -29,6 +27,7 @@ import {updateSpaceImageAction,} from "@/features/space/actions";import { SpaceIcon } from "@/features/space/components/space-icon";+import { spaceIconAssetProfile } from "@/features/space/constants";import type { SpaceDTO } from "@/features/space/types";import { Trans, useTranslation } from "@/i18n/client";import { useSafeAction } from "@/lib/safe-action/client";@@ -54,6 +53,7 @@ export function SpaceSettingsForm({const { t } = useTranslation();const updateSpace = useSafeAction(updateSpaceAction);+ const getImageUploadUrl = useSafeAction(getSpaceImageUploadUrlAction);const updateImage = useSafeAction(updateSpaceImageAction);const removeImage = useSafeAction(removeSpaceImageAction);@@ -64,31 +64,6 @@ export function SpaceSettingsForm({},});- const handleGetUploadUrl = async (input: {- fileType: AllowedMimeType;- fileSize: number;- }) => {- // The control only accepts raster types here (default accept list)- const result = await getSpaceImageUploadUrlAction({- fileType: rasterMimeTypes.parse(input.fileType),- fileSize: input.fileSize,- });-- if (!result?.data) {- throw new Error("Failed to get upload URL");- }-- return result.data;- };-- const handleImageUploadSuccess = async (imageKey: string) => {- await updateImage.executeAsync({ imageKey });- };-- const handleImageRemoveSuccess = async () => {- await removeImage.executeAsync();- };-return (<><Field orientation="responsive">@@ -108,9 +83,11 @@ export function SpaceSettingsForm({<SpaceIcon name={space.name} src={space.image} size="xl" /></ImageUploadPreview><ImageUploadControl- getUploadUrl={handleGetUploadUrl}- onUploadSuccess={handleImageUploadSuccess}- onRemoveSuccess={handleImageRemoveSuccess}+ profile={spaceIconAssetProfile}+ crop+ signUpload={(input) => getImageUploadUrl.executeAsync(input)}+ persistUpload={(imageKey) => updateImage.executeAsync({ imageKey })}+ onRemove={() => removeImage.executeAsync()}hasCurrentImage={!!space.image}/></ImageUpload>diff --git a/apps/web/src/app/[locale]/(space)/settings/profile/components/profile-picture.tsx b/apps/web/src/app/[locale]/(space)/settings/profile/components/profile-picture.tsxindex 6cf5af331..9130966f6 100644--- a/apps/web/src/app/[locale]/(space)/settings/profile/components/profile-picture.tsx+++ b/apps/web/src/app/[locale]/(space)/settings/profile/components/profile-picture.tsx@@ -5,13 +5,13 @@ import {ImageUploadControl,ImageUploadPreview,} from "@/components/image-upload";-import { rasterMimeTypes } from "@/components/image-upload/types";import { OptimizedAvatarImage } from "@/components/optimized-avatar-image";import {getAvatarUploadUrlAction,removeUserAvatarAction,updateUserAvatarAction,} from "@/features/user/actions";+import { avatarAssetProfile } from "@/features/user/constants";import { useFeatureFlag } from "@/lib/feature-flags/client";import { useSafeAction } from "@/lib/safe-action/client";@@ -26,33 +26,19 @@ function ProfilePictureUpload({const updateUserAvatar = useSafeAction(updateUserAvatarAction);const removeUserAvatar = useSafeAction(removeUserAvatarAction);- const handleUploadSuccess = async (imageKey: string) => {- await updateUserAvatar.executeAsync({ imageKey });- };-- const handleRemoveSuccess = async () => {- await removeUserAvatar.executeAsync();- };-return (<ImageUpload><ImageUploadPreview><OptimizedAvatarImage src={image} name={name} size="xl" /></ImageUploadPreview><ImageUploadControl- getUploadUrl={async (input) => {- // The control only accepts raster types here (default accept list)- const result = await getAvatarUploadUrl.executeAsync({- fileType: rasterMimeTypes.parse(input.fileType),- fileSize: input.fileSize,- });- if (!result?.data) {- throw new Error("Failed to get upload URL");- }- return result.data;- }}- onUploadSuccess={handleUploadSuccess}- onRemoveSuccess={handleRemoveSuccess}+ profile={avatarAssetProfile}+ crop+ signUpload={(input) => getAvatarUploadUrl.executeAsync(input)}+ persistUpload={(imageKey) =>+ updateUserAvatar.executeAsync({ imageKey })+ }+ onRemove={() => removeUserAvatar.executeAsync()}hasCurrentImage={!!image}/></ImageUpload>diff --git a/apps/web/src/app/[locale]/control-panel/branding/actions.ts b/apps/web/src/app/[locale]/control-panel/branding/actions.tsindex 17a9342ba..43c400b61 100644--- a/apps/web/src/app/[locale]/control-panel/branding/actions.ts+++ b/apps/web/src/app/[locale]/control-panel/branding/actions.ts@@ -1,10 +1,13 @@"use server";+import {+ brandingLogoEntityIds,+ brandingLogoProfiles,+} from "@/features/instance-settings/constants";import {updateInstanceLogo,updateInstanceSettings,} from "@/features/instance-settings/mutations";-import type { BrandingLogoType } from "@/features/instance-settings/schema";import {brandingLogoUploadSchema,brandingSettingsSchema,@@ -14,7 +17,10 @@ import {import { getWhiteLabelAddon } from "@/features/licensing/data";import { AppError } from "@/lib/errors/app-error";import { adminActionClient } from "@/lib/safe-action/server";-import { getImageUploadUrl } from "@/lib/storage/image-upload";+import {+ assertAssetKey,+ createAssetUploadUrl,+} from "@/lib/storage/asset-upload";async function requireWhiteLabelAddon() {const hasWhiteLabelAddon = await getWhiteLabelAddon();@@ -38,12 +44,6 @@ export const updateBrandingSettingsAction = adminActionClientawait updateInstanceSettings(parsedInput);});-const logoEntityIds: Record<BrandingLogoType, string> = {- logo: "logo",- logoDark: "logo-dark",- logoIcon: "logo-icon",-};-export const getBrandingLogoUploadUrlAction = adminActionClient.metadata({actionName: "get_branding_logo_upload_url",@@ -52,9 +52,9 @@ export const getBrandingLogoUploadUrlAction = adminActionClient.action(async ({ parsedInput }) => {await requireWhiteLabelAddon();- return await getImageUploadUrl({- keyPrefix: "branding",- entityId: logoEntityIds[parsedInput.logoType],+ return await createAssetUploadUrl({+ profile: brandingLogoProfiles[parsedInput.logoType],+ entityId: brandingLogoEntityIds[parsedInput.logoType],fileType: parsedInput.fileType,fileSize: parsedInput.fileSize,});@@ -68,12 +68,10 @@ export const updateBrandingLogoAction = adminActionClient.action(async ({ parsedInput }) => {await requireWhiteLabelAddon();- if (!parsedInput.imageKey.startsWith("branding/")) {- throw new AppError({- code: "FORBIDDEN",- message: "Invalid image key",- });- }+ assertAssetKey(parsedInput.imageKey, {+ profile: brandingLogoProfiles[parsedInput.logoType],+ entityId: brandingLogoEntityIds[parsedInput.logoType],+ });await updateInstanceLogo({logoType: parsedInput.logoType,diff --git a/apps/web/src/app/[locale]/control-panel/branding/components/logo-upload-field.tsx b/apps/web/src/app/[locale]/control-panel/branding/components/logo-upload-field.tsxindex c50b1ae97..acb6bb91a 100644--- a/apps/web/src/app/[locale]/control-panel/branding/components/logo-upload-field.tsx+++ b/apps/web/src/app/[locale]/control-panel/branding/components/logo-upload-field.tsx@@ -2,7 +2,7 @@import { cn } from "@rallly/ui";import { ImageUploadControl } from "@/components/image-upload";-import type { AllowedMimeType } from "@/components/image-upload/types";+import { brandingLogoProfiles } from "@/features/instance-settings/constants";import type { BrandingLogoType } from "@/features/instance-settings/schema";import { useSafeAction } from "@/lib/safe-action/client";import {@@ -32,13 +32,6 @@ const previewVariants: Record<},};-// The icon feeds emails, where SVG rendering is unreliable — raster only-const acceptedMimeTypes: Record<BrandingLogoType, AllowedMimeType[]> = {- logo: ["image/jpeg", "image/png", "image/svg+xml"],- logoDark: ["image/jpeg", "image/png", "image/svg+xml"],- logoIcon: ["image/jpeg", "image/png"],-};-export function LogoUploadField({logoType,previewUrl,@@ -52,25 +45,10 @@ export function LogoUploadField({hasCustomLogo: boolean;disabled?: boolean;}) {+ const getLogoUploadUrl = useSafeAction(getBrandingLogoUploadUrlAction);const updateLogo = useSafeAction(updateBrandingLogoAction);const removeLogo = useSafeAction(removeBrandingLogoAction);- const handleGetUploadUrl = async (input: {- fileType: AllowedMimeType;- fileSize: number;- }) => {- const result = await getBrandingLogoUploadUrlAction({- logoType,- ...input,- });-- if (!result?.data) {- throw new Error("Failed to get upload URL");- }-- return result.data;- };-return (<div className="w-full space-y-3">{/* Full-width preview of the 200x160 slot the logo renders in. The@@ -142,21 +120,15 @@ export function LogoUploadField({</div></div><ImageUploadControl- crop={false}- accept={acceptedMimeTypes[logoType]}+ profile={brandingLogoProfiles[logoType]}disabled={disabled}- getUploadUrl={handleGetUploadUrl}- onUploadSuccess={async (imageKey) => {- const result = await updateLogo.executeAsync({ logoType, imageKey });- // executeAsync resolves on server errors; throw so the control- // reports the failure instead of completing- if (result?.serverError || result?.validationErrors) {- throw new Error("Failed to save logo");- }- }}- onRemoveSuccess={async () => {- await removeLogo.executeAsync({ logoType });- }}+ signUpload={(input) =>+ getLogoUploadUrl.executeAsync({ logoType, ...input })+ }+ persistUpload={(imageKey) =>+ updateLogo.executeAsync({ logoType, imageKey })+ }+ onRemove={() => removeLogo.executeAsync({ logoType })}hasCurrentImage={hasCustomLogo}/></div>diff --git a/apps/web/src/app/api/storage/[...key]/route.ts b/apps/web/src/app/api/storage/[...key]/route.tsindex 6f8faf1c7..79e60e94d 100644--- a/apps/web/src/app/api/storage/[...key]/route.ts+++ b/apps/web/src/app/api/storage/[...key]/route.ts@@ -2,24 +2,15 @@ import { GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";import { createLogger } from "@rallly/logger";import type { NextRequest } from "next/server";import { NextResponse } from "next/server";-+import { assetProfiles } from "@/app/api/storage/asset-profiles";import { env } from "@/env";import { isSelfHosted } from "@/lib/constants";-import { verifyUploadToken } from "@/lib/storage/image-upload";+import { parseAssetKey } from "@/lib/storage/asset-profile";+import { verifyUploadToken } from "@/lib/storage/asset-upload";import { getS3Client } from "@/lib/storage/s3";const logger = createLogger("api/storage");-const MAX_UPLOAD_BYTES = 2 * 1024 * 1024;-// The signed upload key's extension is derived server-side from the-// validated file type, so it decides which content type a PUT may carry —-// without this, any signed URL (e.g. an avatar's) could store an SVG-const CONTENT_TYPE_BY_KEY_EXTENSION: Record<string, string> = {- jpg: "image/jpeg",- png: "image/png",- svg: "image/svg+xml",-};-async function getAvatar(key: string) {const s3Client = getS3Client();@@ -102,20 +93,28 @@ export async function PUT(return new NextResponse("Invalid token", { status: 401 });}+ // The signed key was produced from a profile, so the profile decides which+ // content type and size this PUT may carry — without this, any signed URL+ // (e.g. an avatar's) could store an SVG+ const parsedKey = parseAssetKey(key, assetProfiles);++ if (!parsedKey) {+ return new NextResponse("Not found", { status: 404 });+ }+const contentType = req.headers.get("content-type") ?? "";- const keyExtension = key.split(".").pop() ?? "";- const expectedContentType = CONTENT_TYPE_BY_KEY_EXTENSION[keyExtension];- if (!expectedContentType || contentType !== expectedContentType) {+ if (contentType !== parsedKey.mimeType) {return new NextResponse("Unsupported content type", { status: 415 });}+ const maxUploadBytes = parsedKey.profile.maxSize;const contentLength = Number(req.headers.get("content-length"));if (!Number.isFinite(contentLength) ||contentLength <= 0 ||- contentLength > MAX_UPLOAD_BYTES+ contentLength > maxUploadBytes) {return new NextResponse("Invalid content length", { status: 413 });}@@ -128,7 +127,7 @@ export async function PUT(const arrayBuffer = await req.arrayBuffer();- if (arrayBuffer.byteLength > MAX_UPLOAD_BYTES) {+ if (arrayBuffer.byteLength > maxUploadBytes) {return new NextResponse("Payload too large", { status: 413 });}diff --git a/apps/web/src/app/api/storage/asset-profiles.ts b/apps/web/src/app/api/storage/asset-profiles.tsnew file mode 100644index 000000000..1a724b69e--- /dev/null+++ b/apps/web/src/app/api/storage/asset-profiles.ts@@ -0,0 +1,17 @@+import {+ brandingLogoAssetProfile,+ brandingLogoIconAssetProfile,+} from "@/features/instance-settings/constants";+import { spaceIconAssetProfile } from "@/features/space/constants";+import { avatarAssetProfile } from "@/features/user/constants";+import type { AssetProfile } from "@/lib/storage/asset-profile";++// Profiles are feature-owned; the storage route needs a key-to-profile+// lookup across all of them, and lib cannot import features — so the+// aggregation lives here, at the app layer next to its only consumer.+export const assetProfiles: readonly AssetProfile[] = [+ avatarAssetProfile,+ spaceIconAssetProfile,+ brandingLogoAssetProfile,+ brandingLogoIconAssetProfile,+];diff --git a/apps/web/src/components/asset-upload/use-asset-upload.ts b/apps/web/src/components/asset-upload/use-asset-upload.tsnew file mode 100644index 000000000..e46241965--- /dev/null+++ b/apps/web/src/components/asset-upload/use-asset-upload.ts@@ -0,0 +1,96 @@+"use client";++import { toast } from "@rallly/ui/sonner";+import React from "react";+import { useTranslation } from "@/i18n/client";+import { uploadAsset } from "@/lib/storage/upload-client";++/**+ * A safe-action result, structurally. Actions resolve (rather than reject)+ * on server errors, so success has to be read off the result — forgetting+ * that check is the bug class this hook exists to remove.+ */+interface ActionResult<T> {+ data?: T;+ serverError?: unknown;+ validationErrors?: unknown;+}++/**+ * Server errors already surface a toast via useSafeAction's global handler;+ * this marker keeps the hook from toasting the same failure twice.+ */+class ActionFailedError extends Error {}++function assertActionOk(result: ActionResult<unknown> | undefined) {+ if (result?.serverError) {+ throw new ActionFailedError("Action failed");+ }+ if (!result || result.validationErrors) {+ throw new Error("Action failed");+ }+}++/**+ * The two-phase upload protocol, once: sign against the slot's profile,+ * PUT the bytes, persist the key. Any failed step aborts the pipeline and+ * reports the error — success is only signalled after the persist action+ * confirmed the key was stored.+ *+ * Files must already be validated against the profile (the upload control+ * does this before cropping).+ */+export function useAssetUpload<TAccept extends string>({+ signUpload,+ persistUpload,+}: {+ signUpload: (input: {+ fileType: TAccept;+ fileSize: number;+ }) => Promise<ActionResult<{ url: string; key: string }> | undefined>;+ persistUpload: (key: string) => Promise<ActionResult<unknown> | undefined>;+}) {+ const { t } = useTranslation();+ const [isUploading, startUploading] = React.useTransition();++ const upload = (file: File, options?: { onSuccess?: () => void }) => {+ startUploading(async () => {+ try {+ const signResult = await signUpload({+ fileType: file.type as TAccept,+ fileSize: file.size,+ });++ assertActionOk(signResult);++ const signedUpload = signResult?.data;++ if (!signedUpload) {+ throw new Error("Failed to get upload URL");+ }++ await uploadAsset({ url: signedUpload.url, file });++ assertActionOk(await persistUpload(signedUpload.key));++ options?.onSuccess?.();+ } catch (error) {+ if (!(error instanceof ActionFailedError)) {+ toast.error(+ t("assetUploadError", {+ defaultValue: "Failed to upload",+ }),+ {+ description: t("assetUploadErrorDescription", {+ defaultValue:+ "There was an issue uploading your file. Please try again later.",+ }),+ },+ );+ }+ }+ });+ };++ return { upload, isUploading };+}diff --git a/apps/web/src/components/image-upload/image-upload.tsx b/apps/web/src/components/image-upload/image-upload.tsxindex c04c7047a..7ab5068f3 100644--- a/apps/web/src/components/image-upload/image-upload.tsx+++ b/apps/web/src/components/image-upload/image-upload.tsx@@ -4,45 +4,83 @@ import { cn } from "@rallly/ui";import { Button } from "@rallly/ui/button";import { toast } from "@rallly/ui/sonner";import React from "react";+import { useAssetUpload } from "@/components/asset-upload/use-asset-upload";import { ImageCropDialog } from "@/components/image-upload/image-crop-dialog";-import type {- ImageUploadControlProps,- ImageUploadPreviewProps,- ImageUploadProps,-} from "@/components/image-upload/types";-import {- allowedMimeTypes,- defaultAcceptedMimeTypes,-} from "@/components/image-upload/types";import { Trans, useTranslation } from "@/i18n/client";import { useFeatureFlag } from "@/lib/feature-flags/client";-import {- createImagePreviewUrl,- validateImageFile,-} from "@/lib/image-processing";-import { uploadImage } from "@/lib/storage/upload-client";+import { createImagePreviewUrl } from "@/lib/image-processing";+import type { AssetProfile } from "@/lib/storage/asset-profile";+import { validateAssetFile } from "@/lib/storage/asset-profile";-export function ImageUpload({ className, children }: ImageUploadProps) {+export function ImageUpload({+ className,+ children,+}: {+ className?: string;+ children?: React.ReactNode;+}) {return (<div className={cn("flex items-center gap-x-4", className)}>{children}</div>);}-export function ImageUploadControl({- getUploadUrl,- onUploadSuccess,- onRemoveSuccess,+const fileTypeLabels: Record<string, string> = {+ "image/jpeg": "JPG",+ "image/png": "PNG",+ "image/svg+xml": "SVG",+};++function formatFileTypes(accept: readonly string[], language: string): string {+ const labels = accept.map(+ (mimeType) =>+ fileTypeLabels[mimeType] ??+ mimeType.split("/").pop()?.toUpperCase() ??+ mimeType,+ );+ return new Intl.ListFormat(language, { type: "disjunction" }).format(labels);+}++function formatFileSize(bytes: number): string {+ if (bytes >= 1024 * 1024) {+ return `${Math.round(bytes / (1024 * 1024))}MB`;+ }+ return `${Math.round(bytes / 1024)}KB`;+}++export function ImageUploadControl<TAccept extends string>({+ profile,+ signUpload,+ persistUpload,+ onRemove,hasCurrentImage = false,- crop = true,- accept = defaultAcceptedMimeTypes,+ crop = false,disabled = false,-}: ImageUploadControlProps) {- const acceptsSvg = accept.includes("image/svg+xml");+}: {+ /** The asset slot this control uploads into; drives validation and hints. */+ profile: AssetProfile & { accept: readonly [TAccept, ...TAccept[]] };+ /**+ * Run the selected file through the 1:1 crop dialog before uploading.+ * Only raster types can be cropped (the crop canvas cannot process SVG),+ * so this requires a raster-only profile.+ */+ crop?: boolean;+ signUpload: Parameters<typeof useAssetUpload<TAccept>>[0]["signUpload"];+ persistUpload: Parameters<typeof useAssetUpload<TAccept>>[0]["persistUpload"];+ onRemove: () => Promise<unknown>;+ hasCurrentImage?: boolean;+ disabled?: boolean;+}) {const isStorageEnabled = useFeatureFlag("storage");- const { t } = useTranslation();+ const { t, i18n } = useTranslation();const [isRemoving, startRemoving] = React.useTransition();- const [isUploading, startUploading] = React.useTransition();+ const { upload, isUploading } = useAssetUpload({+ signUpload,+ persistUpload,+ });++ const acceptedFormats = formatFileTypes(profile.accept, i18n.language);+ const maxFileSize = formatFileSize(profile.maxSize);// Cropping stateconst [showCropDialog, setShowCropDialog] = React.useState(false);@@ -61,8 +99,7 @@ export function ImageUploadControl({const file = event.target.files?.[0];if (!file) return;- // Validate the file- const validation = validateImageFile(file, accept);+ const validation = validateAssetFile(file, profile);if (!validation.success) {switch (validation.error) {case "invalidFileType":@@ -71,13 +108,10 @@ export function ImageUploadControl({defaultValue: "Invalid file type",}),{- description: acceptsSvg- ? t("invalidFileTypeSvgDescription", {- defaultValue: "Please upload an SVG, JPG or PNG file.",- })- : t("invalidFileTypeDescription", {- defaultValue: "Please upload a JPG or PNG file.",- }),+ description: t("imageUploadInvalidFileTypeDescription", {+ defaultValue: "Accepted formats: {formats}",+ formats: acceptedFormats,+ }),},);break;@@ -87,8 +121,9 @@ export function ImageUploadControl({defaultValue: "File too large",}),{- description: t("fileTooLargeDescription", {- defaultValue: "Please upload a file smaller than 2MB.",+ description: t("imageUploadFileTooLargeDescription", {+ defaultValue: "Please upload a file no larger than {size}.",+ size: maxFileSize,}),},);@@ -103,7 +138,7 @@ export function ImageUploadControl({}if (!crop) {- startUpload(file);+ upload(file);event.target.value = "";return;}@@ -119,44 +154,10 @@ export function ImageUploadControl({event.target.value = "";};- const startUpload = (file: File, onUploaded?: () => void) => {- const parsedFileType = allowedMimeTypes.parse(file.type);-- startUploading(async () => {- try {- const { url, fields } = await getUploadUrl({- fileType: parsedFileType,- fileSize: file.size,- });-- await uploadImage({- file,- url,- fileType: parsedFileType,- });-- await onUploadSuccess(fields.key);- onUploaded?.();- } catch {- toast.error(- t("errorUploadPicture", {- defaultValue: "Failed to upload",- }),- {- description: t("errorUploadPictureDescription", {- defaultValue:- "There was an issue uploading your picture. Please try again later.",- }),- },- );- }- });- };-const handleCropComplete = async (croppedFile: File) => {if (!originalFile) return;- startUpload(croppedFile, handleCloseCropDialog);+ upload(croppedFile, { onSuccess: handleCloseCropDialog });};const handleCloseCropDialog = () => {@@ -173,7 +174,7 @@ export function ImageUploadControl({const handleRemove = async () => {startRemoving(async () => {- await onRemoveSuccess();+ await onRemove();});};@@ -202,22 +203,16 @@ export function ImageUploadControl({) : null}</div><p className="text-muted-foreground text-xs">- {acceptsSvg ? (- <Trans- i18nKey="imageUploadSvgDescription"- defaults="Up to 2MB, SVG, JPG or PNG"- />- ) : (- <Trans- i18nKey="imageUploadDescription"- defaults="Up to 2MB, JPG or PNG"- />- )}+ <Trans+ i18nKey="imageUploadHint"+ defaults="Up to {size}, {formats}"+ values={{ size: maxFileSize, formats: acceptedFormats }}+ /></p><inputref={fileInputRef}type="file"- accept={accept.join(",")}+ accept={profile.accept.join(",")}onChange={handleFileChange}className="hidden"/>@@ -238,7 +233,10 @@ export function ImageUploadControl({export function ImageUploadPreview({className,children,-}: ImageUploadPreviewProps) {+}: {+ className?: string;+ children?: React.ReactNode;+}) {return (<div className={cn("relative overflow-hidden", className)}>{children}</div>);diff --git a/apps/web/src/components/image-upload/types.ts b/apps/web/src/components/image-upload/types.tsdeleted file mode 100644index 84bee6138..000000000--- a/apps/web/src/components/image-upload/types.ts+++ /dev/null@@ -1,48 +0,0 @@-import * as z from "zod";--export const allowedMimeTypes = z.enum([- "image/jpeg",- "image/png",- "image/svg+xml",-]);-export type AllowedMimeType = z.infer<typeof allowedMimeTypes>;--/** The subset the canvas-based crop pipeline can process. */-export const rasterMimeTypes = z.enum(["image/jpeg", "image/png"]);--export const defaultAcceptedMimeTypes: AllowedMimeType[] = [- "image/jpeg",- "image/png",-];--export interface ImageUploadControlProps {- getUploadUrl: (input: {- fileType: AllowedMimeType;- fileSize: number;- }) => Promise<{ url: string; fields: { key: string } }>;- onUploadSuccess: (imageKey: string) => Promise<void> | void;- onRemoveSuccess: () => Promise<void> | void;- hasCurrentImage?: boolean;- /**- * When false, the selected file is uploaded as-is instead of going through- * the 1:1 crop dialog. Use for images with a free aspect ratio (e.g. logos).- */- crop?: boolean;- /**- * Mime types this uploader takes. Defaults to JPEG/PNG; SVG may only be- * accepted together with crop={false} since the crop canvas can't process- * it.- */- accept?: AllowedMimeType[];- disabled?: boolean;-}--export interface ImageUploadPreviewProps {- className?: string;- children?: React.ReactNode;-}--export interface ImageUploadProps {- className?: string;- children?: React.ReactNode;-}diff --git a/apps/web/src/features/instance-settings/constants.ts b/apps/web/src/features/instance-settings/constants.tsindex 1397f1a11..d209f9c78 100644--- a/apps/web/src/features/instance-settings/constants.ts+++ b/apps/web/src/features/instance-settings/constants.ts@@ -1 +1,36 @@+import type { AssetProfile } from "@/lib/storage/asset-profile";+export const instanceSettingsTag = "instance-settings";++// The wordmark slots share one profile: same prefix, same policy. The icon+// gets its own because it feeds emails, where SVG rendering is unreliable+// across clients — raster only for that slot.+export const brandingLogoAssetProfile = {+ id: "branding-logo",+ keyPrefix: "branding",+ entityIds: ["logo", "logo-dark"],+ accept: ["image/jpeg", "image/png", "image/svg+xml"],+ maxSize: 2 * 1024 * 1024,+} as const satisfies AssetProfile;++export const brandingLogoIconAssetProfile = {+ id: "branding-logo-icon",+ keyPrefix: "branding",+ entityIds: ["logo-icon"],+ accept: ["image/jpeg", "image/png"],+ maxSize: 2 * 1024 * 1024,+} as const satisfies AssetProfile;++// Keyed by BrandingLogoType (schema.ts); declared structurally to keep this+// module free of imports from the rest of the feature.+export const brandingLogoEntityIds = {+ logo: "logo",+ logoDark: "logo-dark",+ logoIcon: "logo-icon",+} as const;++export const brandingLogoProfiles = {+ logo: brandingLogoAssetProfile,+ logoDark: brandingLogoAssetProfile,+ logoIcon: brandingLogoIconAssetProfile,+} as const satisfies Record<keyof typeof brandingLogoEntityIds, AssetProfile>;diff --git a/apps/web/src/features/instance-settings/mutations.ts b/apps/web/src/features/instance-settings/mutations.tsindex cb9b7a25b..b5b6d1418 100644--- a/apps/web/src/features/instance-settings/mutations.ts+++ b/apps/web/src/features/instance-settings/mutations.ts@@ -2,9 +2,7 @@ import "server-only";import { prisma } from "@rallly/database";import { updateTag } from "next/cache";-import { after } from "next/server";-import { deleteImageFromS3 } from "@/lib/storage/image-upload";-import { isStorageKey } from "@/lib/storage/resolve-storage-url";+import { replaceStoredAsset } from "@/lib/storage/asset-upload";import { instanceSettingsTag } from "./constants";import type { BrandingLogoType } from "./schema";@@ -44,22 +42,20 @@ export async function updateInstanceLogo({},});- const oldValue = instanceSettings?.[logoType];-- await prisma.instanceSettings.update({- where: {- id: 1,- },- data: {- [logoType]: imageKey,+ await replaceStoredAsset({+ currentKey: instanceSettings?.[logoType],+ nextKey: imageKey,+ persist: async () => {+ await prisma.instanceSettings.update({+ where: {+ id: 1,+ },+ data: {+ [logoType]: imageKey,+ },+ });++ updateTag(instanceSettingsTag);},});-- updateTag(instanceSettingsTag);-- // Only delete objects we own; a URL value points at externally hosted- // media, and a retry can resubmit the key that is now stored- if (oldValue && oldValue !== imageKey && isStorageKey(oldValue)) {- after(() => deleteImageFromS3(oldValue));- }}diff --git a/apps/web/src/features/instance-settings/schema.ts b/apps/web/src/features/instance-settings/schema.tsindex 43af35f07..f60de6cfd 100644--- a/apps/web/src/features/instance-settings/schema.ts+++ b/apps/web/src/features/instance-settings/schema.ts@@ -1,4 +1,5 @@import * as z from "zod";+import { brandingLogoAssetProfile } from "./constants";export const instanceSettingsSchema = z.object({disableUserRegistration: z.boolean(),@@ -19,23 +20,13 @@ export const brandingLogoTypeSchema = z.enum(["logo", "logoDark", "logoIcon"]);export type BrandingLogoType = z.infer<typeof brandingLogoTypeSchema>;-export const brandingLogoUploadSchema = z- .object({- logoType: brandingLogoTypeSchema,- fileType: z.enum(["image/jpeg", "image/png", "image/svg+xml"]),- fileSize: z- .number()- .int()- .positive()- .max(2 * 1024 * 1024),- })- // The icon renders in emails, where SVG support is unreliable across- // clients — raster only for that slot- .refine(- (value) =>- !(value.logoType === "logoIcon" && value.fileType === "image/svg+xml"),- { message: "The logo icon does not support SVG" },- );+// The accept list is the wordmark profile's (the widest slot); the icon's+// raster-only restriction is enforced at sign time against its own profile.+export const brandingLogoUploadSchema = z.object({+ logoType: brandingLogoTypeSchema,+ fileType: z.enum(brandingLogoAssetProfile.accept),+ fileSize: z.number().int().positive().max(brandingLogoAssetProfile.maxSize),+});export const updateBrandingLogoSchema = z.object({logoType: brandingLogoTypeSchema,diff --git a/apps/web/src/features/space/actions.ts b/apps/web/src/features/space/actions.tsindex 6d028a419..f2b8e047f 100644--- a/apps/web/src/features/space/actions.ts+++ b/apps/web/src/features/space/actions.ts@@ -4,13 +4,13 @@ import { subject } from "@casl/ability";import { prisma } from "@rallly/database";import { createMiddleware } from "next-safe-action";import * as z from "zod";+import { spaceIconAssetProfile } from "@/features/space/constants";import { getActiveSpaceForUser } from "@/features/space/data";import { defineAbilityForMember } from "@/features/space/member/ability";import { effectiveSpaceMemberWhere } from "@/features/space/member/utils";import {createSpace,deleteSpace,- removeSpaceImage,updateSpace,updateSpaceHideAttribution,updateSpaceImage,@@ -32,7 +32,10 @@ import {authActionClient,createRateLimitMiddleware,} from "@/lib/safe-action/server";-import { getImageUploadUrl } from "@/lib/storage/image-upload";+import {+ assertAssetKey,+ createAssetUploadUrl,+} from "@/lib/storage/asset-upload";// Resolves the actor's active space, verifies they can update it, and// injects it into ctx as `space`.@@ -306,8 +309,8 @@ export const getSpaceImageUploadUrlAction = authActionClient.use(spaceUpdateAbilityMiddleware).inputSchema(spaceImageUploadSchema).action(async ({ ctx, parsedInput }) => {- return await getImageUploadUrl({- keyPrefix: "spaces",+ return await createAssetUploadUrl({+ profile: spaceIconAssetProfile,entityId: ctx.space.id,fileType: parsedInput.fileType,fileSize: parsedInput.fileSize,@@ -321,12 +324,10 @@ export const updateSpaceImageAction = authActionClient.action(async ({ ctx, parsedInput }) => {const { space } = ctx;- if (!parsedInput.imageKey.startsWith(`spaces/${space.id}-`)) {- throw new AppError({- code: "FORBIDDEN",- message: "Invalid image key",- });- }+ assertAssetKey(parsedInput.imageKey, {+ profile: spaceIconAssetProfile,+ entityId: space.id,+ });await updateSpaceImage({spaceId: space.id,@@ -338,5 +339,5 @@ export const removeSpaceImageAction = authActionClient.metadata({ actionName: "remove_space_image" }).use(spaceUpdateAbilityMiddleware).action(async ({ ctx }) => {- await removeSpaceImage({ spaceId: ctx.space.id });+ await updateSpaceImage({ spaceId: ctx.space.id, imageKey: null });});diff --git a/apps/web/src/features/space/constants.ts b/apps/web/src/features/space/constants.tsnew file mode 100644index 000000000..893acf78c--- /dev/null+++ b/apps/web/src/features/space/constants.ts@@ -0,0 +1,8 @@+import type { AssetProfile } from "@/lib/storage/asset-profile";++export const spaceIconAssetProfile = {+ id: "space-icon",+ keyPrefix: "spaces",+ accept: ["image/jpeg", "image/png"],+ maxSize: 2 * 1024 * 1024,+} as const satisfies AssetProfile;diff --git a/apps/web/src/features/space/mutations.ts b/apps/web/src/features/space/mutations.tsindex 3f26b43b2..a47cb65d4 100644--- a/apps/web/src/features/space/mutations.ts+++ b/apps/web/src/features/space/mutations.ts@@ -5,7 +5,10 @@ import { prisma } from "@rallly/database";import { after } from "next/server";import { createSpaceDTO } from "@/features/space/data";import { isSelfHosted } from "@/lib/constants";-import { deleteImageFromS3 } from "@/lib/storage/image-upload";+import {+ deleteStoredAsset,+ replaceStoredAsset,+} from "@/lib/storage/asset-upload";export async function createSpace({name = "Personal",@@ -88,23 +91,23 @@ export async function updateSpaceImage({imageKey,}: {spaceId: string;- imageKey: string;+ imageKey: string | null;}) {const space = await prisma.space.findUnique({where: { id: spaceId },select: { image: true },});- const oldImageKey = space?.image;-- await prisma.space.update({- where: { id: spaceId },- data: { image: imageKey },+ await replaceStoredAsset({+ currentKey: space?.image,+ nextKey: imageKey,+ persist: async () => {+ await prisma.space.update({+ where: { id: spaceId },+ data: { image: imageKey },+ });+ },});-- if (oldImageKey) {- after(() => deleteImageFromS3(oldImageKey));- }}export async function deleteSpace({ spaceId }: { spaceId: string }) {@@ -115,24 +118,6 @@ export async function deleteSpace({ spaceId }: { spaceId: string }) {const imageKey = deletedSpace.image;if (imageKey) {- after(() => deleteImageFromS3(imageKey));- }-}--export async function removeSpaceImage({ spaceId }: { spaceId: string }) {- const space = await prisma.space.findUnique({- where: { id: spaceId },- select: { image: true },- });-- const oldImageKey = space?.image;-- await prisma.space.update({- where: { id: spaceId },- data: { image: null },- });-- if (oldImageKey) {- after(() => deleteImageFromS3(oldImageKey));+ after(() => deleteStoredAsset(imageKey));}}diff --git a/apps/web/src/features/space/schema.ts b/apps/web/src/features/space/schema.tsindex 8c71ff64f..9d26fcf74 100644--- a/apps/web/src/features/space/schema.ts+++ b/apps/web/src/features/space/schema.ts@@ -1,4 +1,5 @@import * as z from "zod";+import { spaceIconAssetProfile } from "@/features/space/constants";export const memberRoleSchema = z.enum(["member", "admin"]);export type MemberRole = z.infer<typeof memberRoleSchema>;@@ -28,8 +29,8 @@ export const updateSpaceHideAttributionSchema = z.object({});export const spaceImageUploadSchema = z.object({- fileType: z.enum(["image/jpeg", "image/png"]),- fileSize: z.number(),+ fileType: z.enum(spaceIconAssetProfile.accept),+ fileSize: z.number().int().positive().max(spaceIconAssetProfile.maxSize),});export const updateSpaceImageSchema = z.object({diff --git a/apps/web/src/features/user/actions.ts b/apps/web/src/features/user/actions.tsindex 0afdd0251..92ebc23c2 100644--- a/apps/web/src/features/user/actions.ts+++ b/apps/web/src/features/user/actions.ts@@ -4,6 +4,7 @@ import { prisma } from "@rallly/database";import { supportedLngs } from "@rallly/languages";import { headers } from "next/headers";import * as z from "zod";+import { avatarAssetProfile } from "@/features/user/constants";import { banUser, unbanUser, updateUserRole } from "@/features/user/mutations";import authLib from "@/lib/auth";import { timeFormatSchema, weekStartSchema } from "@/lib/datetime/schema";@@ -14,9 +15,10 @@ import {createRateLimitMiddleware,} from "@/lib/safe-action/server";import {- deleteImageFromS3,- getImageUploadUrl,-} from "@/lib/storage/image-upload";+ assertAssetKey,+ createAssetUploadUrl,+ replaceStoredAsset,+} from "@/lib/storage/asset-upload";import { timezoneSchema } from "@/lib/utils/timezone-schema";// Self-profile updates call Better-Auth's updateUser endpoint directly@@ -73,13 +75,13 @@ export const getAvatarUploadUrlAction = authActionClient.use(createRateLimitMiddleware(10, "1 h")).inputSchema(z.object({- fileType: z.enum(["image/jpeg", "image/png"]),- fileSize: z.number(),+ fileType: z.enum(avatarAssetProfile.accept),+ fileSize: z.number().int().positive().max(avatarAssetProfile.maxSize),}),).action(async ({ ctx, parsedInput }) => {- return await getImageUploadUrl({- keyPrefix: "avatars",+ return await createAssetUploadUrl({+ profile: avatarAssetProfile,entityId: ctx.user.id,fileType: parsedInput.fileType,fileSize: parsedInput.fileSize,@@ -96,44 +98,36 @@ export const updateUserAvatarAction = authActionClient.action(async ({ ctx, parsedInput }) => {const { imageKey } = parsedInput;- if (!imageKey.startsWith(`avatars/${ctx.user.id}-`)) {- throw new AppError({- code: "FORBIDDEN",- message: "Invalid image key",- });- }-- const oldImageKey = ctx.user.image;-- await authLib.api.updateUser({- body: { image: imageKey },- headers: await headers(),+ assertAssetKey(imageKey, {+ profile: avatarAssetProfile,+ entityId: ctx.user.id,});- // Only delete from storage if it's an internal avatar, not an external- // URL from an OAuth provider.- if (oldImageKey && !oldImageKey.startsWith("https://")) {- await deleteImageFromS3(oldImageKey);- }+ await replaceStoredAsset({+ currentKey: ctx.user.image,+ nextKey: imageKey,+ persist: async () => {+ await authLib.api.updateUser({+ body: { image: imageKey },+ headers: await headers(),+ });+ },+ });});export const removeUserAvatarAction = authActionClient.metadata({ actionName: "remove_user_avatar" }).action(async ({ ctx }) => {- const oldImageKey = ctx.user.image;-- await authLib.api.updateUser({- body: { image: null },- headers: await headers(),+ await replaceStoredAsset({+ currentKey: ctx.user.image,+ nextKey: null,+ persist: async () => {+ await authLib.api.updateUser({+ body: { image: null },+ headers: await headers(),+ });+ },});-- // Only delete from storage if it's an internal avatar, not an external- // URL from an OAuth provider.- const isInternalAvatar = oldImageKey && !oldImageKey.startsWith("https://");-- if (isInternalAvatar) {- await deleteImageFromS3(oldImageKey);- }});export const changeRoleAction = adminActionClientdiff --git a/apps/web/src/features/user/constants.ts b/apps/web/src/features/user/constants.tsnew file mode 100644index 000000000..fc9fd9cd4--- /dev/null+++ b/apps/web/src/features/user/constants.ts@@ -0,0 +1,8 @@+import type { AssetProfile } from "@/lib/storage/asset-profile";++export const avatarAssetProfile = {+ id: "avatar",+ keyPrefix: "avatars",+ accept: ["image/jpeg", "image/png"],+ maxSize: 2 * 1024 * 1024,+} as const satisfies AssetProfile;diff --git a/apps/web/src/features/user/mutations.ts b/apps/web/src/features/user/mutations.tsindex 7bcfe51e2..e4ed52dfd 100644--- a/apps/web/src/features/user/mutations.ts+++ b/apps/web/src/features/user/mutations.ts@@ -4,7 +4,7 @@ import type { Prisma, TimeFormat } from "@rallly/database";import { prisma } from "@rallly/database";import { authLib } from "@/lib/auth";import { SESSION_TTL_SECONDS } from "@/lib/auth-config";-import { deleteImageFromS3 } from "@/lib/storage/image-upload";+import { deleteStoredAsset } from "@/lib/storage/asset-upload";export async function createUser({name,@@ -134,8 +134,8 @@ export async function hardDeleteUser({ userId }: { userId: string }) {select: { image: true },});- if (user?.image && !user.image.startsWith("https://")) {- await deleteImageFromS3(user.image);+ if (user?.image) {+ await deleteStoredAsset(user.image);}// Cascades cover content the user owns. Everything on other people's pollsdiff --git a/apps/web/src/lib/image-processing.ts b/apps/web/src/lib/image-processing.tsindex fb408f362..215114887 100644--- a/apps/web/src/lib/image-processing.ts+++ b/apps/web/src/lib/image-processing.ts@@ -131,47 +131,3 @@ export function createImagePreviewUrl(file: File) {const cleanup = () => URL.revokeObjectURL(url);return { url, cleanup };}--export type ImageValidationErrorCode = "invalidFileType" | "fileTooLarge";--export interface ImageValidationSuccess {- success: true;-}--export interface ImageValidationError {- success: false;- error: ImageValidationErrorCode;- description: string;-}--export type ImageValidationResult =- | ImageValidationSuccess- | ImageValidationError;--/**- * Validates if a file is an allowed image type- * @param file - File to validate- * @returns Object with success boolean and optional error message- */-export function validateImageFile(- file: File,- allowedMimeTypes: string[] = ["image/jpeg", "image/png"],-): ImageValidationResult {- if (!allowedMimeTypes.includes(file.type)) {- return {- success: false,- error: "invalidFileType",- description: "Please upload a JPG or PNG file.",- };- }-- if (file.size > 2 * 1024 * 1024) {- return {- success: false,- error: "fileTooLarge",- description: "Please upload a file smaller than 2MB.",- };- }-- return { success: true };-}diff --git a/apps/web/src/lib/storage/asset-profile.test.ts b/apps/web/src/lib/storage/asset-profile.test.tsnew file mode 100644index 000000000..34ae8dcdd--- /dev/null+++ b/apps/web/src/lib/storage/asset-profile.test.ts@@ -0,0 +1,107 @@+import { describe, expect, it } from "vitest";+import type { AssetProfile } from "./asset-profile";+import { parseAssetKey, validateAssetFile } from "./asset-profile";++const avatarProfile = {+ id: "avatar",+ keyPrefix: "avatars",+ accept: ["image/jpeg", "image/png"],+ maxSize: 2 * 1024 * 1024,+} as const satisfies AssetProfile;++const wordmarkProfile = {+ id: "branding-logo",+ keyPrefix: "branding",+ entityIds: ["logo", "logo-dark"],+ accept: ["image/jpeg", "image/png", "image/svg+xml"],+ maxSize: 2 * 1024 * 1024,+} as const satisfies AssetProfile;++const iconProfile = {+ id: "branding-logo-icon",+ keyPrefix: "branding",+ entityIds: ["logo-icon"],+ accept: ["image/jpeg", "image/png"],+ maxSize: 2 * 1024 * 1024,+} as const satisfies AssetProfile;++const profiles = [avatarProfile, wordmarkProfile, iconProfile];++describe("parseAssetKey", () => {+ it("parses a key into its profile, entity id and mime type", () => {+ expect(+ parseAssetKey("avatars/user123-1723800000000.jpg", profiles),+ ).toEqual({+ profile: avatarProfile,+ entityId: "user123",+ mimeType: "image/jpeg",+ });+ });++ it("disambiguates profiles sharing a prefix by entity id", () => {+ expect(+ parseAssetKey("branding/logo-dark-1723800000000.svg", profiles)?.profile,+ ).toBe(wordmarkProfile);+ expect(+ parseAssetKey("branding/logo-icon-1723800000000.png", profiles)?.profile,+ ).toBe(iconProfile);+ });++ it("keeps dashes inside the entity id", () => {+ expect(+ parseAssetKey("branding/logo-dark-1723800000000.svg", profiles)?.entityId,+ ).toBe("logo-dark");+ });++ it("rejects keys whose prefix matches no profile", () => {+ expect(parseAssetKey("polls/abc-1723800000000.jpg", profiles)).toBeNull();+ expect(parseAssetKey("abc-1723800000000.jpg", profiles)).toBeNull();+ });++ it("rejects entity ids outside a profile's fixed set", () => {+ expect(+ parseAssetKey("branding/other-1723800000000.png", profiles),+ ).toBeNull();+ });++ it("rejects extensions outside the profile's accept list", () => {+ expect(+ parseAssetKey("avatars/user123-1723800000000.svg", profiles),+ ).toBeNull();+ expect(+ parseAssetKey("branding/logo-icon-1723800000000.svg", profiles),+ ).toBeNull();+ });++ it("rejects malformed keys", () => {+ expect(parseAssetKey("avatars/user123.jpg", profiles)).toBeNull();+ expect(+ parseAssetKey("avatars/user123-notatimestamp.jpg", profiles),+ ).toBeNull();+ expect(parseAssetKey("avatars/user123-1723800000000", profiles)).toBeNull();+ expect(parseAssetKey("", profiles)).toBeNull();+ });+});++describe("validateAssetFile", () => {+ it("accepts a file matching the profile", () => {+ expect(+ validateAssetFile({ type: "image/png", size: 1024 }, avatarProfile),+ ).toEqual({ success: true });+ });++ it("rejects a mime type outside the accept list", () => {+ expect(+ validateAssetFile({ type: "image/svg+xml", size: 1024 }, avatarProfile),+ ).toEqual({ success: false, error: "invalidFileType" });+ });++ it("rejects files over the size cap", () => {+ expect(+ validateAssetFile(+ { type: "image/png", size: avatarProfile.maxSize + 1 },+ avatarProfile,+ ),+ ).toEqual({ success: false, error: "fileTooLarge" });+ });+});diff --git a/apps/web/src/lib/storage/asset-profile.ts b/apps/web/src/lib/storage/asset-profile.tsnew file mode 100644index 000000000..327380e0f--- /dev/null+++ b/apps/web/src/lib/storage/asset-profile.ts@@ -0,0 +1,107 @@+/**+ * Declarative policy for one asset slot (avatar, space icon, branding logo…).+ *+ * A profile is the single source of truth for what a slot accepts: the+ * feature that owns the slot declares it, actions derive their input schemas+ * from it, `createAssetUploadUrl` validates against it at sign time, the+ * self-hosted upload route re-derives the expected content type from it, and+ * the upload control reads it for client-side validation and hint copy.+ *+ * The storage core is media-agnostic: nothing here branches on whether the+ * bytes are pixels. Presentation concerns like cropping belong to the UI+ * components that produce the file, not to the profile.+ */+export interface AssetProfile {+ id: string;+ /**+ * First segment(s) of the storage key. Stable forever — persisted keys in+ * the database carry it. Profiles may share a prefix only if they declare+ * disjoint `entityIds`.+ */+ keyPrefix: string;+ /**+ * Fixed entity ids for singleton slots (e.g. the instance branding logos).+ * Unset means the entity id is caller-scoped (a user or space id).+ */+ entityIds?: readonly string[];+ /** Mime types this slot accepts. */+ accept: readonly [string, ...string[]];+ /** Maximum file size in bytes. */+ maxSize: number;+}++export const extensionByMimeType: Record<string, string> = {+ "image/jpeg": "jpg",+ "image/png": "png",+ "image/svg+xml": "svg",+};++export interface ParsedAssetKey {+ profile: AssetProfile;+ entityId: string;+ /** The accept-list mime type matching the key's extension. */+ mimeType: string;+}++const keyFileNamePattern = /^(.+)-(\d+)\.([a-z0-9]+)$/;++/**+ * Resolves a storage key (`prefix/entityId-timestamp.ext`) to the profile+ * that produced it. Returns null for keys that no known profile could have+ * signed.+ */+export function parseAssetKey(+ key: string,+ profiles: readonly AssetProfile[],+): ParsedAssetKey | null {+ const segments = key.split("/");+ if (segments.length < 2) {+ return null;+ }++ const fileName = segments[segments.length - 1];+ const keyPrefix = segments.slice(0, -1).join("/");++ const match = fileName.match(keyFileNamePattern);+ if (!match) {+ return null;+ }+ const [, entityId, , extension] = match;++ for (const profile of profiles) {+ if (profile.keyPrefix !== keyPrefix) {+ continue;+ }+ if (profile.entityIds && !profile.entityIds.includes(entityId)) {+ continue;+ }+ const mimeType = profile.accept.find(+ (type) => extensionByMimeType[type] === extension,+ );+ if (!mimeType) {+ continue;+ }+ return { profile, entityId, mimeType };+ }++ return null;+}++export type AssetValidationError = "invalidFileType" | "fileTooLarge";++export type AssetValidationResult =+ | { success: true }+ | { success: false; error: AssetValidationError };++export function validateAssetFile(+ file: { type: string; size: number },+ profile: AssetProfile,+): AssetValidationResult {+ if (!profile.accept.includes(file.type)) {+ return { success: false, error: "invalidFileType" };+ }+ if (file.size > profile.maxSize) {+ return { success: false, error: "fileTooLarge" };+ }+ return { success: true };+}diff --git a/apps/web/src/lib/storage/asset-upload.ts b/apps/web/src/lib/storage/asset-upload.tsnew file mode 100644index 000000000..3134ca38d--- /dev/null+++ b/apps/web/src/lib/storage/asset-upload.ts@@ -0,0 +1,172 @@+import "server-only";+import crypto from "node:crypto";+import { DeleteObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";+import { getSignedUrl } from "@aws-sdk/s3-request-presigner";+import { after } from "next/server";+import { env } from "@/env";+import { isSelfHosted } from "@/lib/constants";+import { AppError } from "@/lib/errors/app-error";+import type { AssetProfile } from "./asset-profile";+import { extensionByMimeType, parseAssetKey } from "./asset-profile";+import { isStorageKey } from "./resolve-storage-url";+import { getS3Client } from "./s3";++const UPLOAD_TOKEN_TTL_SECONDS = 3600;++function computeSignature(payload: string) {+ return crypto+ .createHmac("sha256", env.SECRET_PASSWORD)+ .update(payload)+ .digest("hex");+}++export function signUploadKey(key: string) {+ const expiry = Math.floor(Date.now() / 1000) + UPLOAD_TOKEN_TTL_SECONDS;+ const signature = computeSignature(`${key}:${expiry}`);+ return `${expiry}.${signature}`;+}++export function verifyUploadToken(key: string, token: string) {+ const parts = token.split(".");+ if (parts.length !== 2) return false;+ const [expiryStr, signature] = parts;+ const expiry = Number(expiryStr);+ if (!Number.isInteger(expiry)) return false;+ if (expiry <= Math.floor(Date.now() / 1000)) return false;++ const expected = computeSignature(`${key}:${expiry}`);+ const expectedBuf = Buffer.from(expected, "hex");+ const tokenBuf = Buffer.from(signature, "hex");+ if (expectedBuf.length === 0 || expectedBuf.length !== tokenBuf.length) {+ return false;+ }+ return crypto.timingSafeEqual(expectedBuf, tokenBuf);+}++export async function createAssetUploadUrl({+ profile,+ entityId,+ fileType,+ fileSize,+}: {+ profile: AssetProfile;+ entityId: string;+ fileType: string;+ fileSize: number;+}) {+ const s3Client = getS3Client();++ if (!s3Client) {+ throw new AppError({+ code: "INTERNAL_SERVER_ERROR",+ message: "S3 storage has not been configured",+ });+ }++ if (profile.entityIds && !profile.entityIds.includes(entityId)) {+ throw new AppError({+ code: "FORBIDDEN",+ message: `Invalid entity id for asset profile ${profile.id}`,+ });+ }++ if (!profile.accept.includes(fileType)) {+ throw new AppError({+ code: "FORBIDDEN",+ message: `File type ${fileType} is not accepted for asset profile ${profile.id}`,+ });+ }++ if (fileSize > profile.maxSize) {+ throw new AppError({+ code: "PAYLOAD_TOO_LARGE",+ message: "File size too large",+ });+ }++ const key = `${profile.keyPrefix}/${entityId}-${Date.now()}.${extensionByMimeType[fileType]}`;++ if (isSelfHosted) {+ const token = signUploadKey(key);+ return {+ url: `/api/storage/upload/${key}?token=${token}`,+ key,+ };+ }++ const command = new PutObjectCommand({+ Bucket: env.S3_BUCKET_NAME,+ Key: key,+ ContentType: fileType,+ ContentLength: fileSize,+ });++ const url = await getSignedUrl(s3Client, command, { expiresIn: 3600 });++ return { url, key };+}++/**+ * Verifies that a client-submitted key is one this profile could have signed+ * for this entity. Persist actions call this instead of ad-hoc string checks.+ */+export function assertAssetKey(+ key: string,+ expected: { profile: AssetProfile; entityId: string },+) {+ const parsed = parseAssetKey(key, [expected.profile]);++ if (!parsed || parsed.entityId !== expected.entityId) {+ throw new AppError({+ code: "FORBIDDEN",+ message: "Invalid asset key",+ });+ }+}++/**+ * Deletes an object we own. External values (OAuth avatar URLs, data URIs)+ * are not ours to delete and are ignored.+ */+export async function deleteStoredAsset(key: string) {+ if (!isStorageKey(key)) {+ return;+ }++ const s3Client = getS3Client();++ await s3Client?.send(+ new DeleteObjectCommand({+ Bucket: env.S3_BUCKET_NAME,+ Key: key,+ }),+ );+}++/**+ * The replace-an-asset lifecycle: persist the new value, then delete the old+ * object after the response. Guards live here, once: a retry can resubmit+ * the key that is already stored (equality check), and the old value may be+ * externally hosted media (isStorageKey via deleteStoredAsset).+ *+ * Semantics are last-write-wins: currentKey is read before persist, so a+ * delayed duplicate of an older persist that lands after a newer one can+ * delete an object the concurrent write just made current. Closing that+ * window needs sign-time asset records (the planned Asset table), which is+ * where confirm-before-delete will live.+ */+export async function replaceStoredAsset({+ currentKey,+ nextKey,+ persist,+}: {+ currentKey: string | null | undefined;+ nextKey: string | null;+ persist: () => Promise<void>;+}) {+ await persist();++ if (currentKey && currentKey !== nextKey) {+ after(() => deleteStoredAsset(currentKey));+ }+}diff --git a/apps/web/src/lib/storage/image-upload.ts b/apps/web/src/lib/storage/image-upload.tsdeleted file mode 100644index 2f25faa76..000000000--- a/apps/web/src/lib/storage/image-upload.ts+++ /dev/null@@ -1,118 +0,0 @@-import "server-only";-import crypto from "node:crypto";-import { DeleteObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";-import { getSignedUrl } from "@aws-sdk/s3-request-presigner";-import { env } from "@/env";-import { isSelfHosted } from "@/lib/constants";-import { AppError } from "@/lib/errors/app-error";-import { getS3Client } from "./s3";--const UPLOAD_TOKEN_TTL_SECONDS = 3600;--function computeSignature(payload: string) {- return crypto- .createHmac("sha256", env.SECRET_PASSWORD)- .update(payload)- .digest("hex");-}--export function signUploadKey(key: string) {- const expiry = Math.floor(Date.now() / 1000) + UPLOAD_TOKEN_TTL_SECONDS;- const signature = computeSignature(`${key}:${expiry}`);- return `${expiry}.${signature}`;-}--export function verifyUploadToken(key: string, token: string) {- const parts = token.split(".");- if (parts.length !== 2) return false;- const [expiryStr, signature] = parts;- const expiry = Number(expiryStr);- if (!Number.isInteger(expiry)) return false;- if (expiry <= Math.floor(Date.now() / 1000)) return false;-- const expected = computeSignature(`${key}:${expiry}`);- const expectedBuf = Buffer.from(expected, "hex");- const tokenBuf = Buffer.from(signature, "hex");- if (expectedBuf.length === 0 || expectedBuf.length !== tokenBuf.length) {- return false;- }- return crypto.timingSafeEqual(expectedBuf, tokenBuf);-}--const mimeToExtension = {- "image/jpeg": "jpg",- "image/png": "png",- "image/svg+xml": "svg",-} as const;--export interface GetImageUploadUrlParams {- keyPrefix: string;- entityId: string;- fileType: keyof typeof mimeToExtension;- fileSize: number;-}--export async function getImageUploadUrl({- keyPrefix,- entityId,- fileType,- fileSize,-}: GetImageUploadUrlParams) {- const s3Client = getS3Client();-- if (!s3Client) {- throw new AppError({- code: "INTERNAL_SERVER_ERROR",- message: "S3 storage has not been configured",- });- }-- if (fileSize > 2 * 1024 * 1024) {- throw new AppError({- code: "PAYLOAD_TOO_LARGE",- message: "File size too large",- });- }-- const key = `${keyPrefix}/${entityId}-${Date.now()}.${mimeToExtension[fileType]}`;-- if (isSelfHosted) {- const token = signUploadKey(key);- const url = `/api/storage/upload/${key}?token=${token}`;- return {- success: true,- url,- fields: {- key,- },- } as const;- }-- const command = new PutObjectCommand({- Bucket: env.S3_BUCKET_NAME,- Key: key,- ContentType: fileType,- ContentLength: fileSize,- });-- const url = await getSignedUrl(s3Client, command, { expiresIn: 3600 });-- return {- success: true,- url,- fields: {- key,- },- } as const;-}--export async function deleteImageFromS3(imageKey: string) {- const s3Client = getS3Client();-- await s3Client?.send(- new DeleteObjectCommand({- Bucket: env.S3_BUCKET_NAME,- Key: imageKey,- }),- );-}diff --git a/apps/web/src/lib/storage/upload-client.ts b/apps/web/src/lib/storage/upload-client.tsindex 3e32f9724..41e97b1b4 100644--- a/apps/web/src/lib/storage/upload-client.ts+++ b/apps/web/src/lib/storage/upload-client.ts@@ -1,28 +1,24 @@import { AppError } from "@/lib/errors/app-error";-export interface UploadImageParams {- file: File;- url: string;- fileType: "image/jpeg" | "image/png" | "image/svg+xml";-}--export async function uploadImage({- file,+export async function uploadAsset({url,- fileType,-}: UploadImageParams): Promise<void> {+ file,+}: {+ url: string;+ file: File;+}): Promise<void> {const response = await fetch(url, {method: "PUT",body: file,headers: {- "Content-Type": fileType,+ "Content-Type": file.type,},});if (!response.ok) {throw new AppError({code: "INTERNAL_SERVER_ERROR",- message: "Failed to upload image to storage",+ message: "Failed to upload asset to storage",});}}