forked from phenom/healer-man
42 lines
2.6 KiB
JavaScript
42 lines
2.6 KiB
JavaScript
import assert from "node:assert/strict";
|
|
import { createHash } from "node:crypto";
|
|
import sharp from "sharp";
|
|
|
|
const digest = bytes => createHash("sha256").update(bytes).digest("hex");
|
|
const validHash = value => typeof value === "string" && /^[a-f\d]{64}$/u.test(value);
|
|
|
|
/** Verifies an exact native atlas island, rather than exempting a resized image. */
|
|
export async function verifySourcePixelCrop(metadata, sourcePng, canonicalCropPng, shipped) {
|
|
assert.equal(metadata?.version, 1, "Unsupported source crop proof.");
|
|
assert.ok(typeof metadata.policyId === "string" && metadata.policyId.length > 0);
|
|
assert.ok(typeof metadata.sourceImageName === "string" && !/[\\/]/u.test(metadata.sourceImageName));
|
|
for (const key of ["sourcePreparedPngSha256", "croppedPngSha256", "croppedRgbaSha256"]) {
|
|
assert.ok(validHash(metadata[key]), `Invalid ${key}.`);
|
|
}
|
|
assert.equal(digest(sourcePng), metadata.sourcePreparedPngSha256, "Native atlas PNG changed.");
|
|
assert.equal(digest(canonicalCropPng), metadata.croppedPngSha256, "Canonical crop PNG changed.");
|
|
const source = await sharp(sourcePng).metadata();
|
|
assert.equal(source.width, metadata.sourceWidth);
|
|
assert.equal(source.height, metadata.sourceHeight);
|
|
const rect = metadata.rect;
|
|
assert.ok(rect && [rect.left, rect.top, rect.width, rect.height].every(Number.isInteger));
|
|
assert.ok(rect.left >= 0 && rect.top >= 0 && rect.width > 0 && rect.height > 0
|
|
&& rect.left + rect.width <= source.width && rect.top + rect.height <= source.height,
|
|
"Source crop exceeds its verified native atlas.");
|
|
const crop = await sharp(canonicalCropPng).metadata();
|
|
assert.equal(crop.width, rect.width, "Canonical crop was resized.");
|
|
assert.equal(crop.height, rect.height, "Canonical crop was resized.");
|
|
assert.equal(shipped.width, rect.width, "Shipped crop was resized.");
|
|
assert.equal(shipped.height, rect.height, "Shipped crop was resized.");
|
|
if (shipped.levelCount !== undefined) {
|
|
assert.equal(shipped.levelCount, Math.floor(Math.log2(Math.max(rect.width, rect.height))) + 1,
|
|
"Shipped crop lost its full native island mip chain.");
|
|
}
|
|
const sourcePixels = await sharp(sourcePng).extract(rect).ensureAlpha().raw().toBuffer();
|
|
const cropPixels = await sharp(canonicalCropPng).ensureAlpha().raw().toBuffer();
|
|
assert.equal(digest(sourcePixels), metadata.croppedRgbaSha256, "Native crop pixel proof changed.");
|
|
assert.deepEqual(cropPixels, sourcePixels, "Derived crop changed native RGBA pixels.");
|
|
return { ...metadata, status: "verified-exact-source-pixel-crop", canonicalPixelsByteIdentical: true,
|
|
shippedDimensionsPreserved: true, compressionPixelsRequireSeparateDecode: true };
|
|
}
|