NodeJS/Formidable : 保护图像上传的后端

NodeJS/Formidable : secure the backend for images upload

我正在使用 NodeJS/Formidable 并尝试保护我的后端以上传图像。

检查文件是否为图像的经典方法是使用如下正则表达式:

if(!file.name || file.name.match(/\.(jpg|jpeg|png)$/i)) {
    console.log("the file is an image");
}else{
    console.log("the file is not an image");
}

还有这个:

var fileType = file.type.split('/').pop();
if(fileType == 'jpg' || fileType == 'png' || fileType == 'jpeg' ){
    console.log("the file is an image");
} else {
    console.log( 'incorrect file type: ' + fileType );
}

这是一个很好的检查,但这还不够安全;事实上,如果我将 PDF 重命名为 JPG,浏览器会根据文件的扩展名提供 MIME/type : image/jpg 。 这是一个安全问题,因为您可以将 JS 文件或其他文件重命名为 JPG 并将其上传到您的后端文件系统。

我觉得这很有趣 post : How to check file MIME type with javascript before upload?

它非常适合客户端检查,但我无法在后端重现它。

我想理想的方法是在上传前 4 个字节后即时分析流并检查真实的 MIME 类型。

有什么想法吗?

谢谢!

你可能应该使用像 file-type npm 包这样的东西,它需要一个缓冲区(至少前 4100 个字节)并且 return 你会得到 MIME 类型和文件扩展名:

const fileType = require('file-type')
fileType(buffer) //=> {ext: 'png', mime: 'image/png'} 

有效! 你可以安装一个像 readChunk 这样的模块来将文件转换成一个缓冲区,然后写这样的东西:

form.on('file', function(field, file) {
    buffer = readChunk.sync(file.path, 0, 4100);

    filetype = fileType(buffer);

    if(filetype.ext.match(/(jpg|jpeg|png)$/i)) {
        fs.rename(file.path, path.join(form.uploadDir, file.name));
    }else {
        fs.unlink(file.path);
    }

});