mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-02 17:26:24 +00:00
fix(journey): validate and safely serve media uploads
This commit is contained in:
@@ -24,6 +24,8 @@ import crypto from 'node:crypto';
|
||||
import type { User } from '../../types';
|
||||
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';
|
||||
@@ -103,6 +105,7 @@ export function journeyImageFileFilter(allowedTypes: AllowedFileTypesService): O
|
||||
err.statusCode = 400;
|
||||
cb(err);
|
||||
};
|
||||
if (ext && !journeyImageType(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
|
||||
@@ -184,12 +187,18 @@ export class JourneyController {
|
||||
) {}
|
||||
|
||||
/**
|
||||
* Commit spooled multer files to their final uploads/journey location. On any
|
||||
* failure: best-effort removal of both spool leftovers and already-committed
|
||||
* names, then rethrow (500) — so a DB row never references a missing file.
|
||||
* 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> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
for (const f of files) await this.storage.put('journey', f.filename, { tmpPath: f.path });
|
||||
} catch (err) {
|
||||
for (const f of files) {
|
||||
|
||||
@@ -96,6 +96,37 @@ function sniffFormat(head: Buffer): MediaFormat {
|
||||
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. */
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { lookup } from 'mime-types';
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
@@ -40,3 +41,29 @@ const MIME_BY_EXT: Record<string, string> = {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { RuntimeEnvService } from '../app-config/runtime-env.service';
|
||||
import { logDebug } from '../audit/audit-log.logger';
|
||||
import { contentTypeFor } from './content-type';
|
||||
import { contentTypeFor, journeyInlineType } from './content-type';
|
||||
import type { ReplicaFailure } from './drivers/mirror.driver';
|
||||
import { decideRange, isNotModified, validatorsFor, type ServingHeaders, type Validators } from './http-serving';
|
||||
import { assertValidKey } from './storage-keys';
|
||||
@@ -193,6 +193,17 @@ export class StorageService {
|
||||
async sendToResponse(category: ServedCategory, name: string, res: Response, opts?: SendOptions): Promise<void> {
|
||||
const { driver, key } = this.resolve(category, name);
|
||||
|
||||
if (category === 'journey') {
|
||||
// Older uploads can have arbitrary extensions. Use the same response policy
|
||||
// for local and remote objects, including when a browser opens one directly.
|
||||
const contentType = journeyInlineType(name);
|
||||
opts = contentType
|
||||
? { ...opts, contentType }
|
||||
: { contentType: 'application/octet-stream', disposition: 'attachment' };
|
||||
res.setHeader('Content-Security-Policy', 'sandbox');
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
}
|
||||
|
||||
const localPath = this.localPathIfPresent(driver, key);
|
||||
if (localPath !== null) {
|
||||
this.applyHeaders(res, opts);
|
||||
|
||||
Reference in New Issue
Block a user