import type { AllowedImageType } from "@/lib/media/constants";

/**
 * Identifies the image format from its first bytes. The browser-supplied MIME
 * type and file extension are attacker-controlled, so they are only accepted
 * when they agree with the bytes. No `server-only` guard: the import scripts
 * use it too.
 */
export function sniffImageType(bytes: Uint8Array): AllowedImageType | null {
  const ascii = (start: number, end: number) =>
    String.fromCharCode(...bytes.subarray(start, end));

  if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff)
    return "image/jpeg";
  if (
    bytes[0] === 0x89 &&
    ascii(1, 4) === "PNG" &&
    bytes[4] === 0x0d &&
    bytes[5] === 0x0a
  ) {
    return "image/png";
  }
  if (ascii(0, 4) === "RIFF" && ascii(8, 12) === "WEBP") return "image/webp";
  if (ascii(4, 8) === "ftyp") {
    const brand = ascii(8, 12);
    if (brand === "avif" || brand === "avis") return "image/avif";
  }
  return null;
}
