import type { AttachmentMimeType } from '@dorfteich/shared'; /** * Magic-byte signatures for the raster-image allowlist (ADR 0011). The * client-declared MIME type and filename extension are never trusted — * only the actual bytes decide, which is what catches a renamed * `.html`-as-`.png` upload. */ const SIGNATURES: ReadonlyArray<{ mimeType: AttachmentMimeType; matches: (buf: Buffer) => boolean; }> = [ { mimeType: 'image/png', matches: (buf) => buf.length >= 8 && buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])), }, { mimeType: 'image/jpeg', matches: (buf) => buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff, }, { mimeType: 'image/gif', matches: (buf) => buf.length >= 6 && (buf.toString('ascii', 0, 6) === 'GIF87a' || buf.toString('ascii', 0, 6) === 'GIF89a'), }, { mimeType: 'image/webp', matches: (buf) => buf.length >= 12 && buf.toString('ascii', 0, 4) === 'RIFF' && buf.toString('ascii', 8, 12) === 'WEBP', }, ]; /** Returns the sniffed raster-image MIME type, or null when the bytes match none of the allowed signatures. */ export function sniffImageMimeType(buffer: Buffer): AttachmentMimeType | null { return SIGNATURES.find((signature) => signature.matches(buffer))?.mimeType ?? null; } /** * Heuristic SVG detection: an XML document whose leading bytes contain an * `