Files
clean-architecture-frontend…/src/adapters/browser-transfer/image-cdn/image-header-metadata.ts
T
DongHyeonkaandClaude Opus 5.5 834308c29b perf(browser-transfer): remove guards that earlier checks already make unreachable (Q-B)
- image-header-metadata: `=== undefined` / `?? 0` / `?? null` guards on bytes
  and boxes whose index was bounds-checked a few lines earlier (PNG IHDR,
  JPEG marker, WebP VP8X/VP8L, AVIF ftyp/meta/iprp/ipma, ascii,
  readUint24LittleEndian). A differential fuzz of the old and new parser over
  720k valid and mutated PNG/JPEG/WebP/AVIF inputs found no difference.
- incremental-sha256: `?? 0` on in-range Uint32Array reads and `>>> 0` on
  Uint32Array stores, which already reduce modulo 2^32. Checked against
  node:crypto for 0..1 MiB inputs, one-shot and streamed.
- p256 verifier: the alphabet index can't be negative after the base64url
  pattern check, and the decoded signature is already an owned, exactly sized
  buffer, so it is no longer copied again.
- browser-image-probe: once the bitmap matches the header dimensions, which
  are positive and inside the decode budget, the repeated positivity and
  budget checks on the bitmap cannot fail.

file-transfer reference runtime: 54894 -> 54754 gzip bytes. Other reference
runtimes unchanged.

Verified: check:architecture, check:types:app, check:types:test, lint,
test:unit, test:component, check:adapter-inventory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 14:49:19 +09:00

694 lines
19 KiB
TypeScript

import type { ImageRasterMediaType } from "../../../application/ports/browser-transfer/image-cdn.ts";
export type StaticImageHeaderMetadata = Readonly<{
width: number;
height: number;
}>;
/**
* Parses only the deliberately supported static-image subset. Unknown,
* ambiguous, animated and structurally malformed containers fail closed
* before a native decoder can allocate an output surface.
*/
export function parseStaticImageHeaderMetadata(
bytes: Uint8Array,
mediaType: ImageRasterMediaType,
): StaticImageHeaderMetadata | null {
switch (mediaType) {
case "image/avif":
return parseAvif(bytes);
case "image/jpeg":
return parseJpeg(bytes);
case "image/png":
return parsePng(bytes);
case "image/webp":
return parseWebp(bytes);
}
}
function parsePng(
bytes: Uint8Array,
): StaticImageHeaderMetadata | null {
const signature = [
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
];
if (
bytes.byteLength < 33 ||
!signature.every((value, index) => bytes[index] === value)
) {
return null;
}
const view = dataView(bytes);
let offset = 8;
let dimensions: StaticImageHeaderMetadata | null = null;
let chunkIndex = 0;
let ended = false;
let imageDataSeen = false;
while (offset < bytes.byteLength) {
if (offset + 12 > bytes.byteLength) return null;
const length = view.getUint32(offset);
const type = ascii(bytes, offset + 4, offset + 8);
const payloadStart = offset + 8;
const payloadEnd = payloadStart + length;
const chunkEnd = payloadEnd + 4;
if (
!Number.isSafeInteger(chunkEnd) ||
chunkEnd > bytes.byteLength
) {
return null;
}
if (chunkIndex === 0 && (type !== "IHDR" || length !== 13)) {
return null;
}
if (type === "IHDR") {
if (dimensions || length !== 13) return null;
const width = view.getUint32(payloadStart);
const height = view.getUint32(payloadStart + 4);
dimensions = validDimensions(width, height);
const bitDepth = bytes[payloadStart + 8];
const colorType = bytes[payloadStart + 9];
const compression = bytes[payloadStart + 10];
const filter = bytes[payloadStart + 11];
const interlace = bytes[payloadStart + 12];
if (
!dimensions ||
!validPngColorDepth(colorType, bitDepth) ||
compression !== 0 ||
filter !== 0 ||
(interlace !== 0 && interlace !== 1)
) {
return null;
}
}
if (type === "acTL" || type === "fcTL" || type === "fdAT") {
return null;
}
if (type === "IDAT") imageDataSeen = true;
if (type === "IEND") {
if (
length !== 0 ||
!imageDataSeen ||
chunkEnd !== bytes.byteLength
) {
return null;
}
ended = true;
}
offset = chunkEnd;
chunkIndex += 1;
if (ended) break;
}
return ended && dimensions ? dimensions : null;
}
function validPngColorDepth(
colorType: number,
bitDepth: number,
): boolean {
const supportedDepths: Readonly<Record<number, readonly number[]>> =
{
0: [1, 2, 4, 8, 16],
2: [8, 16],
3: [1, 2, 4, 8],
4: [8, 16],
6: [8, 16],
};
return supportedDepths[colorType]?.includes(bitDepth) ?? false;
}
function parseJpeg(
bytes: Uint8Array,
): StaticImageHeaderMetadata | null {
if (
bytes.byteLength < 4 ||
bytes[0] !== 0xff ||
bytes[1] !== 0xd8
) {
return null;
}
const supportedStartOfFrame = new Set([0xc0, 0xc1, 0xc2]);
const unsupportedStartOfFrame = new Set([
0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf,
]);
const view = dataView(bytes);
let dimensions: StaticImageHeaderMetadata | null = null;
let offset = 2;
while (offset < bytes.byteLength) {
if (bytes[offset] !== 0xff) return null;
while (offset < bytes.byteLength && bytes[offset] === 0xff) {
offset += 1;
}
if (offset >= bytes.byteLength) return null;
const marker = bytes[offset];
offset += 1;
if (marker === 0x00) return null;
if (marker === 0xd9) return null;
if (marker === 0xda) return dimensions;
if (
marker === 0xd8 ||
marker === 0x01 ||
(marker >= 0xd0 && marker <= 0xd7)
) {
continue;
}
if (offset + 2 > bytes.byteLength) return null;
const segmentLength = view.getUint16(offset);
if (segmentLength < 2) return null;
const segmentEnd = offset + segmentLength;
if (segmentEnd > bytes.byteLength) return null;
if (unsupportedStartOfFrame.has(marker)) return null;
if (supportedStartOfFrame.has(marker)) {
if (dimensions || segmentLength < 8) return null;
const precision = bytes[offset + 2];
const height = view.getUint16(offset + 3);
const width = view.getUint16(offset + 5);
const componentCount = bytes[offset + 7];
dimensions = validDimensions(width, height);
if (
!dimensions ||
precision !== 8 ||
(componentCount !== 1 && componentCount !== 3) ||
segmentLength !== 8 + componentCount * 3
) {
return null;
}
}
offset = segmentEnd;
}
return null;
}
function parseWebp(
bytes: Uint8Array,
): StaticImageHeaderMetadata | null {
if (
bytes.byteLength < 20 ||
ascii(bytes, 0, 4) !== "RIFF" ||
ascii(bytes, 8, 12) !== "WEBP"
) {
return null;
}
const view = dataView(bytes);
const riffLength = view.getUint32(4, true) + 8;
if (riffLength !== bytes.byteLength) return null;
let offset = 12;
let dimensions: StaticImageHeaderMetadata | null = null;
let imagePayloadCount = 0;
let extendedHeaderSeen = false;
let chunkIndex = 0;
while (offset < bytes.byteLength) {
if (offset + 8 > bytes.byteLength) return null;
const type = ascii(bytes, offset, offset + 4);
const length = view.getUint32(offset + 4, true);
const payloadStart = offset + 8;
const payloadEnd = payloadStart + length;
const chunkEnd = payloadEnd + (length % 2);
if (
!Number.isSafeInteger(chunkEnd) ||
chunkEnd > bytes.byteLength
) {
return null;
}
if (
length % 2 === 1 &&
bytes[payloadEnd] !== 0
) {
return null;
}
if (type === "ANIM" || type === "ANMF") return null;
let candidate: StaticImageHeaderMetadata | null = null;
if (type === "VP8X") {
if (
chunkIndex !== 0 ||
extendedHeaderSeen ||
length !== 10 ||
(bytes[payloadStart] & 0xc3) !== 0
) {
return null;
}
extendedHeaderSeen = true;
candidate = validDimensions(
readUint24LittleEndian(bytes, payloadStart + 4) + 1,
readUint24LittleEndian(bytes, payloadStart + 7) + 1,
);
} else if (type === "VP8 ") {
imagePayloadCount += 1;
if (
length < 10 ||
bytes[payloadStart + 3] !== 0x9d ||
bytes[payloadStart + 4] !== 0x01 ||
bytes[payloadStart + 5] !== 0x2a
) {
return null;
}
candidate = validDimensions(
view.getUint16(payloadStart + 6, true) & 0x3fff,
view.getUint16(payloadStart + 8, true) & 0x3fff,
);
} else if (type === "VP8L") {
imagePayloadCount += 1;
if (length < 5 || bytes[payloadStart] !== 0x2f) {
return null;
}
const byte1 = bytes[payloadStart + 1];
const byte2 = bytes[payloadStart + 2];
const byte3 = bytes[payloadStart + 3];
const byte4 = bytes[payloadStart + 4];
if ((byte4 & 0xe0) !== 0) return null;
candidate = validDimensions(
1 + byte1 + ((byte2 & 0x3f) << 8),
1 +
((byte2 & 0xc0) >> 6) +
(byte3 << 2) +
((byte4 & 0x0f) << 10),
);
}
if (candidate) {
if (
dimensions &&
(dimensions.width !== candidate.width ||
dimensions.height !== candidate.height)
) {
return null;
}
dimensions = candidate;
}
offset = chunkEnd;
chunkIndex += 1;
}
return offset === bytes.byteLength &&
dimensions &&
imagePayloadCount === 1
? dimensions
: null;
}
function parseAvif(
bytes: Uint8Array,
): StaticImageHeaderMetadata | null {
if (bytes.byteLength < 24) return null;
const boxes = parseBoxes(bytes, 0, bytes.byteLength);
if (!boxes || boxes.length < 2 || boxes[0]?.type !== "ftyp") {
return null;
}
const fileType = boxes[0];
const fileTypeLength = fileType.payloadEnd - fileType.payloadStart;
if (fileTypeLength < 8 || (fileTypeLength - 8) % 4 !== 0) {
return null;
}
const brands: string[] = [
ascii(bytes, fileType.payloadStart, fileType.payloadStart + 4),
];
for (
let offset = fileType.payloadStart + 8;
offset + 4 <= fileType.payloadEnd;
offset += 4
) {
brands.push(ascii(bytes, offset, offset + 4));
}
if (!brands.includes("avif") || brands.includes("avis")) {
return null;
}
if (
boxes.some((box) => box.type === "moov") ||
!boxes.some(
(box) =>
box.type === "mdat" &&
box.payloadEnd > box.payloadStart,
)
) {
return null;
}
const metadataBoxes = boxes.filter((box) => box.type === "meta");
const metadataBox = metadataBoxes[0];
if (
metadataBoxes.length !== 1 ||
metadataBox.payloadStart + 4 > metadataBox.payloadEnd ||
!zeroFullBoxFlags(bytes, metadataBox.payloadStart)
) {
return null;
}
const metadataChildren = parseBoxes(
bytes,
metadataBox.payloadStart + 4,
metadataBox.payloadEnd,
);
if (!metadataChildren) return null;
const state: AvifMetadataState = {
associations: new Map(),
itemTypes: new Map(),
primaryItemId: null,
properties: new Map(),
propertyCount: 0,
};
let itemInfoSeen = false;
let itemPropertiesSeen = false;
for (const box of metadataChildren) {
if (box.type === "pitm") {
const primaryItemId = parseAvifPrimaryItem(bytes, box);
if (
primaryItemId === null ||
state.primaryItemId !== null
) {
return null;
}
state.primaryItemId = primaryItemId;
} else if (box.type === "iinf") {
if (itemInfoSeen || !parseAvifItemInfo(bytes, box, state)) {
return null;
}
itemInfoSeen = true;
} else if (box.type === "iprp") {
if (
itemPropertiesSeen ||
!parseAvifItemProperties(bytes, box, state)
) {
return null;
}
itemPropertiesSeen = true;
}
}
const primaryItemId = state.primaryItemId;
if (
primaryItemId === null ||
state.itemTypes.get(primaryItemId) !== "av01"
) {
return null;
}
const associatedProperties = state.associations.get(primaryItemId);
if (!associatedProperties) return null;
const associatedExtents: StaticImageHeaderMetadata[] = [];
const seenProperties = new Set<number>();
for (const propertyIndex of associatedProperties) {
if (
propertyIndex < 1 ||
propertyIndex > state.propertyCount ||
seenProperties.has(propertyIndex)
) {
return null;
}
seenProperties.add(propertyIndex);
const dimensions = state.properties.get(propertyIndex);
if (dimensions) associatedExtents.push(dimensions);
}
return associatedExtents.length === 1 ? associatedExtents[0] : null;
}
type IsoBox = Readonly<{
type: string;
payloadStart: number;
payloadEnd: number;
}>;
type AvifMetadataState = {
primaryItemId: number | null;
itemTypes: Map<number, string>;
properties: Map<number, StaticImageHeaderMetadata>;
associations: Map<number, readonly number[]>;
propertyCount: number;
};
function parseAvifPrimaryItem(
bytes: Uint8Array,
box: IsoBox,
): number | null {
const version = bytes[box.payloadStart];
const view = dataView(bytes);
if (!zeroFullBoxFlags(bytes, box.payloadStart)) return null;
if (
version === 0 &&
box.payloadEnd - box.payloadStart === 6
) {
return view.getUint16(box.payloadStart + 4);
}
if (
version === 1 &&
box.payloadEnd - box.payloadStart === 8
) {
return view.getUint32(box.payloadStart + 4);
}
return null;
}
function parseAvifItemInfo(
bytes: Uint8Array,
box: IsoBox,
state: AvifMetadataState,
): boolean {
const start = box.payloadStart;
const end = box.payloadEnd;
const version = bytes[start];
if (
(version !== 0 && version !== 1) ||
!zeroFullBoxFlags(bytes, start)
) {
return false;
}
const entryBytes = version === 0 ? 2 : 4;
if (start + 4 + entryBytes > end) return false;
const view = dataView(bytes);
const declaredEntries =
entryBytes === 2
? view.getUint16(start + 4)
: view.getUint32(start + 4);
const entriesStart = start + 4 + entryBytes;
const boxes = parseBoxes(bytes, entriesStart, end);
if (
!boxes ||
boxes.length !== declaredEntries ||
boxes.some((entry) => entry.type !== "infe")
) {
return false;
}
for (const entry of boxes) {
const itemVersion = bytes[entry.payloadStart];
if (!zeroFullBoxFlags(bytes, entry.payloadStart)) return false;
let itemId: number;
let itemTypeOffset: number;
if (itemVersion === 2) {
if (entry.payloadStart + 12 > entry.payloadEnd) return false;
itemId = view.getUint16(entry.payloadStart + 4);
itemTypeOffset = entry.payloadStart + 8;
} else if (itemVersion === 3) {
if (entry.payloadStart + 14 > entry.payloadEnd) return false;
itemId = view.getUint32(entry.payloadStart + 4);
itemTypeOffset = entry.payloadStart + 10;
} else {
return false;
}
const itemType = ascii(
bytes,
itemTypeOffset,
itemTypeOffset + 4,
);
if (itemType === "grid" || itemType === "iovl") {
return false;
}
if (itemId === 0 || state.itemTypes.has(itemId)) return false;
state.itemTypes.set(itemId, itemType);
}
return true;
}
function parseAvifItemProperties(
bytes: Uint8Array,
box: IsoBox,
state: AvifMetadataState,
): boolean {
const boxes = parseBoxes(
bytes,
box.payloadStart,
box.payloadEnd,
);
if (!boxes) return false;
const propertyContainers = boxes.filter(
(child) => child.type === "ipco",
);
const associationBoxes = boxes.filter(
(child) => child.type === "ipma",
);
const propertyContainer = propertyContainers[0];
if (propertyContainers.length !== 1 || associationBoxes.length < 1) {
return false;
}
const properties = parseBoxes(
bytes,
propertyContainer.payloadStart,
propertyContainer.payloadEnd,
);
if (!properties) return false;
state.propertyCount = properties.length;
for (const [offset, property] of properties.entries()) {
if (property.type !== "ispe") continue;
if (
property.payloadEnd - property.payloadStart !== 12 ||
bytes[property.payloadStart] !== 0 ||
bytes[property.payloadStart + 1] !== 0 ||
bytes[property.payloadStart + 2] !== 0 ||
bytes[property.payloadStart + 3] !== 0
) {
return false;
}
const view = dataView(bytes);
const dimensions = validDimensions(
view.getUint32(property.payloadStart + 4),
view.getUint32(property.payloadStart + 8),
);
if (!dimensions) return false;
state.properties.set(offset + 1, dimensions);
}
return associationBoxes.every((association) =>
parseAvifPropertyAssociations(bytes, association, state)
);
}
function parseAvifPropertyAssociations(
bytes: Uint8Array,
box: IsoBox,
state: AvifMetadataState,
): boolean {
const start = box.payloadStart;
const end = box.payloadEnd;
if (start + 8 > end) return false;
const version = bytes[start];
if (version !== 0 && version !== 1) return false;
const flags =
(bytes[start + 1] << 16) | (bytes[start + 2] << 8) | bytes[start + 3];
if ((flags & ~1) !== 0) return false;
const wideAssociation = (flags & 1) === 1;
const view = dataView(bytes);
const entryCount = view.getUint32(start + 4);
let offset = start + 8;
for (let entry = 0; entry < entryCount; entry += 1) {
const itemIdBytes = version === 0 ? 2 : 4;
if (offset + itemIdBytes + 1 > end) return false;
const itemId =
itemIdBytes === 2
? view.getUint16(offset)
: view.getUint32(offset);
offset += itemIdBytes;
const associationCount = bytes[offset];
offset += 1;
const propertyIndices: number[] = [];
for (
let association = 0;
association < associationCount;
association += 1
) {
const associationBytes = wideAssociation ? 2 : 1;
if (offset + associationBytes > end) return false;
const encoded =
associationBytes === 2 ? view.getUint16(offset) : bytes[offset];
const propertyIndex =
encoded & (wideAssociation ? 0x7fff : 0x7f);
offset += associationBytes;
if (propertyIndex !== 0) propertyIndices.push(propertyIndex);
}
if (itemId === 0 || state.associations.has(itemId)) {
return false;
}
state.associations.set(itemId, propertyIndices);
}
return offset === end;
}
function parseBoxes(
bytes: Uint8Array,
start: number,
end: number,
): readonly IsoBox[] | null {
if (
!Number.isSafeInteger(start) ||
!Number.isSafeInteger(end) ||
start < 0 ||
end > bytes.byteLength ||
start > end
) {
return null;
}
const boxes: IsoBox[] = [];
const view = dataView(bytes);
let offset = start;
while (offset < end) {
if (offset + 8 > end) return null;
const shortSize = view.getUint32(offset);
const type = ascii(bytes, offset + 4, offset + 8);
let boxSize = shortSize;
let headerSize = 8;
if (shortSize === 0) return null;
if (shortSize === 1) {
if (offset + 16 > end) return null;
const longSize = view.getBigUint64(offset + 8);
if (longSize > BigInt(Number.MAX_SAFE_INTEGER)) return null;
boxSize = Number(longSize);
headerSize = 16;
}
if (boxSize < headerSize || offset + boxSize > end) {
return null;
}
boxes.push(
Object.freeze({
type,
payloadStart: offset + headerSize,
payloadEnd: offset + boxSize,
}),
);
offset += boxSize;
}
return offset === end ? boxes : null;
}
function zeroFullBoxFlags(
bytes: Uint8Array,
offset: number,
): boolean {
return (
bytes[offset + 1] === 0 &&
bytes[offset + 2] === 0 &&
bytes[offset + 3] === 0
);
}
function validDimensions(
width: number,
height: number,
): StaticImageHeaderMetadata | null {
return Number.isSafeInteger(width) &&
Number.isSafeInteger(height) &&
width > 0 &&
height > 0
? Object.freeze({ width, height })
: null;
}
/** Callers pass an offset whose three bytes lie inside a checked chunk. */
function readUint24LittleEndian(
bytes: Uint8Array,
offset: number,
): number {
return (
bytes[offset] | (bytes[offset + 1] << 8) | (bytes[offset + 2] << 16)
);
}
/** Callers pass a range that the surrounding length checks keep in bounds. */
function ascii(
bytes: Uint8Array,
start: number,
end: number,
): string {
return String.fromCharCode(...bytes.subarray(start, end));
}
function dataView(bytes: Uint8Array): DataView {
return new DataView(
bytes.buffer,
bytes.byteOffset,
bytes.byteLength,
);
}