Asset Storage System
This document outlines the architecture, usage, security policies, media lifecycles, and configuration options for the application-level Asset Storage system.
Overview
The asset storage system provides a provider-neutral abstraction layer (StorageProvider) that isolates application feature logic from vendor-specific storage SDKs.
It supports seamless dynamic switching between local filesystem storage (for development and persistent-volume deployments) and S3-compatible cloud object storage (for production deployments across providers such as AWS S3, Cloudflare R2, MinIO, Backblaze B2, and DigitalOcean Spaces).
Storage Interface
All storage operations and shared types (StorageObject, UploadOptions, StorageUploadInputObject, StorageUploadInput, StorageValidationResult, and StorageProvider) are exposed via src/utils/storage.ts:
export interface StorageObject {
key: string; // Key/path in bucket or relative path (e.g., "uploads/abcdef1234567890.png")
url: string; // Fully resolved public URL
size: number; // File size in bytes
mimeType: string; // MIME type (e.g., "image/png")
metadata?: Record<string, string>; // Optional custom metadata key-value pairs
etag?: string; // Optional ETag / version tag
updatedAt?: Date; // Optional last modified date
}
export interface UploadOptions {
key?: string; // Specific object key to use (must stay within "uploads/" on LocalStorageProvider)
folder?: string; // Directory/prefix (default: "uploads"; LocalStorageProvider requires "uploads" or "uploads/*")
metadata?: Record<string, string>; // Custom metadata
contentType?: string; // MIME type override
}
export interface StorageUploadInputObject {
buffer: Buffer; // Raw binary payload
filename: string; // Original or normalized filename
mimeType: string; // Declared MIME type
}
export type StorageUploadInput = File | StorageUploadInputObject;
export interface StorageValidationResult {
valid: boolean;
error?: string;
}
export interface StorageProvider {
/** Upload file or buffer and receive full object metadata */
upload(input: StorageUploadInput, options?: UploadOptions): Promise<StorageObject>;
/** Delete an asset by key or public URL */
delete(keyOrUrl: string): Promise<void>;
/** Resolve public URL for a key or URL */
getPublicUrl(keyOrUrl: string): string;
/** Fetch object metadata if present */
getMetadata(keyOrUrl: string): Promise<StorageObject | null>;
/** Stream an uploaded object (or inspect metadata when headOnly is true) */
openReadStream(
keyOrUrl: string,
options?: { headOnly?: boolean }
): Promise<LocalUploadStreamResult | null>;
/** Validate provider configuration and health status */
validateConfig(): Promise<StorageValidationResult>;
}Both LocalStorageProvider and S3StorageProvider implement openReadStream returning LocalUploadStreamResult (src/utils/storage.ts) so authorized /uploads/* requests stream seamlessly through src/app/api/uploads/[...path]/route.ts.
Storage Adapters
1. Local Development & Persistent Volume Mode (LocalStorageProvider)
- Instantiated by
getStorageProvider(src/utils/storage.ts) when S3 credentials are not defined in environment variables. - Strict
public/uploadsContainment: Confines everyupload,delete,getMetadata, andopenReadStreammethod (src/utils/storage.ts) topublic/uploads/viaresolveContainedWritePathandresolveContainedExistingPath(src/utils/pathContainment.ts). Both helpers enforce lexicalpath.relativebounds, canonicalfs.promises.realpathchecks across target and ancestor directories (accepting an optional pre-resolvedcanonicalRootinresolveContainedExistingPathto avoid redundant rootrealpathsyscalls during batch reads), null-byte and backslash rejection, and symbolic link rejection (fs.lstat). Passing akeyorfolderoutsidepublic/uploads(for example{ folder: 'photos' }or{ key: 'images/logo.png' }) throwsPathContainmentError(src/utils/pathContainment.ts). - Extension-Based Local Metadata:
LocalStorageProvider.getMetadata(src/utils/storage.ts) resolves MIME types from file extensions viagetLocalUploadMimeType(src/utils/storage.ts), mapping.png,.jpg,.jpeg,.webp, and.icoto their image MIME types and returningapplication/octet-streamfor any other extension (such as.svgor.bin). Custommetadatakey-value pairs andetagvalues are not persisted on disk byLocalStorageProvider. - Serves files dynamically at
/uploads/*in Next.js standalone/server mode vianext.config.tsserverrewrites()toGETandHEADin src/app/api/uploads/[...path]/route.ts, which verifies path containment (resolveContainedExistingPath), rejects symlinks, enforces session and moderation checks (allowing unauthenticated reads only forAppConfig.ogImageUrlandAppConfig.faviconUrl), and attachesContent-Security-Policy: default-src 'none'; sandbox,Cross-Origin-Resource-Policy: same-origin,X-Content-Type-Options: nosniff,Content-Disposition: attachmentfor fallbackapplication/octet-streampayloads (continuing to serve existing.icofiles withimage/x-iconundersandbox),Vary: Cookie, andCache-Control: private, no-cache(Cache-Control: private, no-storeforPENDINGadmin previews).
⚠️ WARNING: Ephemeral Container Local Storage Hazard
Files uploaded when using
LocalStorageProviderare saved directly topublic/uploads/inside the local application container filesystem. Inside containerized environments (such as Docker or Kubernetes), this writable layer is ephemeral unless backed by a persistent volume. If an unmounted container is restarted, updated, or recreated, all files stored inpublic/uploads/will be permanently lost.Production Requirement: When S3 object storage credentials are not configured in production environments, deployers must mount a persistent volume at
/app/public/uploads(such as the defaultuploads_data:/app/public/uploadsnamed volume indocker-compose.yml,-v /var/lib/wedding/uploads:/app/public/uploads, or a Render Persistent Disk) to ensure asset durability.
2. S3-Compatible Production (S3StorageProvider)
- Used when all required S3 credentials are configured in environment variables via
getStorageProvider(src/utils/storage.ts). - Built using AWS SDK v3 (
@aws-sdk/client-s3); vendor SDK usage is strictly isolated inside adapter boundaries. - Path-Style Endpoints,
/uploads/*Routing, Extension-Derived MIME Types, & Legacy URL Fallback: WhenS3_ENDPOINTis set,S3StorageProvider(src/utils/storage.ts) automatically enablesforcePathStyle: trueonS3Client. Uploaded S3 keys normalize underuploads/*andgetPublicUrlreturns root-relative/uploads/*paths so reads pass through the session, moderation, anddefault-src 'none'; sandboxheader gates in src/app/api/uploads/[...path]/route.ts viaS3StorageProvider.openReadStream(bothS3StorageProvider.getMetadataandS3StorageProvider.openReadStreamderivemimeTypestrictly fromgetLocalUploadMimeTyperather than untrusted S3ContentTypeobject metadata). For legacy external URL key extraction (extractKey),S3StorageProviderretainsS3_PUBLIC_URLor falls back to`${endpoint}/${bucket}`(`${S3_ENDPOINT}/${S3_BUCKET}`) whenS3_ENDPOINTis present, or`https://${bucket}.s3.${region}.amazonaws.com`otherwise. - Cloudflare R2 Endpoint & Public URL Validation: Cloudflare R2 configurations setting
S3_REGION=automust also defineS3_ENDPOINT(e.g.,`https://{account_id}.r2.cloudflarestorage.com`). Because private R2 S3 API endpoints (*.r2.cloudflarestorage.com) require SigV4 authentication and are not publicly readable by browsers, bothsrc/env.tsandS3StorageProviderreject*.r2.cloudflarestorage.comendpoints unlessS3_PUBLIC_URLis configured (pointing to an R2 Custom Domain or publichttps://pub-<id>.r2.devbucket URL). - Supports any S3-compatible object storage vendor, including:
- AWS S3: Default endpoint format (
`https://{bucket}.s3.{region}.amazonaws.com`) - Cloudflare R2: Configured via
S3_ENDPOINT(e.g.,`https://{account_id}.r2.cloudflarestorage.com`) plusS3_PUBLIC_URLfor public browser asset delivery - MinIO / Self-Hosted: Configured via
S3_ENDPOINT(withforcePathStyle: true) and optionalS3_PUBLIC_URL - Backblaze B2: Configured via
S3_ENDPOINTand optionalS3_PUBLIC_URL
- AWS S3: Default endpoint format (
Environment Configuration
| Variable | Required for S3 | Description |
|---|---|---|
S3_BUCKET | Yes | Target storage bucket name |
S3_REGION | Yes | Storage region (e.g. us-east-1 or auto for Cloudflare R2) |
S3_ACCESS_KEY_ID | Yes | Storage access key ID |
S3_SECRET_ACCESS_KEY | Yes | Storage secret access key |
S3_ENDPOINT | Optional | Custom S3 API endpoint URL for non-AWS providers (enables forcePathStyle: true) |
S3_PUBLIC_URL | Required for R2 public assets; Optional otherwise | Public CDN, R2 Custom Domain, or r2.dev URL prefix overriding the `${S3_ENDPOINT}/${S3_BUCKET}` fallback |
Validation Behavior
- If no S3 variables are set,
getStorageProvider(src/utils/storage.ts) automatically defaults toLocalStorageProvider. - If all four core S3 variables (
S3_BUCKET,S3_REGION,S3_ACCESS_KEY_ID,S3_SECRET_ACCESS_KEY) are set, the system instantiatesS3StorageProvider. - If partial/inconsistent S3 variables are provided (e.g.,
S3_BUCKETis set withoutS3_SECRET_ACCESS_KEY), or if Cloudflare R2 is configured withS3_REGION=autowithoutS3_ENDPOINTor with a private*.r2.cloudflarestorage.comendpoint withoutS3_PUBLIC_URL,getStorageProviderthrows a descriptive validation error. - Scope of
validateConfig():LocalStorageProvider.validateConfig(src/utils/storage.ts) verifies filesystem write readiness by runningfs.mkdir(public/uploads, { recursive: true }). By contrast,S3StorageProvider.validateConfig(src/utils/storage.ts) checks that the fourprocess.envcredential strings are non-empty and that Cloudflare R2S3_ENDPOINT/S3_PUBLIC_URLinvariants hold; it does not issue live network calls to S3 or verify thatS3_PUBLIC_URLis publicly reachable over HTTP.
Security Policies & Security Controls
1. File Type, Batch Count, and Size Validation
The application defines distinct file size, batch, and format validation rules for administrative asset uploads versus guest photo submissions:
Administrative Upload Constraints
- Maximum File Size: 5 MB (
MAX_UPLOAD_SIZE = 5 * 1024 * 1024), exported asMAX_UPLOAD_SIZEin src/utils/validationPrimitives.ts and enforced byAdminUploadSchemain src/utils/validation.ts. - Allowed MIME Types: JPEG (
image/jpeg), PNG (image/png), ICO (image/x-icon,image/vnd.microsoft.icon). - Allowed Extensions:
.jpg,.jpeg,.png,.ico. - Extension & MIME Consistency: Uploaded file extensions must match declared MIME types (
MIME_TO_EXTENSIONS).
Guest Photo Upload Constraints
- Maximum File Size: 10 MB per file (
MAX_GUEST_PHOTO_SIZE = 10 * 1024 * 1024), exported asMAX_GUEST_PHOTO_SIZEin src/utils/validationPrimitives.ts and enforced per file bySingleGuestPhotoSchemaandvalidateSingleGuestPhotoFilein src/utils/validation.ts. - Batch Upload Cap: Maximum 10 photos per upload request (
files: z.array(SingleGuestPhotoSchema).min(1).max(10)), with optionaluploaderName(<= 100chars),caption(<= 500chars), and per-filecaptions/idempotencyKeysvalidated inGuestPhotoUploadSchemaandGuestPhotoBatchEnvelopeSchema(src/utils/validation.ts). - Allowed MIME Types: JPEG (
image/jpeg), PNG (image/png), WebP (image/webp), and HEIC/HEIF (image/heic,image/heif,image/heic-sequence,image/heif-sequence, or empty/application/octet-streamwhen paired with.heic/.heif). - Allowed Extensions:
.jpg,.jpeg,.png,.webp,.heic,.heif(excluding.ico).
2. Asset & Path URL Guards
Persisted configuration, media, and local path URLs are validated by the URL guard primitives in src/utils/validationPrimitives.ts (re-exported via src/utils/validation.ts):
decodeUrlPathSafely(src/utils/validationPrimitives.ts): Strips query/fragment suffixes and iteratively percent-decodes paths up to 3 rounds (including per-segment fallback decoding), returningnullon null bytes (\0/%00), backslashes (\/%5c), or>3xmulti-encoding.isSafeLocalPathUrl(src/utils/validationPrimitives.ts): Rejects parent traversal (..), protocol-relative or empty double slashes (//), backslashes, and null bytes across both raw anddecodeUrlPathSafely-decoded forms.isSafeConfigAssetUrl(src/utils/validationPrimitives.ts): GuardsAppConfigbranding, Open Graph, and favicon fields; permits'', validhttp(s)://URLs, or root-relative local paths (requireLeadingSlash: true).isSafeMediaOrPhotoUrl(src/utils/validationPrimitives.ts): GuardsMediaandPhotoContentNodeURLs; permits'', validhttp(s)://URLs, base64data:image/*URIs, or safe local paths (requireLeadingSlash: false) while blocking dangerous schemes (javascript:,vbscript:,file:, etc.).
3. Image Sanitization & Processing Pipeline
All uploaded image files undergo server-side sanitization prior to persistence via sanitizeImage in src/utils/imageProcessor.ts and processImageWorkerBuffer in src/utils/imageProcessorWorker.ts:
- Pre-Decode Byte & Dimension Guards: Rejects inputs larger than
MAX_GUEST_PHOTO_SIZE(10 * 1024 * 1024) prior to buffering/decoding, validates ISOBMFFispespatial extents viaparseHeicSpatialExtents(failing closed when ISOBMFF box nesting depth exceedsMAX_ISOBMFF_BOX_DEPTH=6) before lazyheic-decodeWASM loading, inspects every container frame header viaheic-decodeall()(getHeicDecoder) withassertWithinImageDimensionLimitsprior todecode()RGBA buffer allocation (catching derived HEIFgridcanvases and always releasinglibheif-jsWASM handles viadispose()insidefinally), and enforcesMAX_IMAGE_PIXELS(64000000via SharplimitInputPixels) andMAX_IMAGE_DIMENSION(12000max side). - EXIF Metadata Stripping: Strips all embedded EXIF metadata, GPS geotags, camera model identifiers, and timestamps to protect guest and administrator privacy.
- Auto-Rotation: Automatically rotates images based on embedded EXIF orientation tags (
.rotate()) prior to metadata stripping so photos render with correct orientation. - Format, HEIC, &
.icoTranscoding (Fail-Closed): Sharp sanitization preserves JPEG, PNG, and WebP formats, transcodes HEIC/HEIF frames (lazily loadedheic-decode+ Sharp) into sanitizedimage/jpegfiles, parses.icoICONDIR/ICONDIRENTRYheaders (parseIcoDirectoryEntriesin src/utils/imageProcessorWorker.ts) to re-encode the largest frame toimage/png(.pngfilename), and fails closed withApiError(400, ...)insanitizeImage(src/utils/imageProcessor.ts) whenever an unsupported or malformed format is encountered.
4. Worker Thread Offloading & Timeout Handling
To protect the main Node.js event loop from CPU-heavy image processing tasks, sanitization is offloaded to a bounded pool of warm background worker threads using offloadSanitizeToWorker in src/utils/imageProcessor.ts:
- Worker Thread Execution & Resource Limits: Image buffer processing runs inside reusable Node.js worker threads (
new Worker(new URL('./imageProcessorWorker.ts', import.meta.url), { workerData: { isImageProcessorPoolWorker: true }, resourceLimits: { ...WORKER_RESOURCE_LIMITS } }), or--experimental-strip-typesunderNODE_ENV === 'test') bounded by V8WORKER_RESOURCE_LIMITS(maxOldGenerationSizeMb: 256,maxYoungGenerationSizeMb: 64). Concurrent HEIC/HEIF transcoding jobs are capped atMAX_CONCURRENT_HEIC_WORKERS(2) active workers indrainPendingTaskswhile keeping up to4workers (DEFAULT_MAX_WORKER_POOL_SIZE) available for raster images; workersunref()while idle, transferArrayBufferpayloads once ready, and never fall back to the main thread. - Default 10-Second Worker Timeout: A strict 10-second timeout (
timeoutMs = 10000) is enforced per sanitization job. - Timeout, OOM & Error Behavior: If worker execution exceeds 10 seconds, hits V8
resourceLimits, emits an error, or exits unexpectedly, the failure is logged withlogger.error, any stalled or crashed worker is evicted and terminated (failAndEvictWorkerSlot/worker.terminate()), and an HTTP 400 error response is returned (ApiError(400, 'Image sanitization failed. Worker thread timed out.')on timeout orApiError(400, ...)on error/exit).
5. Credential Safety
- Cloud credentials (
S3_ACCESS_KEY_ID,S3_SECRET_ACCESS_KEY) are exclusively accessible on the server side (Node.js runtime). - Credentials are never prefixed with
NEXT_PUBLIC_and are never bundled into client browser code.
Media Persistence, Moderation, Export & Header Lifecycles
1. Upload Persistence: Admin vs. Guest Routes
- Stateless Admin Upload (
POST /api/admin/upload):POSTin src/app/api/admin/upload/route.ts sanitizes a single image, writes it to the defaultuploadsprefix viagetStorageProvider().upload(sanitizedFile), and returns{ url }without insertingMediaorContentNodedatabase rows (callers persist the returned URL onAppConfigor entity payloads). - Stateful Guest Photo Upload (
POST /api/guest/photos/upload):POSTin src/app/api/guest/photos/upload/route.ts enforceslimit: 15requests/minute per session and a shared-venueipLimit: 300requests/minute per client IP (keyPrefix: 'guest-photo-upload') across guest session tokens, sanitizes valid candidate images concurrently (BATCH_SANITIZE_CONCURRENCY = 4) before uploading sanitized files with bounded concurrency (BATCH_PERSIST_CONCURRENCY = 4) under{ folder: 'uploads/photos' }, and persists valid uploads in one transaction viamediaRepository.createGuestPhotosBatch(falling back to per-itemmediaRepository.createMediaandcontentRepository.createNodeon partial mocks) to insert bothMediarows andPhotoContentNoderows (with tags['gallery', 'guest-upload'],status: 'PENDING'andisVisible: falsefor moderation by default, orstatus: 'APPROVED'andisVisible: truewhenAppConfig.autoApproveGuestPhotosis enabled, alongsidedata.mediaId), returning207Multi-Status when individual files fail validation/sanitization while valid files succeed, and cleaning up uploaded storage objects viastorage.deleteif an upload or database failure occurs. Response items omiturlwhilestatusisPENDINGso unapproved storage paths are not exposed before couple moderation.
2. Moderation Rejection & Direct Media Deletion Cleanup
- Full Cleanup on Moderation Rejection: Calling
ContentService.moderatePhoto(src/features/content/service.ts) with'reject'(ContentService.moderatePhoto(nodeId, 'reject')) deletes unreferenced linkedMediadatabase records and underlying storage objects viamediaRepository.deleteMedia(data.mediaId)(preserving entity-boundMediarows, skipping redundantthis.repo.deleteNode(nodeId, author)calls whendeleteMediaalready removed the linkedPhotonode, and falling back togetStorageProvider().delete(data.url)only when noMediarow was removed so storage deletion is never duplicated) and ensures thePhotoContentNode(this.repo.deleteNode(nodeId, author)) is removed. - Set-Based Batch Moderation & Bounded Post-Commit Cleanup: Calling
ContentService.moderatePhotosBatch(src/features/content/service.ts) delegates batch approvals toContentRepository.approvePhotosBatchand batch rejections toContentRepository.rejectPhotosBatch(src/features/content/repository.ts), executing a single interactive database transaction per batch withMediaRepository.deleteMediaBatchand unlinking deduplicated managed storage assets after transaction commit viaunlinkManagedStorageUrls(src/features/media/repository.ts, capped at 8 concurrent workers). - Post-Commit Storage Cleanup on
DELETE /api/media/[id]: CallingDELETE /api/media/[id](src/app/api/media/[id]/route.ts) invokesMediaRepository.deleteMedia(src/features/media/repository.ts) viamediaRepository.deleteMedia(id), which removes linkedPhotoContentNoderows and theMediarow inside a database transaction (preserving audit snapshots) and then callsgetStorageProvider().delete(deletedMedia.url)after the transaction commits, preventing orphaned local or S3 blobs.
3. Streaming Bulk ZIP Export (GET & POST /api/media/export)
GETandPOSTin src/app/api/media/export/route.ts stream sanitized.ziparchives (defaulting toContent-Disposition: attachment; filename="wedding-photos.zip") througharchivercoupled to a pull-driven WebReadableStreamthat pauses on consumer backpressure and abortsarchiverplus pendingsafeFetchrequests (AbortSignal) if the download stream is cancelled.- Zero-Recompression (
STORE) Image Entries & Native Downloads: Compressed image formats (.jpg,.jpeg,.png,.webp,.gif,.avif,.heic,.heif) are written withstore: true(ZIP method0/STORE), while non-image and diagnostic.txtnotices fall back tozliblevel5deflate. Supports lightweightpreflightreadiness checks (GETquery or JSON/formPOST) andOrigin/Sec-Fetch-Site-validatedapplication/x-www-form-urlencodedPOSTsubmissions so admin UIs trigger native<a download>or hidden<form method="POST">downloads without bufferingResponse.blob()in browser RAM. - Processes export items in batches of 8 (
CONCURRENCY_LIMIT = 8) and awaits batch drain before fetching the next batch: decodesdata:URIs in memory, downloads remotehttp(s)://URLs via SSRF-guardedsafeFetch, and resolves local paths insidepublic/viaresolveContainedExistingPath(reusing a single canonicalpublic/realpathand passingfs.Statsintoarchive.file). Missing local files, failed upstream fetches, orPathContainmentErrorviolations emit per-itemmissing_<filename>.txtorerror_<filename>.txtdiagnostic entries rather than aborting the stream.
4. Local Image Header Parsing for Open Graph Metadata
getLocalImageDimensionsin src/utils/image-metadata.ts resolves root-relative local asset URLs underpublic/viaresolveContainedExistingPath(requireLeadingSlash: true) and performs surgical byte-offset reads (fs.promises.open) on PNG (IHDR24-byte header), JPEG (SOFmarker scan), and SVG (width/heightorviewBoxwithin the first 4096 bytes) without loading full image buffers into memory.- Invoked by
generateMetadataat src/app/metadata.ts to populate Open Graph image dimensions; remotehttp(s)://URLs and unsupported local extensions (such as.webpor.ico) returnnulland fall back to1200x630.
Business Logic Decoupling
Application components and API endpoints access storage solely through getStorageProvider (src/utils/storage.ts):
import { getStorageProvider } from '@/utils/storage';
const storage = getStorageProvider();
const object = await storage.upload(file, { folder: 'uploads/photos' });Portable Folder Prefix Contract: Both S3StorageProvider.upload and LocalStorageProvider.upload (src/utils/storage.ts) normalize uploaded keys under uploads/ (LocalStorageProvider.upload enforces strict filesystem containment under public/uploads and throws PathContainmentError for any folder or key outside uploads). Feature and route code should always omit options.folder (defaulting to 'uploads') or pass 'uploads/<subpath>' so switching between LocalStorageProvider, AWS S3, Cloudflare R2, or MinIO requires zero code changes.