diff --git a/server/src/nest/journey/journey.controller.ts b/server/src/nest/journey/journey.controller.ts index c32ef44b0..85e5aa2ac 100644 --- a/server/src/nest/journey/journey.controller.ts +++ b/server/src/nest/journey/journey.controller.ts @@ -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 { + private async commitJourneyUploads(files: Express.Multer.File[], kind: 'photos' | 'video' = 'photos'): Promise { 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}`, diff --git a/server/src/nest/memories/media-redact.ts b/server/src/nest/memories/media-redact.ts index 0b68302f4..376a255c9 100644 --- a/server/src/nest/memories/media-redact.ts +++ b/server/src/nest/memories/media-redact.ts @@ -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 { - 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 { - 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(items: readonly T[], step: (item: T) => Promise): Promise { return items.reduce>((done, item) => done.then((ok) => ok && step(item)), Promise.resolve(true)); @@ -557,11 +487,6 @@ async function redactMeta(handle: FileHandle, meta: Box): Promise { 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 { if (MOVIE_CONTAINERS.has(box.type)) { const children = await readBoxes(handle, box.body, box.end); diff --git a/server/src/nest/storage/content-type.ts b/server/src/nest/storage/content-type.ts index 1f2f7b900..1c85c8c43 100644 --- a/server/src/nest/storage/content-type.ts +++ b/server/src/nest/storage/content-type.ts @@ -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); } diff --git a/server/src/utils/media-format.ts b/server/src/utils/media-format.ts new file mode 100644 index 000000000..d70a984d7 --- /dev/null +++ b/server/src/utils/media-format.ts @@ -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 { + 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 { + 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; +} diff --git a/server/tests/unit/nest/journey.controller.test.ts b/server/tests/unit/nest/journey.controller.test.ts index 1d6830533..f5589c68a 100644 --- a/server/tests/unit/nest/journey.controller.test.ts +++ b/server/tests/unit/nest/journey.controller.test.ts @@ -23,6 +23,12 @@ import os from 'node:os'; import path from 'node:path'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +// Route unit tests use stand-in uploads. Integration tests exercise real file headers. +vi.mock('../../../src/utils/media-format', async (importOriginal) => ({ + ...(await importOriginal()), + fileMatchesRasterType: vi.fn().mockResolvedValue(true), +})); + const user = { id: 1, username: 'u', role: 'user', email: 'u@example.test' } as User; function svc(o: Partial = {}): JourneyService { diff --git a/server/tests/unit/nest/memories/media-redact.test.ts b/server/tests/unit/nest/memories/media-redact.test.ts index ccd6d2d4c..13ce60264 100644 --- a/server/tests/unit/nest/memories/media-redact.test.ts +++ b/server/tests/unit/nest/memories/media-redact.test.ts @@ -8,6 +8,7 @@ * kept, a PNG whose checksums still hold and still decodes). */ import { redactLocationInBuffer, redactLocationInFile } from '../../../../src/nest/memories/media-redact'; +import { fileMatchesRasterType } from '../../../../src/utils/media-format'; import { jpegWithExif } from '../../../helpers/exif-jpeg'; import exifr from 'exifr'; @@ -102,6 +103,28 @@ function box(type: string, ...parts: Buffer[]): Buffer { return Buffer.concat([head, body]); } +describe('fileMatchesRasterType', () => { + it.each([ + ['image/jpeg', 'ffd8ff'], + ['image/png', '89504e470d0a1a0a'], + ['image/apng', '89504e470d0a1a0a'], + ['image/gif', '4749463839610000'], + ['image/webp', '524946460000000057454250'], + ['image/avif', '00000010667479706176696600000000'], + ['image/heic', '00000010667479706865696300000000'], + ['image/bmp', '424d000000000000000000000000'], + ['image/vnd.microsoft.icon', '000001000100'], + ])('recognizes a %s header', async (contentType, hex) => { + const file = writeTemp('raster-header', Buffer.from(hex, 'hex')); + await expect(fileMatchesRasterType(file, contentType)).resolves.toBe(true); + }); + + it('distinguishes an image header from bytes of a different format', async () => { + const file = writeTemp('wrong-image-format', phonePhoto()); + await expect(fileMatchesRasterType(file, 'image/png')).resolves.toBe(false); + }); +}); + /** A QuickTime movie as an iPhone lays out its location: udta location atom and the mdta keys of moov/meta. */ function iphoneMovie(): Buffer { const xyz = Buffer.alloc(4 + ISO6709.length); diff --git a/server/tests/unit/nest/storage/content-type.test.ts b/server/tests/unit/nest/storage/content-type.test.ts index 367ae8072..b3bef8f0c 100644 --- a/server/tests/unit/nest/storage/content-type.test.ts +++ b/server/tests/unit/nest/storage/content-type.test.ts @@ -1,4 +1,4 @@ -import { contentTypeFor } from '../../../../src/nest/storage/content-type'; +import { contentTypeFor, journeyInlineType } from '../../../../src/nest/storage/content-type'; import { describe, it, expect } from 'vitest'; @@ -13,3 +13,16 @@ describe('contentTypeFor', () => { expect(contentTypeFor('files/weird.xyzzy')).toBe('application/octet-stream'); }); }); + +describe('journeyInlineType', () => { + it.each([ + ['picture.apng', 'image/apng'], + ['picture.HEIF', 'image/heif'], + ['clip.M4V', 'video/mp4'], + ['clip.webm', 'video/webm'], + ['unknown.svg', undefined], + ['unknown.txt', undefined], + ] as const)('uses the inline media type for %s', (name, type) => { + expect(journeyInlineType(name)).toBe(type); + }); +});