const SIGNATURE_CHECKS: Record boolean> = { 'image/png': (buffer) => buffer.length >= 8 && buffer .subarray(0, 8) .equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])), 'image/jpeg': (buffer) => buffer.length >= 3 && buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff, 'image/webp': (buffer) => buffer.length >= 12 && buffer.subarray(0, 4).toString('ascii') === 'RIFF' && buffer.subarray(8, 12).toString('ascii') === 'WEBP', 'application/pdf': (buffer) => buffer.length >= 5 && buffer.subarray(0, 5).toString('ascii') === '%PDF-', }; /** * Verifies a file's actual bytes match its declared MIME type instead of * trusting the client-supplied value alone (a multipart Content-Type header * or a data: URL prefix are both attacker-controlled). Used at every upload * path that persists the bytes to disk under a server-chosen name/extension, * so a mislabeled file can't be dropped onto the filesystem as a type it * isn't. Types with no signature defined here are not checked (returns * true) - callers still gate on their own MIME allowlist first. */ export function matchesFileSignature( buffer: Buffer, declaredMimeType: string, ): boolean { const check = SIGNATURE_CHECKS[declaredMimeType]; return check ? check(buffer) : true; }