fix(journey): align media validation with server checks

Validate spooled uploads in order with the shared iterator and keep media format detection in a shared utility. Adapt the controller unit fixtures and cover raster signatures, including animated PNG.
This commit is contained in:
Maurice
2026-12-02 09:27:30 +01:00
parent 24ddc3e4b0
commit 3089aee593
7 changed files with 161 additions and 111 deletions
+13 -12
View File
@@ -22,10 +22,10 @@ import path from 'node:path';
import fs from 'node:fs';
import crypto from 'node:crypto';
import type { User } from '../../types';
import { forEachInOrder } from '../../utils/for-each-in-order';
import { fileMatchesRasterType, rasterImageType } from '../../utils/media-format';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { isDemoWriteBlocked, DEMO_WRITE_ERROR } from '../common/demo-write';
import { fileMatchesRasterType } from '../memories/media-redact';
import { journeyImageType } from '../storage/content-type';
import { StorageService } from '../storage/storage.service';
import { JourneyGalleryService } from './journey-gallery.service';
import { captureHintFrom } from './journey-capture-hint';
@@ -105,7 +105,7 @@ export function journeyImageFileFilter(allowedTypes: AllowedFileTypesService): O
err.statusCode = 400;
cb(err);
};
if (ext && !journeyImageType(file.originalname)) return reject();
if (ext && !rasterImageType(file.originalname)) return reject();
// R1.5: multer's fileFilter is a callback API that cannot await, and the
// allowed-extension list is now an async read. The decision runs in a
// detached async function that always answers through `cb`; a rejection
@@ -190,14 +190,15 @@ export class JourneyController {
* Check image bytes before committing the batch. On failure, remove spool
* leftovers and any already-committed objects before the error reaches the caller.
*/
private async commitJourneyUploads(files: Express.Multer.File[]): Promise<void> {
private async commitJourneyUploads(files: Express.Multer.File[], kind: 'photos' | 'video' = 'photos'): Promise<void> {
try {
for (const file of files) {
if (file.fieldname === 'video' || file.fieldname === 'poster') continue;
const contentType = journeyImageType(file.filename);
if (!contentType || !(await fileMatchesRasterType(file.path, contentType))) {
throw new HttpException({ error: 'Invalid image file' }, 400);
}
if (kind === 'photos') {
await forEachInOrder(files, async (file) => {
const contentType = rasterImageType(file.filename);
if (!contentType || !(await fileMatchesRasterType(file.path, contentType))) {
throw new HttpException({ error: 'Invalid image file' }, 400);
}
});
}
for (const f of files) await this.storage.put('journey', f.filename, { tmpPath: f.path });
} catch (err) {
@@ -384,7 +385,7 @@ export class JourneyController {
cleanup();
throw new HttpException({ error: 'No video uploaded' }, 400);
}
await this.commitJourneyUploads(poster ? [video, poster] : [video]);
await this.commitJourneyUploads(poster ? [video, poster] : [video], 'video');
const durationMs = body?.duration_ms != null ? Number(body.duration_ms) : null;
const photo = await withRowId(entryId, (id) => this.journey.addPhoto(
id,
@@ -532,7 +533,7 @@ export class JourneyController {
cleanup();
throw new HttpException({ error: 'No video uploaded' }, 400);
}
await this.commitJourneyUploads(poster ? [video, poster] : [video]);
await this.commitJourneyUploads(poster ? [video, poster] : [video], 'video');
const durationMs = body?.duration_ms != null ? Number(body.duration_ms) : null;
const photos = (await withRowId(id, (journeyId) => this.journey.uploadGalleryPhotos(journeyId, user.id, [{
path: `journey/${video.filename}`,
+2 -77
View File
@@ -1,3 +1,5 @@
import { isStillImageBrand, readAt, readTiffByteOrder, sniffFormat } from '../../utils/media-format';
import exifr from 'exifr';
import type { FileHandle } from 'node:fs/promises';
import fsPromises from 'node:fs/promises';
@@ -37,16 +39,6 @@ const XMP_UUID = Buffer.from('be7acfcb97a942e89c71999491e3afac', 'hex');
/** The QuickTime user-data atom holding an ISO 6709 location string. */
const LOCATION_ATOM = '\u00a9xyz';
/**
* ftyp major brands of a still HEIF/AVIF image. Only these may take the
* in-memory image path; any other ISO BMFF file is a movie and has to be
* walked as one, or it is refused.
*/
const STILL_IMAGE_BRANDS = new Set(['avif', 'heic', 'heim', 'heis', 'heix', 'miaf', 'mif1', 'mif2']);
/** Top-level atoms an old QuickTime file may start with instead of ftyp. */
const QUICKTIME_LEAD_ATOMS = new Set(['free', 'mdat', 'moov', 'pnot', 'skip', 'wide']);
const MOOV = Buffer.from('moov', 'latin1');
const PHOTOSHOP_MARK = Buffer.from('Photoshop 3.0\0', 'latin1');
@@ -79,64 +71,8 @@ const XMP_LOCATION_FIELDS = new Set([
'worldregion',
]);
type MediaFormat = 'jpeg' | 'png' | 'webp' | 'gif' | 'tiff' | 'isobmff' | 'quicktime' | 'ebml' | 'unknown';
function sniffFormat(head: Buffer): MediaFormat {
if (head.length >= 3 && head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff) return 'jpeg';
if (head.length < 8) return 'unknown';
if (head.readUInt32BE(0) === 0x89504e47) return 'png';
if (head.toString('latin1', 0, 4) === 'GIF8') return 'gif';
if (head.toString('latin1', 4, 8) === 'ftyp') return 'isobmff';
if (QUICKTIME_LEAD_ATOMS.has(head.toString('latin1', 4, 8))) return 'quicktime';
if (head.readUInt32BE(0) === 0x1a45dfa3) return 'ebml';
if (readTiffByteOrder(head, 0, head.length) !== null) return 'tiff';
if (head.length >= 12 && head.toString('latin1', 0, 4) === 'RIFF' && head.toString('latin1', 8, 12) === 'WEBP') {
return 'webp';
}
return 'unknown';
}
const PNG_SIGNATURE = Buffer.from('89504e470d0a1a0a', 'hex');
const ICON_SIGNATURE = Buffer.from([0, 0, 1, 0]);
/** Match raster headers without decoding untrusted pixel data on upload. */
export async function fileMatchesRasterType(file: string, contentType: string): Promise<boolean> {
const handle = await fsPromises.open(file, 'r');
try {
const head = await readAt(handle, 0, 16);
const format = sniffFormat(head);
switch (contentType) {
case 'image/png':
return head.subarray(0, 8).equals(PNG_SIGNATURE);
case 'image/gif':
return ['GIF87a', 'GIF89a'].includes(head.toString('latin1', 0, 6));
case 'image/avif':
case 'image/heic':
case 'image/heif':
return format === 'isobmff' && isStillImageBrand(head);
case 'image/bmp':
return head.length >= 14 && head.toString('latin1', 0, 2) === 'BM';
case 'image/vnd.microsoft.icon':
case 'image/x-icon':
return head.length >= 6 && head.subarray(0, 4).equals(ICON_SIGNATURE);
default:
return contentType === `image/${format}`;
}
} finally {
await handle.close();
}
}
// ── EXIF / TIFF ─────────────────────────────────────────────────────────────
/** 'le' or 'be' for a TIFF header at `base`, null when there is none. */
function readTiffByteOrder(buf: Buffer, base: number, limit: number): 'le' | 'be' | null {
if (base + 8 > limit) return null;
if (buf[base] === 0x49 && buf[base + 1] === 0x49 && buf.readUInt16LE(base + 2) === 42) return 'le';
if (buf[base] === 0x4d && buf[base + 1] === 0x4d && buf.readUInt16BE(base + 2) === 42) return 'be';
return null;
}
/**
* Empties the GPS IFD of the TIFF structure at `base`: its out-of-line values
* and its entries are zeroed and its entry count set to 0, which also reads
@@ -459,12 +395,6 @@ interface Box {
end: number;
}
async function readAt(handle: FileHandle, position: number, length: number): Promise<Buffer> {
const buf = Buffer.alloc(length);
const { bytesRead } = await handle.read(buf, 0, length, position);
return buf.subarray(0, bytesRead);
}
/** Runs `step` on each item in order, stopping at the first false. */
function everyInOrder<T>(items: readonly T[], step: (item: T) => Promise<boolean>): Promise<boolean> {
return items.reduce<Promise<boolean>>((done, item) => done.then((ok) => ok && step(item)), Promise.resolve(true));
@@ -557,11 +487,6 @@ async function redactMeta(handle: FileHandle, meta: Box): Promise<boolean> {
const MOVIE_CONTAINERS = new Set(['moov', 'trak', 'udta']);
/** Whether the ftyp box at the start of `head` names a still HEIF/AVIF image. */
function isStillImageBrand(head: Buffer): boolean {
return head.length >= 12 && STILL_IMAGE_BRANDS.has(head.toString('latin1', 8, 12));
}
async function redactMovieBox(handle: FileHandle, box: Box): Promise<boolean> {
if (MOVIE_CONTAINERS.has(box.type)) {
const children = await readBoxes(handle, box.body, box.end);
+3 -21
View File
@@ -1,4 +1,5 @@
import { lookup } from 'mime-types';
import { rasterImageType } from '../../utils/media-format';
import path from 'node:path';
/**
@@ -42,28 +43,9 @@ export function contentTypeFor(key: string): string {
return MIME_BY_EXT[path.extname(key).toLowerCase()] ?? 'application/octet-stream';
}
const JOURNEY_IMAGE_TYPES = new Set([
'image/avif',
'image/bmp',
'image/gif',
'image/heic',
'image/heif',
'image/jpeg',
'image/png',
'image/tiff',
'image/vnd.microsoft.icon',
'image/webp',
'image/x-icon',
]);
export function journeyImageType(key: string): string | undefined {
const type = lookup(key);
return type && JOURNEY_IMAGE_TYPES.has(type) ? type : undefined;
}
export function journeyInlineType(key: string): string | undefined {
const type = contentTypeFor(key);
if (type.startsWith('video/')) return type;
if (path.extname(key).toLowerCase() === '.m4v') return 'video/mp4';
return journeyImageType(key);
return rasterImageType(key);
}
+100
View File
@@ -0,0 +1,100 @@
import { lookup } from 'mime-types';
import { open, type FileHandle } from 'node:fs/promises';
/**
* ftyp major brands of a still HEIF/AVIF image. Only these may take the
* in-memory image path; any other ISO BMFF file is a movie and has to be
* walked as one, or it is refused.
*/
const STILL_IMAGE_BRANDS = new Set(['avif', 'heic', 'heim', 'heis', 'heix', 'miaf', 'mif1', 'mif2']);
/** Top-level atoms an old QuickTime file may start with instead of ftyp. */
const QUICKTIME_LEAD_ATOMS = new Set(['free', 'mdat', 'moov', 'pnot', 'skip', 'wide']);
type MediaFormat = 'jpeg' | 'png' | 'webp' | 'gif' | 'tiff' | 'isobmff' | 'quicktime' | 'ebml' | 'unknown';
export function sniffFormat(head: Buffer): MediaFormat {
if (head.length >= 3 && head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff) return 'jpeg';
if (head.length < 8) return 'unknown';
if (head.readUInt32BE(0) === 0x89504e47) return 'png';
if (head.toString('latin1', 0, 4) === 'GIF8') return 'gif';
if (head.toString('latin1', 4, 8) === 'ftyp') return 'isobmff';
if (QUICKTIME_LEAD_ATOMS.has(head.toString('latin1', 4, 8))) return 'quicktime';
if (head.readUInt32BE(0) === 0x1a45dfa3) return 'ebml';
if (readTiffByteOrder(head, 0, head.length) !== null) return 'tiff';
if (head.length >= 12 && head.toString('latin1', 0, 4) === 'RIFF' && head.toString('latin1', 8, 12) === 'WEBP') {
return 'webp';
}
return 'unknown';
}
const PNG_SIGNATURE = Buffer.from('89504e470d0a1a0a', 'hex');
const ICON_SIGNATURE = Buffer.from([0, 0, 1, 0]);
/** Match raster headers without decoding untrusted pixel data on upload. */
export async function fileMatchesRasterType(file: string, contentType: string): Promise<boolean> {
const handle = await open(file, 'r');
try {
const head = await readAt(handle, 0, 16);
const format = sniffFormat(head);
switch (contentType) {
case 'image/apng':
case 'image/png':
return head.subarray(0, 8).equals(PNG_SIGNATURE);
case 'image/gif':
return ['GIF87a', 'GIF89a'].includes(head.toString('latin1', 0, 6));
case 'image/avif':
case 'image/heic':
case 'image/heif':
return format === 'isobmff' && isStillImageBrand(head);
case 'image/bmp':
return head.length >= 14 && head.toString('latin1', 0, 2) === 'BM';
case 'image/vnd.microsoft.icon':
case 'image/x-icon':
return head.length >= 6 && head.subarray(0, 4).equals(ICON_SIGNATURE);
default:
return contentType === `image/${format}`;
}
} finally {
await handle.close();
}
}
/** 'le' or 'be' for a TIFF header at `base`, null when there is none. */
export function readTiffByteOrder(buf: Buffer, base: number, limit: number): 'le' | 'be' | null {
if (base + 8 > limit) return null;
if (buf[base] === 0x49 && buf[base + 1] === 0x49 && buf.readUInt16LE(base + 2) === 42) return 'le';
if (buf[base] === 0x4d && buf[base + 1] === 0x4d && buf.readUInt16BE(base + 2) === 42) return 'be';
return null;
}
/** Whether the ftyp box at the start of `head` names a still HEIF/AVIF image. */
export function isStillImageBrand(head: Buffer): boolean {
return head.length >= 12 && STILL_IMAGE_BRANDS.has(head.toString('latin1', 8, 12));
}
export async function readAt(handle: FileHandle, position: number, length: number): Promise<Buffer> {
const buf = Buffer.alloc(length);
const { bytesRead } = await handle.read(buf, 0, length, position);
return buf.subarray(0, bytesRead);
}
const RASTER_IMAGE_TYPES = new Set([
'image/apng',
'image/avif',
'image/bmp',
'image/gif',
'image/heic',
'image/heif',
'image/jpeg',
'image/png',
'image/tiff',
'image/vnd.microsoft.icon',
'image/webp',
'image/x-icon',
]);
export function rasterImageType(key: string): string | undefined {
const type = lookup(key);
return type && RASTER_IMAGE_TYPES.has(type) ? type : undefined;
}