fix(security): validate file uploads with magic bytes, remove SVG from favicon whitelist
- Add validateImageMagicBytes() to storage.ts reading first 12 bytes to verify JPEG/PNG/WebP/ICO signatures regardless of declared MIME type - Remove image/svg+xml from favicon upload whitelist (SVG can embed scripts) - Apply magic bytes check in product image and favicon upload endpoints
This commit is contained in:
@@ -16,6 +16,23 @@ export async function saveImage(
|
||||
return `/uploads/${productId}/${filename}`
|
||||
}
|
||||
|
||||
const IMAGE_MAGIC_BYTES: Record<string, (buf: Buffer) => boolean> = {
|
||||
'image/jpeg': (b) => b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff,
|
||||
'image/png': (b) => b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47,
|
||||
'image/webp': (b) =>
|
||||
b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46 &&
|
||||
b[8] === 0x57 && b[9] === 0x45 && b[10] === 0x42 && b[11] === 0x50,
|
||||
'image/x-icon': (b) => b[0] === 0x00 && b[1] === 0x00 && b[2] === 0x01 && b[3] === 0x00,
|
||||
}
|
||||
|
||||
export async function validateImageMagicBytes(file: File, declaredType: string): Promise<boolean> {
|
||||
const checker = IMAGE_MAGIC_BYTES[declaredType]
|
||||
if (!checker) return false
|
||||
const arrayBuffer = await file.slice(0, 12).arrayBuffer()
|
||||
const buf = Buffer.from(arrayBuffer)
|
||||
return checker(buf)
|
||||
}
|
||||
|
||||
export async function deleteImageFile(url: string): Promise<void> {
|
||||
const filePath = path.join(process.cwd(), 'public', url)
|
||||
await unlink(filePath)
|
||||
|
||||
Reference in New Issue
Block a user