import { LIMITS } from "./limits.ts"; export const ALLOWED_MIME_TYPES = [ "image/jpeg", "image/png", "image/gif", "image/webp", ] as const; type AllowedMimeType = (typeof ALLOWED_MIME_TYPES)[number]; class ImageValidationError extends Error { constructor(message: string) { super(message); this.name = "ImageValidationError"; } } function isAllowedMimeType(mimeType: string): mimeType is AllowedMimeType { return (ALLOWED_MIME_TYPES as readonly string[]).includes(mimeType); } const SHARP_FORMAT_TO_MIME: Record = { jpeg: "image/jpeg", png: "image/png", gif: "image/gif", webp: "image/webp", }; // GIF magic bytes: "GIF87a" or "GIF89a". function isGifData(data: Buffer): boolean { return data.length >= 6 && data.toString("ascii", 0, 3) === "GIF"; } // Callers check the declared size before reading a body; processImage checks the // bytes it was actually handed. Same ceiling, same message, two places. export function assertImageSize(byteLength: number): void { if (byteLength <= LIMITS.image.bytes) return; const maxMb = LIMITS.image.bytes / 1024 / 1024; throw new ImageValidationError( `Image too large: ${(byteLength / 1024 / 1024).toFixed(1)}MB. Maximum: ${maxMb}MB`, ); } export async function processImage( data: Buffer, mimeType: string, ): Promise<{ data: Buffer; mimeType: string }> { if (!isAllowedMimeType(mimeType)) { throw new ImageValidationError( `Unsupported image type: ${mimeType}. Allowed: ${ALLOWED_MIME_TYPES.join(", ")}`, ); } assertImageSize(data.length); // GIFs pass through after a magic-byte check: sharp's animated-GIF support is limited. if (mimeType === "image/gif") { if (!isGifData(data)) { throw new ImageValidationError("File content is not a valid GIF"); } return { data, mimeType }; } // rotate() applies EXIF orientation then strips metadata; sharp throws on non-image data. const { default: sharp } = await import("sharp"); const instance = sharp(data); const meta = await instance.metadata(); const detectedMime = meta.format ? SHARP_FORMAT_TO_MIME[meta.format] : undefined; if (detectedMime && detectedMime !== mimeType) { throw new ImageValidationError( `MIME type mismatch: claimed ${mimeType} but content is ${detectedMime}`, ); } const processed = await instance.rotate().toBuffer(); return { data: processed, mimeType }; }