How do I upload files in an Express API safely?

posée 3 months ago487 vuesen

4

Users need to upload profile pictures. I'm using multer and saving to ./uploads. What should I watch out for?

Diagnostic IA

Généré par IA. Ce n'est pas une réponse — la communauté ci-dessous le confirme ou le corrige. Vérifiez toujours avant de vous y fier.

posée 3 months ago

1 réponse

7
✓
✓ Réponse acceptée

Key safeguards:

1. Limit size: multer({ limits: { fileSize: 2 * 1024 * 1024 } }). 2. Validate the real type, not the client-provided MIME or extension. Check magic bytes with file-type, and only allow image/jpeg|png|webp. 3. Re-encode images with sharp. This strips EXIF (including GPS location!) and neutralizes polyglot files. 4. Never use the original filename on disk. Generate one with crypto.randomUUID(). 5. Don't serve uploads from your app's origin with executable types. Better: store them in object storage (S3, R2, Supabase Storage) and serve them from a separate domain or CDN. 6. Rate-limit the upload endpoint.

const buf = await sharp(req.file.buffer)
  .rotate()
  .resize(512, 512, { fit: 'cover' })
  .webp({ quality: 80 })
  .toBuffer();

Connectez-vous pour dire si ça a marché.

answered 3 months ago

Sign in and verify your email to post an answer.