Files
mtusi2026lab4/app/src/attachments/image/image-decoder.ts
T

73 lines
2.1 KiB
TypeScript

import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import sharp from 'sharp';
import type { AppConfig } from '../../config/app-config.schema.js';
import { MetricsService } from '../../metrics/metrics.service.js';
import { ImageRejectedError } from './image-inspector.js';
// One libvips worker per decode and no operation cache: decodes are one-off,
// and memory must stay predictable under the per-replica limit.
sharp.cache(false);
sharp.concurrency(1);
/**
* Full decode check. ImageInspector only proves the container structure
* (signature, chunk CRCs, markers, dimensions); a PNG with a garbage zlib stream
* or a JPEG without scan data passes it. Decoding every pixel with
* failOn=warning rejects those, including truncated or corrupted entropy data.
* Decodes are bounded by IMAGE_DECODE_MAX_CONCURRENT; callers wait for a slot.
*/
@Injectable()
export class ImageDecoder {
private readonly maxPixels: number;
private readonly maxConcurrent: number;
private active = 0;
private readonly waiting: (() => void)[] = [];
constructor(
config: ConfigService<AppConfig>,
private readonly metrics: MetricsService,
) {
this.maxPixels = config.getOrThrow('MAX_IMAGE_PIXELS');
this.maxConcurrent = config.getOrThrow('IMAGE_DECODE_MAX_CONCURRENT');
}
async verify(data: Buffer): Promise<void> {
await this.acquire();
const started = performance.now();
try {
await sharp(data, {
failOn: 'warning',
sequentialRead: true,
limitInputPixels: this.maxPixels,
}).stats();
} catch {
this.metrics.increment('attachments.decode.rejected');
throw new ImageRejectedError(
'unsupported_media_type',
'Image data cannot be decoded',
);
} finally {
this.metrics.add(
'attachments.decode.ms',
performance.now() - started,
);
this.release();
}
}
private async acquire(): Promise<void> {
if (this.active < this.maxConcurrent) {
this.active += 1;
return;
}
await new Promise<void>((resolve) => this.waiting.push(resolve));
}
private release(): void {
const next = this.waiting.shift();
if (next) next();
else this.active -= 1;
}
}