import { createHash } from "node:crypto"; import { open, realpath } from "node:fs/promises"; import { constants } from "node:fs"; import { resolve, sep } from "node:path"; import { Injectable } from "@nestjs/common"; import { EstimatePhoto } from "./price-estimation.types"; @Injectable() export class EstimateImages { async read( photo: EstimatePhoto, ): Promise<{ buffer: Buffer; mime: string; sha256: string }> { try { const root = await realpath(resolve("files")); const path = await realpath(resolve(photo.path)); if (!path.startsWith(root + sep)) throw new Error("UNAVAILABLE_IMAGE"); const handle = await open( path, constants.O_RDONLY | constants.O_NOFOLLOW, ); try { const info = await handle.stat(); if (!info.isFile() || info.size < 12 || info.size > 10 * 1024 * 1024) throw new Error("UNAVAILABLE_IMAGE"); const buffer = Buffer.alloc(info.size); let offset = 0; while (offset < buffer.length) { const { bytesRead } = await handle.read( buffer, offset, buffer.length - offset, offset, ); if (!bytesRead) throw new Error("UNAVAILABLE_IMAGE"); offset += bytesRead; } if ((await handle.stat()).size !== buffer.length) throw new Error("UNAVAILABLE_IMAGE"); const mime = buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff ? "image/jpeg" : buffer .subarray(0, 8) .equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) ? "image/png" : buffer.toString("ascii", 0, 4) === "RIFF" && buffer.toString("ascii", 8, 12) === "WEBP" ? "image/webp" : null; if (!mime) throw new Error("UNAVAILABLE_IMAGE"); const sha256 = createHash("sha256").update(buffer).digest("hex"); if (photo.sha256 && photo.sha256 !== sha256) throw new Error("IMAGE_CHANGED"); return { buffer, mime, sha256 }; } finally { await handle.close(); } } catch (error) { if (error instanceof Error && error.message === "IMAGE_CHANGED") throw error; throw new Error("UNAVAILABLE_IMAGE"); } } }