Validate content types on uploads
Check an uploaded file's real type by reading its magic bytes, and compare the declared Content-Type against an allowlist, not the file name.
The Content-Type of an upload is whatever the client says, and so is the extension. Both are only hints. Check them against an allowlist, then verify the content as the next snippet shows.
const ALLOWED = new Set(['image/png', 'image/jpeg', 'image/webp']);
export function checkUpload(file) {
if (!ALLOWED.has(file.mimetype)) {
return { ok: false, reason: `type ${file.mimetype} is not allowed` };
}
if (file.size > 2 * 1024 * 1024) {
return { ok: false, reason: 'file is larger than 2 MB' };
}
return { ok: true };
}
console.log(checkUpload({ mimetype: 'image/png', size: 1024 }));
console.log(checkUpload({ mimetype: 'text/html', size: 200 }));{ ok: true }
{ ok: false, reason: 'type text/html is not allowed' }An allowlist names what you accept and rejects everything else, including types you have never heard of, which a denylist of .exe and .php cannot do. Serve uploads from a separate domain or with Content-Disposition: attachment and X-Content-Type-Options: nosniff, so a browser never runs one as a page. See the OWASP file upload cheat sheet.
An allowlist on the declared type stops honest mistakes only. A script can claim image/png, so confirm the content too.