Secure File Uploads with AI Prompts

Share

TL;DR

File uploads are dangerous. Attackers can upload malicious scripts, oversized files for DoS, or files with misleading extensions. Validate file type by content (not extension), enforce size limits, store outside webroot, and use random filenames. These prompts help you build safe upload handling.

File Upload Validation

Validate Uploaded Files

Implement secure file upload validation.

Requirements:

  1. Validate file type by content (magic bytes), not extension
  2. Enforce maximum file size
  3. Allowlist permitted file types
  4. Generate random filename for storage
  5. Store outside web-accessible directory

For images, validate:

  • Magic bytes match claimed type
  • Actually parseable as image
  • Dimensions within limits
  • Strip EXIF metadata (privacy)

Implementation:

  • Use file-type library to check magic bytes
  • Use sharp or similar to validate/process images
  • Reject if validation fails
  • Never trust Content-Type header

Example allowlist: const allowedTypes = 'image/jpeg', 'image/png', 'image/webp', 'application/pdf'; const maxSize = 5 * 1024 * 1024; // 5MB

Secure Storage

Store Files Safely

Set up secure file storage for uploads.

Storage options:

  1. Cloud storage (S3, Cloudflare R2) - recommended
  2. Local filesystem outside webroot

For S3/R2:

  • Private bucket with signed URLs for access
  • Separate bucket from application code
  • Set proper Content-Type on upload
  • Consider CDN for delivery

For local storage:

  • Store outside public directory
  • Serve through application (not static)
  • Set Content-Disposition header

Filename handling: const safeFilename = crypto.randomUUID() + '.jpg'; // Never use user-provided filename

Serving files: res.setHeader('Content-Type', 'image/jpeg'); res.setHeader('Content-Disposition', 'inline'); // or 'attachment' for downloads res.setHeader('X-Content-Type-Options', 'nosniff');

Never serve with user-controlled Content-Type.

Never trust file extensions: An attacker can name a PHP script "innocent.jpg". Validate by reading the file's magic bytes, not its name. And never store uploads where they can be executed.

Image Processing Security

Process Images Safely

Implement secure image processing for uploads.

Using sharp (Node.js):

async function processImage(buffer, options) { const image = sharp(buffer); const metadata = await image.metadata();

// Validate dimensions if (metadata.width > 4000 || metadata.height > 4000) { throw new Error('Image too large'); }

return image .resize(options.maxWidth, options.maxHeight, { fit: 'inside' }) .rotate() // Auto-rotate based on EXIF .withMetadata(false) // Strip EXIF (removes location data!) .jpeg({ quality: 80 }) // Re-encode (sanitizes) .toBuffer(); }

Benefits of re-encoding:

  • Strips embedded scripts/payloads
  • Removes EXIF metadata (privacy)
  • Normalizes format
  • Validates image is actually valid

Always re-encode uploaded images rather than storing originals.

Client-Side Validation

Frontend Upload UX

Add client-side file validation for better UX.

Note: This is for UX only - always validate server-side!

function validateFile(input) { const file = input.files0; const maxSize = 5 * 1024 * 1024; // 5MB const allowedTypes = 'image/jpeg', 'image/png', 'image/webp';

if (!file) return;

if (!allowedTypes.includes(file.type)) { showError('Please upload a JPEG, PNG, or WebP image'); input.value = ''; return; }

if (file.size > maxSize) { showError('File must be under 5MB'); input.value = ''; return; }

// Optional: preview image const reader = new FileReader(); reader.onload = (e) => previewImage(e.target.result); reader.readAsDataURL(file); }

Remember: Attackers bypass JavaScript. Server must validate too.

Pro tip: Use a dedicated service like Cloudflare Images or Imgix for image processing. They handle resizing, format conversion, and security, taking the burden off your servers.

Can uploaded images contain malware?

Yes. Images can contain embedded scripts, exploit image parser vulnerabilities, or use polyglot techniques (valid image AND valid script). Re-encoding with a library like sharp sanitizes most threats.

Should I scan uploads for viruses?

For high-risk applications (user file sharing), yes. Use ClamAV or a cloud service. For images only, re-encoding is usually sufficient. For documents, consider sandboxed preview generation.

Check Your Upload Security

Scan your file upload handling for vulnerabilities.

Start Free Scan
AI Fix Prompts

Secure File Uploads with AI Prompts