forked from mtusi2026/mtusi2026lab4
388 lines
10 KiB
TypeScript
388 lines
10 KiB
TypeScript
import { crc32 } from 'node:zlib';
|
|
|
|
export type ImageHeader = {
|
|
contentType: 'image/png' | 'image/jpeg';
|
|
width: number;
|
|
height: number;
|
|
};
|
|
|
|
export class ImageRejectedError extends Error {
|
|
constructor(
|
|
readonly reason: 'unsupported_media_type' | 'too_many_pixels',
|
|
message: string,
|
|
) {
|
|
super(message);
|
|
this.name = 'ImageRejectedError';
|
|
}
|
|
}
|
|
|
|
const PNG_SIGNATURE = Buffer.from([
|
|
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
|
|
]);
|
|
const PNG_MAX_DIMENSION = 2 ** 31 - 1;
|
|
const PNG_BIT_DEPTHS: Record<number, readonly number[]> = {
|
|
0: [1, 2, 4, 8, 16],
|
|
2: [8, 16],
|
|
3: [1, 2, 4, 8],
|
|
4: [8, 16],
|
|
6: [8, 16],
|
|
};
|
|
const SOF_MARKERS = new Set([
|
|
0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce,
|
|
0xcf,
|
|
]);
|
|
|
|
type State =
|
|
| 'start'
|
|
// PNG
|
|
| 'png_chunk_head'
|
|
| 'png_ihdr'
|
|
| 'png_skip'
|
|
| 'png_crc'
|
|
| 'png_done'
|
|
// JPEG
|
|
| 'jpeg_marker'
|
|
| 'jpeg_code'
|
|
| 'jpeg_length'
|
|
| 'jpeg_sof'
|
|
| 'jpeg_skip'
|
|
| 'jpeg_entropy'
|
|
| 'jpeg_entropy_ff'
|
|
| 'jpeg_trailer';
|
|
|
|
function unsupported(message: string): ImageRejectedError {
|
|
return new ImageRejectedError('unsupported_media_type', message);
|
|
}
|
|
|
|
/**
|
|
* Streaming structural validator for PNG and JPEG. It never buffers the body:
|
|
* only fixed-size fields (chunk headers, IHDR, SOF) are accumulated, and
|
|
* nothing is decompressed. It is the early gate (type, dimensions, pixel limit
|
|
* before anything is stored), not proof of a valid image: compressed pixel
|
|
* data is checked by ImageDecoder.
|
|
*/
|
|
export class ImageInspector {
|
|
private state: State = 'start';
|
|
private imageHeader: ImageHeader | undefined;
|
|
|
|
// Accumulator for fixed-length fields.
|
|
private field = Buffer.alloc(16);
|
|
private fieldNeed = 0;
|
|
private fieldLength = 0;
|
|
|
|
// Remaining bytes to skip in png_skip / jpeg_skip.
|
|
private skip = 0;
|
|
|
|
// PNG
|
|
private chunkType = '';
|
|
private chunkLength = 0;
|
|
private crc = 0;
|
|
private firstChunk = true;
|
|
private seenIdat = false;
|
|
|
|
// JPEG
|
|
private marker = 0;
|
|
private scans = 0;
|
|
private afterSkip: State = 'jpeg_marker';
|
|
|
|
constructor(private readonly maxPixels: number) {}
|
|
|
|
get header(): ImageHeader | undefined {
|
|
return this.imageHeader;
|
|
}
|
|
|
|
push(chunk: Buffer): void {
|
|
let offset = 0;
|
|
while (offset < chunk.length) offset = this.step(chunk, offset);
|
|
}
|
|
|
|
finish(): ImageHeader {
|
|
const done = this.state === 'png_done' || this.state === 'jpeg_trailer';
|
|
if (!done || this.imageHeader === undefined)
|
|
throw unsupported('Image data is incomplete');
|
|
return this.imageHeader;
|
|
}
|
|
|
|
private collect(need: number): void {
|
|
this.fieldNeed = need;
|
|
this.fieldLength = 0;
|
|
}
|
|
|
|
/** Copies up to fieldNeed bytes; returns new offset and whether complete. */
|
|
private fill(chunk: Buffer, offset: number): [number, boolean] {
|
|
const take = Math.min(
|
|
this.fieldNeed - this.fieldLength,
|
|
chunk.length - offset,
|
|
);
|
|
chunk.copy(this.field, this.fieldLength, offset, offset + take);
|
|
this.fieldLength += take;
|
|
return [offset + take, this.fieldLength === this.fieldNeed];
|
|
}
|
|
|
|
private step(chunk: Buffer, offset: number): number {
|
|
switch (this.state) {
|
|
case 'start':
|
|
return this.stepStart(chunk, offset);
|
|
case 'png_chunk_head':
|
|
case 'png_ihdr':
|
|
case 'png_crc':
|
|
case 'jpeg_length':
|
|
case 'jpeg_sof': {
|
|
const [next, complete] = this.fill(chunk, offset);
|
|
if (complete) this.fieldDone();
|
|
return next;
|
|
}
|
|
case 'png_skip':
|
|
case 'jpeg_skip': {
|
|
const take = Math.min(this.skip, chunk.length - offset);
|
|
if (this.state === 'png_skip')
|
|
this.crc = crc32(
|
|
chunk.subarray(offset, offset + take),
|
|
this.crc,
|
|
);
|
|
this.skip -= take;
|
|
if (this.skip === 0) this.skipDone();
|
|
return offset + take;
|
|
}
|
|
case 'png_done':
|
|
throw unsupported('Data after the PNG end chunk');
|
|
case 'jpeg_marker':
|
|
if (chunk[offset] !== 0xff)
|
|
throw unsupported('Unexpected byte between JPEG segments');
|
|
this.state = 'jpeg_code';
|
|
return offset + 1;
|
|
case 'jpeg_code':
|
|
this.onMarkerCode(chunk[offset]);
|
|
return offset + 1;
|
|
case 'jpeg_entropy': {
|
|
const next = chunk.indexOf(0xff, offset);
|
|
if (next === -1) return chunk.length;
|
|
this.state = 'jpeg_entropy_ff';
|
|
return next + 1;
|
|
}
|
|
case 'jpeg_entropy_ff': {
|
|
const byte = chunk[offset];
|
|
if (byte === 0xff) return offset + 1;
|
|
if (byte === 0x00 || (byte >= 0xd0 && byte <= 0xd7)) {
|
|
this.state = 'jpeg_entropy';
|
|
return offset + 1;
|
|
}
|
|
this.onMarkerCode(byte);
|
|
return offset + 1;
|
|
}
|
|
case 'jpeg_trailer':
|
|
return chunk.length;
|
|
}
|
|
}
|
|
|
|
private stepStart(chunk: Buffer, offset: number): number {
|
|
// Accumulate until the type is certain: 3 bytes for JPEG, 8 for PNG.
|
|
if (this.fieldLength === 0 && this.fieldNeed === 0) this.collect(8);
|
|
const have = this.fieldLength;
|
|
const take = Math.min(this.fieldNeed - have, chunk.length - offset);
|
|
chunk.copy(this.field, have, offset, offset + take);
|
|
this.fieldLength += take;
|
|
const first = this.field[0];
|
|
if (first === 0xff) {
|
|
if (this.fieldLength >= 3) {
|
|
if (this.field[1] !== 0xd8 || this.field[2] !== 0xff)
|
|
throw unsupported('Not a JPEG file');
|
|
// The third byte opens the next marker.
|
|
this.state = 'jpeg_code';
|
|
this.fieldNeed = 0;
|
|
this.fieldLength = 0;
|
|
return offset + (3 - have);
|
|
}
|
|
return offset + take;
|
|
}
|
|
if (first === PNG_SIGNATURE[0]) {
|
|
for (let index = 0; index < this.fieldLength; index += 1)
|
|
if (this.field[index] !== PNG_SIGNATURE[index])
|
|
throw unsupported('Not a PNG file');
|
|
if (this.fieldLength === 8) {
|
|
this.state = 'png_chunk_head';
|
|
this.collect(8);
|
|
}
|
|
return offset + take;
|
|
}
|
|
throw unsupported('Unsupported image format');
|
|
}
|
|
|
|
private fieldDone(): void {
|
|
switch (this.state) {
|
|
case 'png_chunk_head':
|
|
this.onPngChunkHead();
|
|
return;
|
|
case 'png_ihdr':
|
|
this.crc = crc32(this.field.subarray(0, 13), this.crc);
|
|
this.parseIhdr();
|
|
this.state = 'png_crc';
|
|
this.collect(4);
|
|
return;
|
|
case 'png_crc': {
|
|
const expected = this.field.readUInt32BE(0);
|
|
if (this.crc >>> 0 !== expected)
|
|
throw unsupported('PNG chunk checksum mismatch');
|
|
this.onPngChunkEnd();
|
|
return;
|
|
}
|
|
case 'jpeg_length':
|
|
this.onJpegLength();
|
|
return;
|
|
case 'jpeg_sof':
|
|
this.onJpegSof();
|
|
return;
|
|
default:
|
|
return;
|
|
}
|
|
}
|
|
|
|
private skipDone(): void {
|
|
if (this.state === 'png_skip') {
|
|
this.state = 'png_crc';
|
|
this.collect(4);
|
|
} else {
|
|
this.state = this.afterSkip;
|
|
}
|
|
}
|
|
|
|
// ---- PNG ----
|
|
|
|
private onPngChunkHead(): void {
|
|
const length = this.field.readUInt32BE(0);
|
|
const type = this.field.toString('latin1', 4, 8);
|
|
if (length > PNG_MAX_DIMENSION)
|
|
throw unsupported('PNG chunk is too long');
|
|
if (!/^[A-Za-z]{4}$/u.test(type))
|
|
throw unsupported('PNG chunk type is invalid');
|
|
if (this.firstChunk) {
|
|
if (type !== 'IHDR' || length !== 13)
|
|
throw unsupported('PNG must start with IHDR');
|
|
this.firstChunk = false;
|
|
} else if (type === 'IHDR') {
|
|
throw unsupported('Duplicate PNG IHDR');
|
|
}
|
|
if (type === 'IEND') {
|
|
if (length !== 0 || !this.seenIdat)
|
|
throw unsupported('PNG IEND is invalid');
|
|
}
|
|
if (type === 'IDAT') this.seenIdat = true;
|
|
this.chunkType = type;
|
|
this.chunkLength = length;
|
|
this.crc = crc32(this.field.subarray(4, 8), 0);
|
|
if (type === 'IHDR') {
|
|
this.state = 'png_ihdr';
|
|
this.collect(13);
|
|
} else if (length === 0) {
|
|
this.state = 'png_crc';
|
|
this.collect(4);
|
|
} else {
|
|
this.state = 'png_skip';
|
|
this.skip = length;
|
|
}
|
|
}
|
|
|
|
private parseIhdr(): void {
|
|
const width = this.field.readUInt32BE(0);
|
|
const height = this.field.readUInt32BE(4);
|
|
const bitDepth = this.field[8];
|
|
const colorType = this.field[9];
|
|
if (width < 1 || width > PNG_MAX_DIMENSION)
|
|
throw unsupported('PNG width is invalid');
|
|
if (height < 1 || height > PNG_MAX_DIMENSION)
|
|
throw unsupported('PNG height is invalid');
|
|
if (!PNG_BIT_DEPTHS[colorType]?.includes(bitDepth))
|
|
throw unsupported('PNG color type / bit depth is invalid');
|
|
if (this.field[10] !== 0 || this.field[11] !== 0)
|
|
throw unsupported('PNG compression/filter method is invalid');
|
|
if (this.field[12] > 1)
|
|
throw unsupported('PNG interlace method is invalid');
|
|
this.pendingHeader = { contentType: 'image/png', width, height };
|
|
}
|
|
|
|
private pendingHeader: ImageHeader | undefined;
|
|
|
|
private onPngChunkEnd(): void {
|
|
if (this.chunkType === 'IHDR' && this.pendingHeader) {
|
|
const { width, height } = this.pendingHeader;
|
|
if (width * height > this.maxPixels)
|
|
throw new ImageRejectedError(
|
|
'too_many_pixels',
|
|
'Image has too many pixels',
|
|
);
|
|
this.imageHeader = this.pendingHeader;
|
|
}
|
|
if (this.chunkType === 'IEND') {
|
|
this.state = 'png_done';
|
|
return;
|
|
}
|
|
this.state = 'png_chunk_head';
|
|
this.collect(8);
|
|
}
|
|
|
|
// ---- JPEG ----
|
|
|
|
private onMarkerCode(code: number): void {
|
|
if (code === 0xff) return; // fill byte
|
|
this.marker = code;
|
|
if (code === 0x00 || code === 0xd8)
|
|
throw unsupported('Unexpected JPEG marker');
|
|
if (code === 0x01 || (code >= 0xd0 && code <= 0xd7)) {
|
|
this.state = 'jpeg_marker';
|
|
return;
|
|
}
|
|
if (code === 0xd9) {
|
|
if (this.imageHeader === undefined || this.scans === 0)
|
|
throw unsupported('JPEG ended before image data');
|
|
this.state = 'jpeg_trailer';
|
|
return;
|
|
}
|
|
if (code === 0xda && this.imageHeader === undefined)
|
|
throw unsupported('JPEG scan before frame header');
|
|
this.state = 'jpeg_length';
|
|
this.collect(2);
|
|
}
|
|
|
|
private onJpegLength(): void {
|
|
const length = this.field.readUInt16BE(0);
|
|
if (length < 2) throw unsupported('JPEG segment length is invalid');
|
|
const dataLength = length - 2;
|
|
if (SOF_MARKERS.has(this.marker)) {
|
|
if (this.imageHeader !== undefined || this.pendingHeader)
|
|
throw unsupported('Duplicate JPEG frame header');
|
|
if (dataLength < 6) throw unsupported('JPEG frame header is short');
|
|
this.skip = dataLength - 6;
|
|
this.afterSkip = 'jpeg_marker';
|
|
this.state = 'jpeg_sof';
|
|
this.collect(6);
|
|
return;
|
|
}
|
|
if (this.marker === 0xda) {
|
|
this.scans += 1;
|
|
this.afterSkip = 'jpeg_entropy';
|
|
} else {
|
|
this.afterSkip = 'jpeg_marker';
|
|
}
|
|
if (dataLength === 0) this.state = this.afterSkip;
|
|
else {
|
|
this.skip = dataLength;
|
|
this.state = 'jpeg_skip';
|
|
}
|
|
}
|
|
|
|
private onJpegSof(): void {
|
|
const height = this.field.readUInt16BE(1);
|
|
const width = this.field.readUInt16BE(3);
|
|
if (width === 0 || height === 0 || this.field[5] === 0)
|
|
throw unsupported('JPEG dimensions are invalid');
|
|
if (width * height > this.maxPixels)
|
|
throw new ImageRejectedError(
|
|
'too_many_pixels',
|
|
'Image has too many pixels',
|
|
);
|
|
this.imageHeader = { contentType: 'image/jpeg', width, height };
|
|
if (this.skip === 0) this.state = 'jpeg_marker';
|
|
else this.state = 'jpeg_skip';
|
|
}
|
|
}
|