Hi, I’m trying to create a server side function to validate the file type to prevent any malicious file upload but I don’t know what to feed into fileTypeFromFile. the path is empty.
import { Plugin } from '@nocobase/server';
import { fileTypeFromFile } from 'file-type';
export default class FileValidation extends Plugin {
async load() {
this.db.on('file.afterCreate', async (model: any, options: any) => {
const allowedMimeTypes = new Set([
'image/jpeg',
'image/png',
'image/webp',
'application/pdf',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
]);
const mimeType = model.get('mimetype')
// Do not trust the MIME type supplied by the client.
const filePath = options.values.path
console.log('path: ', filePath)
if (!filePath) {
throw new Error('Cannot validate uploaded file');
}
const detected = await fileTypeFromFile(filePath);
console.log('detected: ', detected.mime)
if (!detected || !allowedMimeTypes.has(detected.mime)) {
throw new Error('This file type is not allowed');
}
// Compare declared MIME type with detected MIME type.
if (mimeType !== detected.mime) {
throw new Error('File MIME type does not match its contents');
}
});
}
}