src / verifiedImages.ts

import {open} from "node:fs/promises";
import sharp from "sharp";

export const IMAGE_BYTE_LIMIT = 20 * 1024 * 1024;
export const IMAGE_BATCH_LIMIT = 64 * 1024 * 1024;
const PIXEL_LIMIT = 40_000_000;
export interface ImageBudget {remaining: number;}
export class ImageValidationError extends Error {
  constructor(readonly code: string, message: string) {super(message); this.name = "ImageValidationError";}
}
export interface VerifiedImage {bytes: Buffer; mime: string; extension: string; width: number; height: number; finalUrl?: string;}
const types: Record<string, {extension: string; decoder: string}> = {
  "image/png": {extension: "png", decoder: "png"}, "image/jpeg": {extension: "jpg", decoder: "jpeg"},
  "image/gif": {extension: "gif", decoder: "gif"}, "image/webp": {extension: "webp", decoder: "webp"},
  "image/tiff": {extension: "tiff", decoder: "tiff"}, "image/avif": {extension: "avif", decoder: "heif"},
};
const aliases: Record<string,string> = {"image/jpg":"image/jpeg", "image/pjpeg":"image/jpeg", "image/x-png":"image/png", "image/apng":"image/png", "image/tif":"image/tiff"};
function mimeType(value?: string | null) {
  const mime = value?.split(";")[0].trim().toLowerCase() ?? "";
  return aliases[mime] ?? mime;
}
function sniff(bytes: Buffer): string | undefined {
  if (bytes.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10]))) return "image/png";
  if (bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "image/jpeg";
  if (/^GIF8[79]a$/.test(bytes.subarray(0,6).toString("ascii"))) return "image/gif";
  if (bytes.subarray(0,4).toString("ascii") === "RIFF" && bytes.subarray(8,12).toString("ascii") === "WEBP") return "image/webp";
  if (["49492a00","4d4d002a"].includes(bytes.subarray(0,4).toString("hex"))) return "image/tiff";
  if (bytes.subarray(4,8).toString("ascii") === "ftyp") {
    const brands = [bytes.subarray(8,12).toString("ascii")];
    for (let n=16;n+4<=Math.min(bytes.length,64);n+=4) brands.push(bytes.subarray(n,n+4).toString("ascii"));
    if (brands.some(brand=>brand === "avif" || brand === "avis")) return "image/avif";
  }
  return undefined;
}
function charge(size: number, budget: ImageBudget) {
  if (size > budget.remaining) throw new ImageValidationError("batch_too_large", "Image reads exceed the 64 MiB call budget.");
  budget.remaining -= size;
}

export async function validateImageBytes(bytes: Buffer, declaredMime?: string | null, signal?: AbortSignal): Promise<VerifiedImage> {
  signal?.throwIfAborted();
  if (!bytes.length || bytes.length > IMAGE_BYTE_LIMIT) throw new ImageValidationError("invalid_size", "Image must contain 1 byte to 20 MiB.");
  const mime = sniff(bytes), declared = mimeType(declaredMime);
  if (!mime) throw new ImageValidationError("not_image_data", "Response body is not a supported raster image. HTML/JSON/error pages are not saved as images.");
  if (declared && !["application/octet-stream","binary/octet-stream"].includes(declared) && declared !== mime) {
    throw new ImageValidationError("mime_mismatch", `Content-Type ${declared} conflicts with detected ${mime}.`);
  }
  const options = {failOn: "warning" as const, limitInputPixels: PIXEL_LIMIT, animated: false};
  try {
    const info = await sharp(bytes, options).metadata();
    if (info.format !== types[mime].decoder || !info.width || !info.height || info.width * info.height > PIXEL_LIMIT) throw new Error("Invalid image metadata.");
    // Metadata alone can accept a truncated file. Decode the first frame too.
    await sharp(bytes, options).resize(1,1,{fit:"inside"}).raw().toBuffer();
    signal?.throwIfAborted();
    return {bytes, mime, extension: types[mime].extension, width: info.width, height: info.height};
  } catch (error) {
    signal?.throwIfAborted();
    throw new ImageValidationError("invalid_image", "Image data cannot be decoded, is truncated, or exceeds 40 million pixels.");
  }
}

export async function fetchVerifiedImage(url: string, headers: Record<string,string>, signal: AbortSignal, budget: ImageBudget): Promise<VerifiedImage> {
  if (!/^https?:$/.test(new URL(url).protocol)) throw new ImageValidationError("invalid_url", "Image URL must use HTTP(S).");
  const requestHeaders = {...headers, Accept:"image/avif,image/webp,image/png,image/jpeg,image/gif,image/tiff;q=0.9,*/*;q=0.1", "Sec-Fetch-Dest":"image", "Sec-Fetch-Mode":"no-cors"};
  delete (requestHeaders as Record<string,string>)["Sec-Fetch-User"];
  delete (requestHeaders as Record<string,string>)["Upgrade-Insecure-Requests"];
  const requestSignal = AbortSignal.any([signal, AbortSignal.timeout(30000)]);
  const response = await fetch(url,{headers:requestHeaders,signal:requestSignal,redirect:"follow"});
  const reject = async (code: string, reason: string): Promise<never> => {await response.body?.cancel().catch(()=>{});throw new ImageValidationError(code,reason);};
  if (!response.ok) return reject("http_error", `Image request failed with HTTP ${response.status}.`);
  const finalUrl = response.url || url;
  if (!/^https?:$/.test(new URL(finalUrl).protocol)) return reject("invalid_redirect", "Image redirect did not end at an HTTP(S) URL.");
  const declared = mimeType(response.headers.get("content-type"));
  if (declared && !types[declared] && !["application/octet-stream","binary/octet-stream"].includes(declared)) {
    return reject("not_image_mime", `URL returned ${declared}, not a supported raster image. Use a direct image URL instead of a page/gallery URL.`);
  }
  const contentLength = Number(response.headers.get("content-length"));
  if (contentLength > IMAGE_BYTE_LIMIT) return reject("image_too_large", "Image response exceeds 20 MiB.");
  if (contentLength > budget.remaining) return reject("batch_too_large", "Image response exceeds the remaining call budget.");
  const reader = response.body?.getReader(), chunks: Buffer[] = [];
  let size = 0;
  if (reader) try {
    while (true) {
      requestSignal.throwIfAborted();
      const chunk = await reader.read();
      if (chunk.done) break;
      size += chunk.value.byteLength;
      if (size > IMAGE_BYTE_LIMIT) throw new ImageValidationError("image_too_large", "Image response exceeds 20 MiB.");
      charge(chunk.value.byteLength,budget);chunks.push(Buffer.from(chunk.value));
    }
  } finally {await reader.cancel().catch(()=>{});reader.releaseLock();}
  return {...await validateImageBytes(Buffer.concat(chunks,size),declared,requestSignal),finalUrl};
}

export async function validateLocalImage(path: string, signal: AbortSignal, budget: ImageBudget): Promise<VerifiedImage> {
  signal.throwIfAborted();
  const file = await open(path,"r");
  try {
    const info = await file.stat();
    if (!info.isFile() || info.size > IMAGE_BYTE_LIMIT) throw new ImageValidationError("invalid_size", "Local image must be a file of at most 20 MiB.");
    const bytes = Buffer.alloc(info.size+1);let length=0;
    while (length<bytes.length) {
      signal.throwIfAborted();
      const part=await file.read(bytes,length,bytes.length-length,null);
      if (!part.bytesRead) break;
      charge(part.bytesRead,budget);length+=part.bytesRead;
    }
    if (length>info.size) throw new ImageValidationError("changed_image", "Local image changed while reading. Retry.");
    return await validateImageBytes(bytes.subarray(0,length),undefined,signal);
  } finally {await file.close();}
}

export async function mapImages<T,R>(inputs: T[], operation: (input:T,index:number)=>Promise<R>): Promise<R[]> {
  const output = new Array<R>(inputs.length);let next=0;
  await Promise.all(Array.from({length:Math.min(3,inputs.length)},async()=>{
    while (next<inputs.length) {const index=next++;output[index]=await operation(inputs[index],index);}
  }));
  return output;
}