image-processor-unavailable.test.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { describe, expect, it, vi } from "vitest";
  2. vi.mock("../src/utils/photon.ts", () => ({
  3. loadPhoton: vi.fn(async () => null),
  4. }));
  5. import {
  6. ImageProcessorUnavailableError,
  7. resizeImageInProcess,
  8. } from "../src/utils/image-resize-core.ts";
  9. function pngHeader(width: number, height: number, totalBytes = 24): Buffer {
  10. const bytes = Buffer.alloc(totalBytes);
  11. Buffer.from("89504e470d0a1a0a", "hex").copy(bytes);
  12. bytes.writeUInt32BE(13, 8);
  13. bytes.write("IHDR", 12, "ascii");
  14. bytes.writeUInt32BE(width, 16);
  15. bytes.writeUInt32BE(height, 20);
  16. return bytes;
  17. }
  18. describe("resizeImageInProcess without Photon", () => {
  19. it.each([
  20. ["PNG", "image/png", pngHeader(20, 10)],
  21. [
  22. "JPEG",
  23. "image/jpeg",
  24. Buffer.from([0xff, 0xd8, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x00, 0x0a, 0x00, 0x14]),
  25. ],
  26. ["GIF", "image/gif", Buffer.from("47494638396114000a00", "hex")],
  27. [
  28. "WebP",
  29. "image/webp",
  30. Buffer.from("524946461600000057454250565038580000000000000000130000090000", "hex"),
  31. ],
  32. ])("returns an already-safe %s without an image processor", async (_label, mimeType, bytes) => {
  33. const result = await resizeImageInProcess(bytes, mimeType);
  34. expect(result).toEqual({
  35. data: bytes.toString("base64"),
  36. mimeType,
  37. originalWidth: 20,
  38. originalHeight: 10,
  39. width: 20,
  40. height: 10,
  41. wasResized: false,
  42. });
  43. });
  44. it("still reports an unavailable processor when the image exceeds dimension limits", async () => {
  45. await expect(resizeImageInProcess(pngHeader(2001, 1200), "image/png")).rejects.toBeInstanceOf(
  46. ImageProcessorUnavailableError,
  47. );
  48. });
  49. it("still reports an unavailable processor when the encoded image exceeds the size limit", async () => {
  50. await expect(
  51. resizeImageInProcess(pngHeader(20, 10), "image/png", { maxBytes: 31 }),
  52. ).rejects.toBeInstanceOf(ImageProcessorUnavailableError);
  53. });
  54. it("still reports an unavailable processor when dimensions cannot be verified", async () => {
  55. await expect(
  56. resizeImageInProcess(Buffer.from("not-an-image"), "image/png"),
  57. ).rejects.toBeInstanceOf(ImageProcessorUnavailableError);
  58. });
  59. it("does not treat a truncated JPEG marker sequence as a safe image", async () => {
  60. const truncated = Buffer.from([0xff, 0xd8, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xc0]);
  61. await expect(resizeImageInProcess(truncated, "image/jpeg")).rejects.toBeInstanceOf(
  62. ImageProcessorUnavailableError,
  63. );
  64. });
  65. });