(filename: string, mimetype: string)
| 140 | * @returns {void} Throws an error if validation fails |
| 141 | */ |
| 142 | export const validateMimeTypeAndExtensionMatch = (filename: string, mimetype: string): void => { |
| 143 | validateFilename(filename) |
| 144 | |
| 145 | if (!mimetype || typeof mimetype !== 'string') { |
| 146 | throw new Error('Invalid MIME type: MIME type is required and must be a string') |
| 147 | } |
| 148 | |
| 149 | const normalizedExt = extractFileExtension(filename) |
| 150 | |
| 151 | if (!normalizedExt) { |
| 152 | // Files without extensions are rejected for security |
| 153 | throw new Error('File type not allowed: files must have a valid file extension') |
| 154 | } |
| 155 | |
| 156 | // Get the expected extension from mapMimeTypeToExt (returns extension without dot) |
| 157 | const expectedExt = mapMimeTypeToExt(mimetype) |
| 158 | |
| 159 | if (!expectedExt) { |
| 160 | // If mapMimeTypeToExt doesn't recognize the MIME type, it's not supported |
| 161 | throw new Error(`MIME type "${mimetype}" is not supported or does not have a valid file extension mapping`) |
| 162 | } |
| 163 | |
| 164 | // Ensure the file extension matches the expected extension for the MIME type |
| 165 | if (normalizedExt !== expectedExt) { |
| 166 | throw new Error( |
| 167 | `MIME type mismatch: file extension "${normalizedExt}" does not match declared MIME type "${mimetype}". Expected: ${expectedExt}` |
| 168 | ) |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | /** |
| 173 | * Filters an array of MIME type strings to only those allowed for file upload config. |
no test coverage detected