Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/autopsy/images.ts

Raw
import { getImageDimensions } from "@earendil-works/pi-tui";

const MAX_IMAGE_BYTES = 4 * 1024 * 1024;
const MAX_IMAGE_PIXELS = 16 * 1024 * 1024;
const MAX_IMAGE_SIDE = 16_384;
const IMAGE_TYPES = new Set([
	"image/png",
	"image/jpeg",
	"image/gif",
	"image/webp",
]);

type ImageResponse = {
	status: number;
	body: Buffer | string;
	contentType: string;
};

export function sessionImage(entry: unknown, index: number): ImageResponse {
	const fail = (status: number, body: string): ImageResponse => ({
		status,
		body,
		contentType: "text/plain; charset=utf-8",
	});
	if (
		!entry ||
		typeof entry !== "object" ||
		!Number.isSafeInteger(index) ||
		index < 0
	)
		return fail(404, "Image not found");
	const source = entry as {
		message?: { content?: unknown };
		content?: unknown;
	};
	const content = source.message?.content ?? source.content;
	const image = Array.isArray(content)
		? (content[index] as unknown)
		: undefined;
	if (
		!image ||
		typeof image !== "object" ||
		!("type" in image) ||
		image.type !== "image"
	)
		return fail(404, "Image not found");
	const block = image as { data?: unknown; mimeType?: unknown };
	if (typeof block.mimeType !== "string" || !IMAGE_TYPES.has(block.mimeType))
		return fail(
			415,
			"Unsupported image type; previews support PNG, JPEG, GIF, and WebP",
		);
	if (typeof block.data !== "string" || !block.data.length)
		return fail(400, "Invalid image data");
	if (block.data.length > 4 * Math.ceil(MAX_IMAGE_BYTES / 3))
		return fail(413, "Image exceeds 4 MiB preview limit");
	const body = Buffer.from(block.data, "base64");
	if (body.length > MAX_IMAGE_BYTES)
		return fail(413, "Image exceeds 4 MiB preview limit");
	if (body.toString("base64") !== block.data)
		return fail(400, "Invalid base64 image data");
	const dimensions = getImageDimensions(block.data, block.mimeType);
	if (!dimensions || dimensions.widthPx <= 0 || dimensions.heightPx <= 0)
		return fail(400, "Invalid image header or dimensions");
	if (
		dimensions.widthPx > MAX_IMAGE_SIDE ||
		dimensions.heightPx > MAX_IMAGE_SIDE ||
		dimensions.widthPx * dimensions.heightPx > MAX_IMAGE_PIXELS
	)
		return fail(
			413,
			"Image exceeds 16 Mi-pixel or 16384-pixel side preview limit",
		);
	return { status: 200, body, contentType: block.mimeType };
}