mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-01 17:03:15 +00:00
fix(media): bound image work before public rendition
Check avatar uploads and raster fallbacks before decoding. Limit compressed bytes, decoded dimensions, GIF frames and the combined TIFF page budget.
This commit is contained in:
@@ -6,6 +6,7 @@ import { CurrentUser } from '../auth-core/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { currentSessionId, decodeSessionClaims } from '../auth-core/jwt-verify';
|
||||
import { MfaExempt } from '../auth-core/mfa-policy.guard';
|
||||
import { boundedRasterHeader, readRasterFile } from '../common/bounded-raster';
|
||||
import { DEMO_ACCOUNT_REFUSAL, DEMO_WRITE_ERROR, isDemoWriteBlocked, refuseForDemoAccount } from '../common/demo-write';
|
||||
import { ManagedForbidden } from '../common/managed';
|
||||
import { RateLimitService } from '../common/rate-limit.service';
|
||||
@@ -46,17 +47,20 @@ import { FileInterceptor } from '@nestjs/platform-express';
|
||||
|
||||
import type { Request, Response } from 'express';
|
||||
import type { Options } from 'multer';
|
||||
import { rm } from 'node:fs/promises';
|
||||
import path from 'path';
|
||||
|
||||
const WINDOW = 15 * 60 * 1000;
|
||||
const ALLOWED_AVATAR_EXTS = ['.jpg', '.jpeg', '.png', '.gif', '.webp'];
|
||||
const ALLOWED_AVATAR_MIME_TYPES = new Set(['image/jpeg', 'image/png', 'image/gif', 'image/webp']);
|
||||
const INVALID_AVATAR_MESSAGE = 'Only image files (jpg, png, gif, webp) are allowed';
|
||||
export const MAX_AVATAR_SIZE = 5 * 1024 * 1024;
|
||||
// Consumed by auth.module.ts's MulterModule factory; the storage engine (spool
|
||||
// destination + UUID filename) comes from the storage upload factory.
|
||||
export const AVATAR_FILE_FILTER: Options['fileFilter'] = (_req, file, cb) => {
|
||||
const ext = path.extname(file.originalname).toLowerCase();
|
||||
if (!file.mimetype.startsWith('image/') || !ALLOWED_AVATAR_EXTS.includes(ext)) {
|
||||
const err: Error & { statusCode?: number } = new Error('Only image files (jpg, png, gif, webp) are allowed');
|
||||
const err: Error & { statusCode?: number } = new Error(INVALID_AVATAR_MESSAGE);
|
||||
err.statusCode = 400;
|
||||
return cb(err);
|
||||
}
|
||||
@@ -225,6 +229,12 @@ export class AuthController {
|
||||
if (!file) {
|
||||
throw new HttpException({ error: 'No image uploaded' }, 400);
|
||||
}
|
||||
const bytes = await readRasterFile(file.path, MAX_AVATAR_SIZE);
|
||||
const header = bytes && boundedRasterHeader(bytes);
|
||||
if (!header || !ALLOWED_AVATAR_MIME_TYPES.has(header.mimeType)) {
|
||||
await rm(file.path, { force: true });
|
||||
throw new HttpException({ error: INVALID_AVATAR_MESSAGE }, 400);
|
||||
}
|
||||
// Commit the spooled upload to its final storage location (atomic
|
||||
// same-volume rename) before the DB row references the final path.
|
||||
await this.storage.put('avatars', file.filename, { tmpPath: file.path });
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import { readImageHeader } from './image-header';
|
||||
|
||||
import { open } from 'node:fs/promises';
|
||||
|
||||
const MAX_EDGE = 16_384;
|
||||
export const MAX_RASTER_PIXELS = 40_000_000;
|
||||
const MAX_RASTER_BYTES = MAX_RASTER_PIXELS * 4;
|
||||
const MAX_TIFF_PAGES = 64;
|
||||
const TIFF_SIZE_TAGS = new Set([256, 257, 258, 262, 277, 322, 323]);
|
||||
const TIFF_UNSUPPORTED_TAGS = new Set([330, 50885]);
|
||||
|
||||
type RasterInfo = { width: number; height: number; mimeType: string };
|
||||
type ReadInteger = (offset: number) => number;
|
||||
|
||||
function fitsRaster(width: number, height: number): boolean {
|
||||
return width > 0 && height > 0 && width <= MAX_EDGE && height <= MAX_EDGE && width * height <= MAX_RASTER_PIXELS;
|
||||
}
|
||||
|
||||
function tiffValue(data: Buffer, short: ReadInteger, long: ReadInteger, entry: number, tag: number): number | null {
|
||||
const type = short(entry + 2);
|
||||
const count = long(entry + 4);
|
||||
if ((type !== 3 && type !== 4) || count < 1 || count > (tag === 258 ? 4 : 1)) return null;
|
||||
const size = type === 3 ? 2 : 4;
|
||||
const offset = count * size <= 4 ? entry + 8 : long(entry + 8);
|
||||
if (offset + count * size > data.length) return null;
|
||||
return type === 3 ? short(offset) : long(offset);
|
||||
}
|
||||
|
||||
function readTiffPage(data: Buffer, short: ReadInteger, long: ReadInteger, directory: number) {
|
||||
if (directory < 8 || directory + 2 > data.length) return null;
|
||||
const end = directory + 2 + short(directory) * 12;
|
||||
if (end + 4 > data.length) return null;
|
||||
const tags = new Map<number, number>();
|
||||
for (let entry = directory + 2; entry < end; entry += 12) {
|
||||
const tag = short(entry);
|
||||
if (TIFF_UNSUPPORTED_TAGS.has(tag)) return null;
|
||||
if (!TIFF_SIZE_TAGS.has(tag)) continue;
|
||||
const value = tiffValue(data, short, long, entry, tag);
|
||||
if (value === null) return null;
|
||||
tags.set(tag, value);
|
||||
}
|
||||
const width = tags.get(256) ?? 0;
|
||||
const height = tags.get(257) ?? 0;
|
||||
if (!fitsRaster(width, height) || tags.get(262) === 32803) return null;
|
||||
const samples = tags.get(277) ?? 1;
|
||||
const bits = tags.get(258) ?? 1;
|
||||
if (samples < 1 || samples > 4 || bits < 1 || bits > 32) return null;
|
||||
const tileWidth = tags.get(322) ?? 0;
|
||||
const tileHeight = tags.get(323) ?? 0;
|
||||
if ((tileWidth || tileHeight) && !fitsRaster(tileWidth, tileHeight)) return null;
|
||||
const bytes = (width * height + tileWidth * tileHeight) * Math.max(4, Math.ceil((samples * bits) / 8));
|
||||
return { width, height, bytes, next: long(end) };
|
||||
}
|
||||
|
||||
function readTiffHeader(data: Buffer): RasterInfo | null {
|
||||
const littleEndian = data.toString('latin1', 0, 2) === 'II';
|
||||
const short = littleEndian ? data.readUInt16LE.bind(data) : data.readUInt16BE.bind(data);
|
||||
const long = littleEndian ? data.readUInt32LE.bind(data) : data.readUInt32BE.bind(data);
|
||||
if ((!littleEndian && data.toString('latin1', 0, 2) !== 'MM') || short(2) !== 42) return null;
|
||||
|
||||
let directory = long(4);
|
||||
let first: RasterInfo | null = null;
|
||||
let decodedBytes = 0;
|
||||
for (let page = 0; directory; page++) {
|
||||
if (page === MAX_TIFF_PAGES) return null;
|
||||
const info = readTiffPage(data, short, long, directory);
|
||||
if (!info) return null;
|
||||
decodedBytes += info.bytes;
|
||||
if (decodedBytes > MAX_RASTER_BYTES) return null;
|
||||
first ??= { width: info.width, height: info.height, mimeType: 'image/tiff' };
|
||||
directory = info.next;
|
||||
}
|
||||
return first;
|
||||
}
|
||||
|
||||
function skipGifBlocks(data: Buffer, offset: number): number {
|
||||
while (offset < data.length) {
|
||||
const blockSize = data[offset++];
|
||||
if (blockSize === 0) return offset;
|
||||
offset += blockSize;
|
||||
}
|
||||
return data.length;
|
||||
}
|
||||
|
||||
function gifPaletteBytes(flags: number): number {
|
||||
return flags & 0x80 ? 3 * (2 << (flags & 7)) : 0;
|
||||
}
|
||||
|
||||
function readGifHeader(data: Buffer): RasterInfo | null {
|
||||
const width = data.readUInt16LE(6);
|
||||
const height = data.readUInt16LE(8);
|
||||
if (!fitsRaster(width, height)) return null;
|
||||
let offset = 13 + gifPaletteBytes(data[10]);
|
||||
let frames = 0;
|
||||
while (offset < data.length) {
|
||||
const block = data[offset++];
|
||||
if (block === 0x3b) return frames ? { width, height, mimeType: 'image/gif' } : null;
|
||||
if (block === 0x21) {
|
||||
offset = skipGifBlocks(data, offset + 1);
|
||||
continue;
|
||||
}
|
||||
if (block !== 0x2c || offset + 9 > data.length || ++frames > 1_000) return null;
|
||||
if (!fitsRaster(data.readUInt16LE(offset + 4), data.readUInt16LE(offset + 6))) return null;
|
||||
offset = skipGifBlocks(data, offset + 10 + gifPaletteBytes(data[offset + 8]));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function readRasterHeader(data: Buffer): RasterInfo | null {
|
||||
const common = readImageHeader(data);
|
||||
if (common) return common;
|
||||
|
||||
const signature = data.toString('latin1', 0, 6);
|
||||
if (data.length >= 13 && (signature === 'GIF87a' || signature === 'GIF89a')) {
|
||||
return readGifHeader(data);
|
||||
}
|
||||
if (data.length >= 26 && signature.startsWith('BM')) {
|
||||
const dibSize = data.readUInt32LE(14);
|
||||
if (dibSize < 40 || 14 + dibSize > data.length) return null;
|
||||
return { width: data.readInt32LE(18), height: Math.abs(data.readInt32LE(22)), mimeType: 'image/bmp' };
|
||||
}
|
||||
return data.length >= 8 ? readTiffHeader(data) : null;
|
||||
}
|
||||
|
||||
export function boundedRasterHeader(data: Buffer): RasterInfo | null {
|
||||
const header = readRasterHeader(data);
|
||||
return header && fitsRaster(header.width, header.height) ? header : null;
|
||||
}
|
||||
|
||||
/** Limit the compressed input independently of the decoded pixel budget. */
|
||||
export async function readRasterFile(path: string, maxBytes: number): Promise<Buffer | null> {
|
||||
const file = await open(path, 'r');
|
||||
try {
|
||||
const { size } = await file.stat();
|
||||
if (size === 0 || size > maxBytes) return null;
|
||||
const data = Buffer.alloc(size);
|
||||
const { bytesRead } = await file.read(data);
|
||||
return bytesRead === size ? data : null;
|
||||
} finally {
|
||||
await file.close();
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { TrekPhotos } from '../../db/entities/TrekPhotos.entity';
|
||||
import type { JourneysRepository } from '../../db/repositories/Journeys.repository';
|
||||
import type { TrekPhotosRepository } from '../../db/repositories/TrekPhotos.repository';
|
||||
import { logWarn } from '../audit/audit-log.logger';
|
||||
import { boundedRasterHeader, MAX_RASTER_PIXELS, readRasterFile } from '../common/bounded-raster';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { StorageNotFoundError, type ServedCategory } from '../storage/storage.types';
|
||||
import { redactLocationInFile } from './media-redact';
|
||||
@@ -23,6 +24,7 @@ const RENDITION_CATEGORIES: readonly ServedCategory[] = ['avatars', 'covers', 'j
|
||||
|
||||
/** Image types Jimp both decodes and writes; it writes no metadata, so a re-encoded copy carries no location. */
|
||||
const REENCODABLE_EXTENSIONS = new Set(['.bmp', '.gif', '.jpeg', '.jpg', '.png', '.tif', '.tiff']);
|
||||
const MAX_REENCODE_BYTES = 32 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* How long a request waits for a copy being made: just under the 60 s a
|
||||
@@ -188,7 +190,11 @@ export class PublicMediaService {
|
||||
if (!REENCODABLE_EXTENSIONS.has(extension)) return false;
|
||||
try {
|
||||
// Jimp applies the EXIF orientation on read, so the copy shows upright without it.
|
||||
const image = await this.storage.withLocalFile(category, name, (source) => Jimp.read(source));
|
||||
const bytes = await this.storage.withLocalFile(category, name, (source) =>
|
||||
readRasterFile(source, MAX_REENCODE_BYTES),
|
||||
);
|
||||
if (!bytes || !boundedRasterHeader(bytes)) return false;
|
||||
const image = await Jimp.read(bytes, { 'image/jpeg': { maxResolutionInMP: MAX_RASTER_PIXELS / 1_000_000 } });
|
||||
await image.write(spool as Parameters<typeof image.write>[0]);
|
||||
return true;
|
||||
} catch {
|
||||
|
||||
Reference in New Issue
Block a user