Skip to content

πŸ“¨ The ultimate agentic social media scheduling tool πŸ€–

feat: fix uploading

Nevo David118d89c0fb3c
diff --git a/apps/backend/src/api/routes/media.controller.ts b/apps/backend/src/api/routes/media.controller.ts
index dabc629d7..3c6902e88 100644
--- a/apps/backend/src/api/routes/media.controller.ts
+++ b/apps/backend/src/api/routes/media.controller.ts
@@ -1,4 +1,5 @@
import {
+ BadRequestException,
Body,
Controller,
Delete,
@@ -10,7 +11,6 @@ import {
Res,
UploadedFile,
UseInterceptors,
- UsePipes,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
@@ -19,7 +19,7 @@ import { MediaService } from '@gitroom/nestjs-libraries/database/prisma/media/me
import { ApiTags } from '@nestjs/swagger';
import handleR2Upload from '@gitroom/nestjs-libraries/upload/r2.uploader';
import { FileInterceptor } from '@nestjs/platform-express';
-import { CustomFileValidationPipe } from '@gitroom/nestjs-libraries/upload/custom.upload.validation';
+import { streamUploadOptions } from '@gitroom/nestjs-libraries/upload/multer.stream.engine';
import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/subscription.service';
import { UploadFactory } from '@gitroom/nestjs-libraries/upload/upload.factory';
import { SaveMediaInformationDto } from '@gitroom/nestjs-libraries/dtos/media/save.media.information.dto';
@@ -85,19 +85,19 @@ export class MediaController {
}
@Post('/upload-server')
- @UseInterceptors(FileInterceptor('file'))
- @UsePipes(new CustomFileValidationPipe())
+ @UseInterceptors(FileInterceptor('file', streamUploadOptions()))
async uploadServer(
@GetOrgFromRequest() org: Organization,
@UploadedFile() file: Express.Multer.File
) {
- const originalName = file?.originalname || '';
- const uploadedFile = await this.storage.uploadFile(file);
+ if (!file) {
+ throw new BadRequestException('No file provided');
+ }
return this._mediaService.saveFile(
org.id,
- uploadedFile.originalname,
- uploadedFile.path,
- originalName
+ file.filename,
+ file.path,
+ file.originalname
);
}
@@ -128,26 +128,25 @@ export class MediaController {
}
@Post('/upload-simple')
- @UseInterceptors(FileInterceptor('file'))
- @UsePipes(new CustomFileValidationPipe())
+ @UseInterceptors(FileInterceptor('file', streamUploadOptions()))
async uploadSimple(
@GetOrgFromRequest() org: Organization,
@UploadedFile('file') file: Express.Multer.File,
@Body('preventSave') preventSave: string = 'false'
) {
- const originalName = file.originalname;
- const getFile = await this.storage.uploadFile(file);
+ if (!file) {
+ throw new BadRequestException('No file provided');
+ }
if (preventSave === 'true') {
- const { path } = getFile;
- return { path };
+ return { path: file.path };
}
return this._mediaService.saveFile(
org.id,
- getFile.originalname,
- getFile.path,
- originalName
+ file.filename,
+ file.path,
+ file.originalname
);
}
diff --git a/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts b/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts
index a2371240b..8d1e0aa95 100644
--- a/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts
+++ b/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts
@@ -1,4 +1,5 @@
import {
+ BadRequestException,
Body,
Controller,
Delete,
@@ -11,12 +12,8 @@ import {
UploadedFile,
UseGuards,
UseInterceptors,
- UsePipes,
} from '@nestjs/common';
-import {
- CustomFileValidationPipe,
- getMaxSize,
-} from '@gitroom/nestjs-libraries/upload/custom.upload.validation';
+import { streamUploadOptions } from '@gitroom/nestjs-libraries/upload/multer.stream.engine';
import { ApiTags } from '@nestjs/swagger';
import { GetOrgFromRequest } from '@gitroom/nestjs-libraries/user/org.from.request';
import { Organization } from '@prisma/client';
@@ -24,7 +21,6 @@ import { IntegrationService } from '@gitroom/nestjs-libraries/database/prisma/in
import { CheckPolicies } from '@gitroom/backend/services/auth/permissions/permissions.ability';
import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';
import { FileInterceptor } from '@nestjs/platform-express';
-import { UploadFactory } from '@gitroom/nestjs-libraries/upload/upload.factory';
import { MediaService } from '@gitroom/nestjs-libraries/database/prisma/media/media.service';
import { GetPostsDto } from '@gitroom/nestjs-libraries/dtos/posts/get.posts.dto';
import { ChangePostStatusDto } from '@gitroom/nestjs-libraries/dtos/posts/change.post.status.dto';
@@ -38,21 +34,6 @@ import { VideoFunctionDto } from '@gitroom/nestjs-libraries/dtos/videos/video.fu
import { UploadDto } from '@gitroom/nestjs-libraries/dtos/media/upload.dto';
import { NotificationService } from '@gitroom/nestjs-libraries/database/prisma/notifications/notification.service';
import { GetNotificationsDto } from '@gitroom/nestjs-libraries/dtos/notifications/get.notifications.dto';
-import { Readable } from 'stream';
-import { ssrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
-// eslint-disable-next-line @typescript-eslint/no-var-requires
-const { fileTypeFromBuffer } = require('file-type');
-
-const PUBLIC_API_ALLOWED_MIME = new Set<string>([
- 'image/jpeg',
- 'image/png',
- 'image/gif',
- 'image/webp',
- 'image/avif',
- 'image/bmp',
- 'image/tiff',
- 'video/mp4',
-]);
import * as Sentry from '@sentry/nestjs';
import {
socialIntegrationList,
@@ -70,8 +51,6 @@ import { ioRedis } from '@gitroom/nestjs-libraries/redis/redis.service';
@ApiTags('Public API')
@Controller('/public/v1')
export class PublicIntegrationsController {
- private storage = UploadFactory.createStorage();
-
constructor(
private _integrationService: IntegrationService,
private _postsService: PostsService,
@@ -83,8 +62,7 @@ export class PublicIntegrationsController {
) {}
@Post('/upload')
- @UseInterceptors(FileInterceptor('file'))
- @UsePipes(new CustomFileValidationPipe())
+ @UseInterceptors(FileInterceptor('file', streamUploadOptions()))
async uploadSimple(
@GetOrgFromRequest() org: Organization,
@UploadedFile('file') file: Express.Multer.File
@@ -94,12 +72,7 @@ export class PublicIntegrationsController {
throw new HttpException({ msg: 'No file provided' }, 400);
}
- const getFile = await this.storage.uploadFile(file);
- return this._mediaService.saveFile(
- org.id,
- getFile.originalname,
- getFile.path
- );
+ return this._mediaService.saveFile(org.id, file.filename, file.path);
}
@Post('/upload-from-url')
@@ -108,62 +81,15 @@ export class PublicIntegrationsController {
@Body() body: UploadDto
) {
Sentry.metrics.count('public_api-request', 1);
- let response: globalThis.Response;
try {
- response = await fetch(body.url, {
- // @ts-ignore β€” undici option, not in lib.dom fetch types
- dispatcher: ssrfSafeDispatcher,
- });
- } catch {
- // Network-level failure (DNS, connection refused, SSRF block, etc.) β€”
- // fetch rejects rather than returning a non-ok response.
- throw new HttpException({ msg: 'Failed to fetch URL' }, 400);
- }
- if (!response.ok) {
- throw new HttpException({ msg: 'Failed to fetch URL' }, 400);
- }
-
- // Guard against OOM: bail out before buffering the whole body into memory.
- // Content-Length may be absent or wrong, so we re-check the real size after
- // download too. The type isn't known yet (sniffed below), so the pre-check
- // uses the largest allowed cap (video).
- const maxDownloadSize = getMaxSize('video/mp4');
- const declaredSize = Number(response.headers.get('content-length'));
- if (declaredSize && declaredSize > maxDownloadSize) {
- throw new HttpException({ msg: 'File is too large.' }, 400);
- }
-
- const buffer = Buffer.from(await response.arrayBuffer());
- const detected = await fileTypeFromBuffer(buffer);
- if (!detected || !PUBLIC_API_ALLOWED_MIME.has(detected.mime)) {
- throw new HttpException({ msg: 'Unsupported file type.' }, 400);
- }
-
- if (buffer.length > getMaxSize(detected.mime)) {
- throw new HttpException({ msg: 'File is too large.' }, 400);
+ return await this._mediaService.uploadFromUrl(org.id, body.url);
+ } catch (err) {
+ // Validation failures keep this route's { msg } error shape
+ if (err instanceof BadRequestException) {
+ throw new HttpException({ msg: err.message }, 400);
+ }
+ throw err;
}
-
- const mimetype = detected.mime;
- const ext = detected.ext;
-
- const getFile = await this.storage.uploadFile({
- buffer,
- mimetype,
- size: buffer.length,
- path: '',
- fieldname: '',
- destination: '',
- stream: new Readable(),
- filename: '',
- originalname: `upload.${ext}`,
- encoding: '',
- });
-
- return this._mediaService.saveFile(
- org.id,
- getFile.originalname,
- getFile.path
- );
}
@Get('/find-slot/:id')
diff --git a/libraries/nestjs-libraries/src/chat/tools/upload.from.url.tool.ts b/libraries/nestjs-libraries/src/chat/tools/upload.from.url.tool.ts
index 3d99c365e..7b7fb4dbb 100644
--- a/libraries/nestjs-libraries/src/chat/tools/upload.from.url.tool.ts
+++ b/libraries/nestjs-libraries/src/chat/tools/upload.from.url.tool.ts
@@ -3,30 +3,10 @@ import { createTool } from '@mastra/core/tools';
import { z } from 'zod';
import { Injectable } from '@nestjs/common';
import { MediaService } from '@gitroom/nestjs-libraries/database/prisma/media/media.service';
-import { UploadFactory } from '@gitroom/nestjs-libraries/upload/upload.factory';
-import { getMaxSize } from '@gitroom/nestjs-libraries/upload/custom.upload.validation';
import { checkAuth } from '@gitroom/nestjs-libraries/chat/auth.context';
-import { ssrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
-import { Readable } from 'stream';
-// eslint-disable-next-line @typescript-eslint/no-var-requires
-const { fileTypeFromBuffer } = require('file-type');
-
-// Same allow-list as the public API /upload-from-url route.
-const ALLOWED_MIME = new Set<string>([
- 'image/jpeg',
- 'image/png',
- 'image/gif',
- 'image/webp',
- 'image/avif',
- 'image/bmp',
- 'image/tiff',
- 'video/mp4',
-]);
@Injectable()
export class UploadFromUrlTool implements AgentToolInterface {
- private storage = UploadFactory.createStorage();
-
constructor(private _mediaService: MediaService) {}
name = 'uploadFromUrlTool';
@@ -68,75 +48,27 @@ so the attachment passes the upload-domain validation. Returns the hosted media
(context?.requestContext as any)?.get('organization') as string
);
- const response = await fetch(inputData.url, {
- // @ts-ignore β€” undici option, not in lib.dom fetch types
- dispatcher: ssrfSafeDispatcher,
- });
-
- if (!response.ok) {
- return { error: 'Failed to fetch URL' };
- }
-
- // Guard against OOM: bail out before buffering the whole body into
- // memory. Content-Length may be absent or wrong, so we re-check the
- // real size after download too. The type isn't known yet (sniffed
- // below), so the pre-check uses the largest allowed cap (video).
- const maxDownloadSize = getMaxSize('video/mp4');
- const declaredSize = Number(response.headers.get('content-length'));
- if (declaredSize && declaredSize > maxDownloadSize) {
- return {
- error: `File is too large: ${declaredSize} bytes (max ${maxDownloadSize} bytes).`,
- };
- }
-
- const buffer = Buffer.from(await response.arrayBuffer());
- const detected = await fileTypeFromBuffer(buffer);
- if (!detected || !ALLOWED_MIME.has(detected.mime)) {
- return { error: 'Unsupported file type.' };
- }
-
- const maxSize = getMaxSize(detected.mime);
- if (buffer.length > maxSize) {
- return {
- error: `File is too large: ${buffer.length} bytes (max ${maxSize} bytes).`,
- };
- }
-
- const getFile = await this.storage.uploadFile({
- buffer,
- mimetype: detected.mime,
- size: buffer.length,
- path: '',
- fieldname: '',
- destination: '',
- stream: new Readable(),
- filename: '',
- originalname: `upload.${detected.ext}`,
- encoding: '',
- });
-
- return await this._mediaService.saveFile(
- org.id,
- getFile.originalname,
- getFile.path
- );
+ return await this._mediaService.uploadFromUrl(org.id, inputData.url);
} catch (err) {
// undici's fetch rejects with a generic TypeError('fetch failed')
// and hides the real reason (DNS, TLS, SSRF block, ...) in
- // err.cause, so surface it for the agent. Error.cause isn't in the
- // es2020 lib typings this repo compiles against, hence the cast.
- const cause =
- err instanceof Error
- ? (err as Error & { cause?: unknown }).cause
- : undefined;
- const causeText =
- cause instanceof Error && cause.message
- ? ` (${cause.message})`
- : '';
+ // err.cause, which the service wraps once more, so walk the chain
+ // and surface it for the agent. Error.cause isn't in the es2020
+ // lib typings this repo compiles against, hence the cast
+ const message =
+ err instanceof Error ? err.message : 'Unexpected error';
+ const causes: string[] = [];
+ let cause = (err as Error & { cause?: unknown })?.cause;
+ while (cause instanceof Error) {
+ if (cause.message) {
+ causes.push(cause.message);
+ }
+ cause = (cause as Error & { cause?: unknown }).cause;
+ }
+ const causeText = causes.length ? ` (${causes.join(': ')})` : '';
+
return {
- error: `Failed to upload media from URL: ${
- err instanceof Error ? err.message : 'Unexpected error'
- }${causeText}`,
+ error: `Failed to upload media from URL: ${message}${causeText}`,
};
}
},
diff --git a/libraries/nestjs-libraries/src/database/prisma/media/media.service.ts b/libraries/nestjs-libraries/src/database/prisma/media/media.service.ts
index 1d3106734..11d222c52 100644
--- a/libraries/nestjs-libraries/src/database/prisma/media/media.service.ts
+++ b/libraries/nestjs-libraries/src/database/prisma/media/media.service.ts
@@ -1,4 +1,4 @@
-import { HttpException, Injectable } from '@nestjs/common';
+import { BadRequestException, HttpException, Injectable } from '@nestjs/common';
import { MediaRepository } from '@gitroom/nestjs-libraries/database/prisma/media/media.repository';
import { OpenaiService } from '@gitroom/nestjs-libraries/openai/openai.service';
import { generationError } from '@gitroom/nestjs-libraries/openai/generation.error';
@@ -19,6 +19,11 @@ import { organizationId } from '@gitroom/nestjs-libraries/temporal/temporal.sear
import { makeId } from '@gitroom/nestjs-libraries/services/make.is';
import { MediaProcessorJob } from '@gitroom/nestjs-libraries/upload/media.processor.interface';
import { extname } from 'path';
+import { ssrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
+import {
+ getMaxSize,
+ uploadStreamToStorage,
+} from '@gitroom/nestjs-libraries/upload/custom.upload.validation';
// What every upload is normalized to before a provider ever sees it. The
// service applies exactly these, so a platform-specific need belongs in the
@@ -53,7 +58,10 @@ const LIMITS: MediaProcessorJob['limits'] = {
};
// Extension of the normalized file and the content type the presigned PUT is
// minted for; anything else (gif, avif, ...) is stored as uploaded
-const PROCESSABLE: Record<string, { type: 'video' | 'image'; ext: string; contentType: string }> = {
+const PROCESSABLE: Record<
+ string,
+ { type: 'video' | 'image'; ext: string; contentType: string }
+> = {
'.mp4': { type: 'video', ext: 'mp4', contentType: 'video/mp4' },
'.mov': { type: 'video', ext: 'mp4', contentType: 'video/mp4' },
'.jpg': { type: 'image', ext: 'jpg', contentType: 'image/jpeg' },
@@ -62,7 +70,14 @@ const PROCESSABLE: Record<string, { type: 'video' | 'image'; ext: string; conten
'.webp': { type: 'image', ext: 'webp', contentType: 'image/webp' },
};
// Formats a post can carry without normalization; anything else only exists to be converted
-const USABLE_AS_IS = new Set(['.mp4', '.jpg', '.jpeg', '.png', '.webp', '.gif']);
+const USABLE_AS_IS = new Set([
+ '.mp4',
+ '.jpg',
+ '.jpeg',
+ '.png',
+ '.webp',
+ '.gif',
+]);
@Injectable()
export class MediaService {
@@ -109,8 +124,55 @@ export class MediaService {
}
}
- saveFile(org: string, fileName: string, filePath: string, originalName?: string) {
- return this._mediaRepository.saveFile(org, fileName, filePath, originalName);
+ // Streams the remote body straight into storage: only the sniffing prefix
+ // and a few upload parts are ever in memory, so a 1 GB video does not cost
+ // 1 GB of heap
+ async uploadFromUrl(org: string, url: string) {
+ let response: globalThis.Response;
+ try {
+ response = await fetch(url, {
+ // @ts-ignore β€” undici option, not in lib.dom fetch types
+ dispatcher: ssrfSafeDispatcher,
+ });
+ } catch (err) {
+ // Network-level failure (DNS, connection refused, SSRF block, etc.) β€”
+ // fetch rejects rather than returning a non-ok response. Keep the real
+ // reason reachable for callers that want to surface it
+ throw new BadRequestException('Failed to fetch URL', { cause: err });
+ }
+ if (!response.ok || !response.body) {
+ throw new BadRequestException('Failed to fetch URL');
+ }
+
+ // Cheap early exit when the server declares the size; Content-Length may
+ // be absent or wrong, so the stream cap below is what really enforces it.
+ // The type isn't known yet (sniffed below), so this uses the largest cap
+ const declaredSize = Number(response.headers.get('content-length'));
+ if (declaredSize && declaredSize > getMaxSize('video/mp4')) {
+ await response.body.cancel();
+ throw new BadRequestException('File is too large.');
+ }
+
+ const uploaded = await uploadStreamToStorage(
+ this.storage,
+ response.body,
+ declaredSize
+ );
+ return this.saveFile(org, uploaded.originalname, uploaded.path);
+ }
+
+ saveFile(
+ org: string,
+ fileName: string,
+ filePath: string,
+ originalName?: string
+ ) {
+ return this._mediaRepository.saveFile(
+ org,
+ fileName,
+ filePath,
+ originalName
+ );
}
// Saves an upload and, when a normalizer is configured, hands it to the
@@ -123,7 +185,11 @@ export class MediaService {
) {
const media = await this.saveFile(org, fileName, filePath, originalName);
const client = this._temporalService.client.getRawClient();
- if (!this.processor || !PROCESSABLE[extname(fileName).toLowerCase()] || !client) {
+ if (
+ !this.processor ||
+ !PROCESSABLE[extname(fileName).toLowerCase()] ||
+ !client
+ ) {
return media;
}
@@ -205,7 +271,10 @@ export class MediaService {
reference: media.id,
source: { url: await this.storage.signDownloadUrl(media.name) },
output: {
- url: await this.storage.signUploadUrl(outputName, processable.contentType),
+ url: await this.storage.signUploadUrl(
+ outputName,
+ processable.contentType
+ ),
content_type: processable.contentType,
},
rules: processable.type === 'video' ? VIDEO_RULES : IMAGE_RULES,
@@ -247,9 +316,15 @@ export class MediaService {
}
const { result } = job;
- if (!result || !['completed', 'unchanged', 'failed'].includes(result.status)) {
+ if (
+ !result ||
+ !['completed', 'unchanged', 'failed'].includes(result.status)
+ ) {
await this._mediaRepository.finishProcessing(org, mediaId, {
- error: `Unexpected processor result: ${JSON.stringify(result).slice(0, 500)}`,
+ error: `Unexpected processor result: ${JSON.stringify(result).slice(
+ 0,
+ 500
+ )}`,
});
return true;
}
@@ -258,7 +333,9 @@ export class MediaService {
// the stderr tail is the only way to know what ffmpeg objected to
await this._mediaRepository.finishProcessing(org, mediaId, {
error: [
- `${result.failure?.code || 'FAILED'}: ${result.failure?.message || ''}`,
+ `${result.failure?.code || 'FAILED'}: ${
+ result.failure?.message || ''
+ }`,
result.failure?.stderr_tail,
]
.filter(Boolean)
@@ -298,9 +375,13 @@ export class MediaService {
return;
}
- return this._mediaRepository.finishProcessing(media.organizationId, mediaId, {
- error,
- });
+ return this._mediaRepository.finishProcessing(
+ media.organizationId,
+ mediaId,
+ {
+ error,
+ }
+ );
}
getMedia(org: string, page: number, search?: string) {
diff --git a/libraries/nestjs-libraries/src/upload/cloudflare.storage.ts b/libraries/nestjs-libraries/src/upload/cloudflare.storage.ts
index 748807f9a..6fc597d5c 100644
--- a/libraries/nestjs-libraries/src/upload/cloudflare.storage.ts
+++ b/libraries/nestjs-libraries/src/upload/cloudflare.storage.ts
@@ -5,12 +5,14 @@ import {
DeleteObjectCommand,
} from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
+import { Upload } from '@aws-sdk/lib-storage';
+import { Readable } from 'stream';
import 'multer';
import { makeId } from '@gitroom/nestjs-libraries/services/make.is';
import mime from 'mime-types';
// @ts-ignore
import { getExtension } from 'mime';
-import { IUploadProvider } from './upload.interface';
+import { IUploadProvider, UploadedStream } from './upload.interface';
import axios from 'axios';
import { isSafePublicHttpsUrl } from '@gitroom/nestjs-libraries/dtos/webhooks/webhook.url.validator';
import { ssrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
@@ -160,6 +162,44 @@ class CloudflareStorage implements IUploadProvider {
}
}
+ async uploadStream(
+ stream: Readable,
+ mimetype: string,
+ ext: string
+ ): Promise<UploadedStream> {
+ try {
+ if (!ALLOWED_MIME_TYPES.has(mimetype)) {
+ throw new Error('Unsupported file type.');
+ }
+ const id = makeId(10);
+ const key = `${id}.${ext}`;
+
+ // Multipart upload holds only a few parts in memory at a time instead
+ // of the whole body, and does not need to know the length up front
+ const upload = new Upload({
+ client: this._client,
+ params: {
+ Bucket: this._bucketName,
+ ACL: 'public-read',
+ Key: key,
+ Body: stream,
+ ContentType: mimetype,
+ },
+ });
+ await upload.done();
+
+ return {
+ filename: key,
+ mimetype,
+ originalname: key,
+ path: `${this._uploadUrl}/${key}`,
+ };
+ } catch (err) {
+ console.error('Error streaming file to Cloudflare R2:', err);
+ throw err;
+ }
+ }
+
async signDownloadUrl(fileName: string) {
return getSignedUrl(
this._client,
diff --git a/libraries/nestjs-libraries/src/upload/custom.upload.validation.ts b/libraries/nestjs-libraries/src/upload/custom.upload.validation.ts
index 1e3c5d144..788473b8a 100644
--- a/libraries/nestjs-libraries/src/upload/custom.upload.validation.ts
+++ b/libraries/nestjs-libraries/src/upload/custom.upload.validation.ts
@@ -1,12 +1,12 @@
-import {
- BadRequestException,
- Injectable,
- PipeTransform,
-} from '@nestjs/common';
+import { BadRequestException } from '@nestjs/common';
+import { pipeline, Readable, Transform } from 'stream';
+import { IUploadProvider } from './upload.interface';
// eslint-disable-next-line @typescript-eslint/no-var-requires
-const { fileTypeFromBuffer } = require('file-type');
+const { fileTypeStream } = require('file-type');
-const ALLOWED_MIME_TYPES = new Set<string>([
+// What users may put in the media library, whether by multipart upload or
+// from a remote URL; narrower than what storage itself accepts, no audio
+export const UPLOAD_ALLOWED_MIME = new Set<string>([
'image/jpeg',
'image/png',
'image/gif',
@@ -17,46 +17,6 @@ const ALLOWED_MIME_TYPES = new Set<string>([
'video/mp4',
]);
-@Injectable()
-export class CustomFileValidationPipe implements PipeTransform {
- async transform(value: any) {
- if (!value || typeof value !== 'object') {
- return value;
- }
-
- // Skip non-file parameters (org, body, query, etc.)
- if (!('buffer' in value) && !('mimetype' in value) && !('fieldname' in value)) {
- return value;
- }
-
- if (!value.buffer || !Buffer.isBuffer(value.buffer)) {
- throw new BadRequestException('Invalid file upload.');
- }
-
- const detected = await fileTypeFromBuffer(value.buffer);
- if (!detected || !ALLOWED_MIME_TYPES.has(detected.mime)) {
- throw new BadRequestException('Unsupported file type.');
- }
-
- const maxSize = getMaxSize(detected.mime);
- if (value.size > maxSize) {
- throw new BadRequestException(
- `File size exceeds the maximum allowed size of ${maxSize} bytes.`
- );
- }
-
- value.mimetype = detected.mime;
- const safeBase = (value.originalname || 'upload')
- .replace(/\.[^./\\]*$/, '')
- .replace(/[\\/]/g, '_')
- .slice(0, 100) || 'upload';
- value.originalname = `${safeBase}.${detected.ext}`;
-
- return value;
- }
-
-}
-
export function getMaxSize(mimeType: string): number {
if (mimeType.startsWith('image/')) {
return 10 * 1024 * 1024; // 10 MB
@@ -66,3 +26,68 @@ export function getMaxSize(mimeType: string): number {
throw new BadRequestException('Unsupported file type.');
}
}
+
+// Passes bytes through and fails once they exceed maxSize, so a body with a
+// missing or lying Content-Length cannot be streamed into storage unbounded
+export function maxSizeStream(maxSize: number) {
+ let total = 0;
+ return new Transform({
+ transform(chunk: Buffer, _encoding, callback) {
+ total += chunk.length;
+ if (total > maxSize) {
+ return callback(new BadRequestException('File is too large.'));
+ }
+ callback(null, chunk);
+ },
+ });
+}
+
+// Sniffs the real type from the first bytes, applies the per-type size cap
+// and streams the rest into storage, so only the sniffing prefix and a few
+// upload parts are ever in memory. Rejections are BadRequestException with
+// the same messages the old buffer validation used. `declaredSize` is the
+// Content-Length when the sender gave one; it may be absent or wrong, so the
+// stream cap is what really enforces the limit
+export async function uploadStreamToStorage(
+ storage: IUploadProvider,
+ webStream: ReadableStream,
+ declaredSize = 0
+) {
+ let sniffed: ReadableStream & { fileType?: { mime: string; ext: string } };
+ try {
+ sniffed = await fileTypeStream(webStream);
+ } catch (err) {
+ throw new BadRequestException('Failed to read file', { cause: err });
+ }
+ const detected = sniffed.fileType;
+ if (!detected || !UPLOAD_ALLOWED_MIME.has(detected.mime)) {
+ await sniffed.cancel();
+ throw new BadRequestException('Unsupported file type.');
+ }
+
+ const maxSize = getMaxSize(detected.mime);
+ if (declaredSize > maxSize) {
+ await sniffed.cancel();
+ throw new BadRequestException('File is too large.');
+ }
+
+ // pipeline (not pipe) so failing the cap also tears down the source
+ const body = pipeline(
+ Readable.fromWeb(sniffed as any),
+ maxSizeStream(maxSize),
+ () => {}
+ );
+
+ try {
+ const uploaded = await storage.uploadStream(
+ body,
+ detected.mime,
+ detected.ext
+ );
+ return { ...uploaded, ext: detected.ext };
+ } catch (err) {
+ // The size cap rejects mid-upload with its own BadRequestException
+ body.destroy();
+ throw err;
+ }
+}
diff --git a/libraries/nestjs-libraries/src/upload/local.storage.ts b/libraries/nestjs-libraries/src/upload/local.storage.ts
index 3351253a0..6a4452e1f 100644
--- a/libraries/nestjs-libraries/src/upload/local.storage.ts
+++ b/libraries/nestjs-libraries/src/upload/local.storage.ts
@@ -1,5 +1,7 @@
-import { IUploadProvider } from './upload.interface';
-import { mkdirSync, unlink, writeFileSync } from 'fs';
+import { IUploadProvider, UploadedStream } from './upload.interface';
+import { createWriteStream, mkdirSync, unlink, writeFileSync } from 'fs';
+import { Readable } from 'stream';
+import { pipeline } from 'stream/promises';
import { isSafePublicHttpsUrl } from '@gitroom/nestjs-libraries/dtos/webhooks/webhook.url.validator';
import { ssrfSafeDispatcher } from '@gitroom/nestjs-libraries/dtos/webhooks/ssrf.safe.dispatcher';
import { parseDataUrl } from '@gitroom/nestjs-libraries/upload/data.url';
@@ -23,6 +25,30 @@ const LOCAL_STORAGE_ALLOWED_MIME = new Set<string>([
export class LocalStorage implements IUploadProvider {
constructor(private uploadDirectory: string) {}
+ // Files live under /YYYY/MM/DD with a random name; creates the folder
+ private newFilePath(ext: string) {
+ const now = new Date();
+ const year = now.getFullYear();
+ const month = String(now.getMonth() + 1).padStart(2, '0');
+ const day = String(now.getDate()).padStart(2, '0');
+
+ const innerPath = `/${year}/${month}/${day}`;
+ const dir = `${this.uploadDirectory}${innerPath}`;
+ mkdirSync(dir, { recursive: true });
+
+ const randomName = Array(32)
+ .fill(null)
+ .map(() => Math.round(Math.random() * 16).toString(16))
+ .join('');
+
+ const filename = `${randomName}.${ext}`;
+ return {
+ filename,
+ filePath: `${dir}/${filename}`,
+ path: process.env.FRONTEND_URL + '/uploads' + `${innerPath}/${filename}`,
+ };
+ }
+
async uploadSimple(path: string) {
const dataUrl = path.startsWith('data:') ? parseDataUrl(path) : null;
@@ -49,28 +75,12 @@ export class LocalStorage implements IUploadProvider {
if (!detected || !LOCAL_STORAGE_ALLOWED_MIME.has(detected.mime)) {
throw new Error('Unsupported file type.');
}
- const findExtension = detected.ext;
-
- const now = new Date();
- const year = now.getFullYear();
- const month = String(now.getMonth() + 1).padStart(2, '0');
- const day = String(now.getDate()).padStart(2, '0');
- const innerPath = `/${year}/${month}/${day}`;
- const dir = `${this.uploadDirectory}${innerPath}`;
- mkdirSync(dir, { recursive: true });
-
- const randomName = Array(32)
- .fill(null)
- .map(() => Math.round(Math.random() * 16).toString(16))
- .join('');
-
- const filePath = `${dir}/${randomName}.${findExtension}`;
- const publicPath = `${innerPath}/${randomName}.${findExtension}`;
+ const { filePath, path: publicUrl } = this.newFilePath(detected.ext);
// Logic to save the file to the filesystem goes here
writeFileSync(filePath, body);
- return process.env.FRONTEND_URL + '/uploads' + publicPath;
+ return publicUrl;
}
async uploadFile(file: Express.Multer.File): Promise<any> {
@@ -79,33 +89,16 @@ export class LocalStorage implements IUploadProvider {
if (!detected || !LOCAL_STORAGE_ALLOWED_MIME.has(detected.mime)) {
throw new Error('Unsupported file type.');
}
- const safeExt = `.${detected.ext}`;
const safeMime = detected.mime;
- const now = new Date();
- const year = now.getFullYear();
- const month = String(now.getMonth() + 1).padStart(2, '0');
- const day = String(now.getDate()).padStart(2, '0');
-
- const innerPath = `/${year}/${month}/${day}`;
- const dir = `${this.uploadDirectory}${innerPath}`;
- mkdirSync(dir, { recursive: true });
-
- const randomName = Array(32)
- .fill(null)
- .map(() => Math.round(Math.random() * 16).toString(16))
- .join('');
-
- const filePath = `${dir}/${randomName}${safeExt}`;
- const publicPath = `${innerPath}/${randomName}${safeExt}`;
-
+ const { filename, filePath, path } = this.newFilePath(detected.ext);
writeFileSync(filePath, file.buffer);
return {
- filename: `${randomName}${safeExt}`,
- path: process.env.FRONTEND_URL + '/uploads' + publicPath,
+ filename,
+ path,
mimetype: safeMime,
- originalname: `${randomName}${safeExt}`,
+ originalname: filename,
};
} catch (err) {
console.error('Error uploading file to Local Storage:', err);
@@ -113,10 +106,46 @@ export class LocalStorage implements IUploadProvider {
}
}
+ async uploadStream(
+ stream: Readable,
+ mimetype: string,
+ ext: string
+ ): Promise<UploadedStream> {
+ try {
+ if (!LOCAL_STORAGE_ALLOWED_MIME.has(mimetype)) {
+ throw new Error('Unsupported file type.');
+ }
+
+ const { filename, filePath, path } = this.newFilePath(ext);
+ try {
+ await pipeline(stream, createWriteStream(filePath));
+ } catch (err) {
+ // Don't leave a truncated file behind (size cap hit, remote closed, ...)
+ await this.removeFile(filePath).catch(() => {});
+ throw err;
+ }
+
+ return {
+ filename,
+ path,
+ mimetype,
+ originalname: filename,
+ };
+ } catch (err) {
+ console.error('Error streaming file to Local Storage:', err);
+ throw err;
+ }
+ }
+
+ // Accepts either the public URL or the filesystem path
async removeFile(filePath: string): Promise<void> {
+ const publicPrefix = process.env.FRONTEND_URL + '/uploads';
+ const localPath = filePath.startsWith(publicPrefix)
+ ? this.uploadDirectory + filePath.slice(publicPrefix.length)
+ : filePath;
// Logic to remove the file from the filesystem goes here
return new Promise((resolve, reject) => {
- unlink(filePath, (err) => {
+ unlink(localPath, (err) => {
if (err) {
reject(err);
} else {
diff --git a/libraries/nestjs-libraries/src/upload/multer.stream.engine.ts b/libraries/nestjs-libraries/src/upload/multer.stream.engine.ts
new file mode 100644
index 000000000..2d5d205a0
--- /dev/null
+++ b/libraries/nestjs-libraries/src/upload/multer.stream.engine.ts
@@ -0,0 +1,67 @@
+import { Request } from 'express';
+import { StorageEngine } from 'multer';
+import { Readable } from 'stream';
+import { IUploadProvider } from './upload.interface';
+import { UploadFactory } from './upload.factory';
+import { getMaxSize, uploadStreamToStorage } from './custom.upload.validation';
+
+// Multer storage engine that streams each incoming file straight into
+// storage instead of multer's default of buffering it whole in memory.
+// `file.filename` / `file.path` end up as the stored key and public URL,
+// `file.originalname` keeps the sender's name with the detected extension
+export class MulterStreamEngine implements StorageEngine {
+ constructor(private storage: IUploadProvider) {}
+
+ _handleFile(
+ req: Request,
+ file: Express.Multer.File,
+ cb: (error?: any, info?: Partial<Express.Multer.File>) => void
+ ) {
+ uploadStreamToStorage(
+ this.storage,
+ Readable.toWeb(file.stream) as any
+ ).then(
+ (uploaded) => {
+ const safeBase =
+ (file.originalname || 'upload')
+ .replace(/\.[^./\\]*$/, '')
+ .replace(/[\\/]/g, '_')
+ .slice(0, 100) || 'upload';
+ cb(null, {
+ filename: uploaded.filename,
+ path: uploaded.path,
+ mimetype: uploaded.mimetype,
+ originalname: `${safeBase}.${uploaded.ext}`,
+ });
+ },
+ (err) => cb(err)
+ );
+ }
+
+ // Multer calls this when the request fails after the file was already
+ // stored (e.g. another part hit a limit), so the orphan is dropped
+ _removeFile(
+ req: Request,
+ file: Express.Multer.File,
+ cb: (error: Error | null) => void
+ ) {
+ this.storage.removeFile(file.path).then(
+ () => cb(null),
+ (err) => cb(err)
+ );
+ }
+}
+
+let engine: MulterStreamEngine;
+
+// Options for FileInterceptor on the multipart upload routes. Multer's own
+// limit sits one byte above the largest allowed type so the in-stream cap is
+// what rejects (a uniform 400 that aborts the upload) rather than multer
+// truncating the file, storing it whole and only then failing with a 413
+export function streamUploadOptions() {
+ engine = engine || new MulterStreamEngine(UploadFactory.createStorage());
+ return {
+ storage: engine,
+ limits: { fileSize: getMaxSize('video/mp4') + 1 },
+ };
+}
diff --git a/libraries/nestjs-libraries/src/upload/upload.interface.ts b/libraries/nestjs-libraries/src/upload/upload.interface.ts
index 73230f110..3fda97352 100644
--- a/libraries/nestjs-libraries/src/upload/upload.interface.ts
+++ b/libraries/nestjs-libraries/src/upload/upload.interface.ts
@@ -1,6 +1,23 @@
+import { Readable } from 'stream';
+
+export interface UploadedStream {
+ filename: string;
+ originalname: string;
+ path: string;
+ mimetype: string;
+}
+
export interface IUploadProvider {
uploadSimple(path: string): Promise<string>;
uploadFile(file: Express.Multer.File): Promise<any>;
+ // Streams the body straight into storage without buffering it. The caller
+ // has already sniffed the real type from the first bytes, so it passes the
+ // detected mime/ext instead of the provider re-sniffing a buffer
+ uploadStream(
+ stream: Readable,
+ mimetype: string,
+ ext: string
+ ): Promise<UploadedStream>;
removeFile(filePath: string): Promise<void>;
// Presigned URLs handed to the media processor, which has no storage
// credentials; only cloud storage can mint them
diff --git a/libraries/nestjs-libraries/src/upload/upload.module.ts b/libraries/nestjs-libraries/src/upload/upload.module.ts
index aa03d86e6..2853315ad 100644
--- a/libraries/nestjs-libraries/src/upload/upload.module.ts
+++ b/libraries/nestjs-libraries/src/upload/upload.module.ts
@@ -1,10 +1,9 @@
import { Global, Module } from '@nestjs/common';
import { UploadFactory } from './upload.factory';
-import { CustomFileValidationPipe } from '@gitroom/nestjs-libraries/upload/custom.upload.validation';
@Global()
@Module({
- providers: [UploadFactory, CustomFileValidationPipe],
- exports: [UploadFactory, CustomFileValidationPipe],
+ providers: [UploadFactory],
+ exports: [UploadFactory],
})
export class UploadModule {}
diff --git a/package.json b/package.json
index 27223fbcd..54a87c224 100644
--- a/package.json
+++ b/package.json
@@ -44,6 +44,7 @@
"@ai-sdk/openai": "^2.0.52",
"@atproto/api": "^0.15.15",
"@aws-sdk/client-s3": "^3.787.0",
+ "@aws-sdk/lib-storage": "^3.1003.0",
"@aws-sdk/s3-request-presigner": "^3.787.0",
"@casl/ability": "^6.5.0",
"@copilotkit/react-core": "1.10.6",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 0a45e55f4..10b6dadc0 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -29,6 +29,9 @@ importers:
'@aws-sdk/client-s3':
specifier: ^3.787.0
version: 3.1003.0
+ '@aws-sdk/lib-storage':
+ specifier: ^3.1003.0
+ version: 3.1003.0(@aws-sdk/[email protected])
'@aws-sdk/s3-request-presigner':
specifier: ^3.787.0
version: 3.1003.0
@@ -1168,6 +1171,12 @@ packages:
resolution: {integrity: sha512-g2Z9s6Y4iNh0wICaEqutgYgt/Pmhv5Ev9G3eKGFe2w9VuZDhc76vYdop6I5OocmpHV79d4TuLG+JWg5rQIVDVA==}
engines: {node: '>=20.0.0'}
+ '@aws-sdk/[email protected]':
+ resolution: {integrity: sha512-tyc2WazRhlBNdJu1Vpi7v9Oak8gl4zo0521MYOZustCmdSvGmV8kJdOEa4VK8pUPvm2D7mRgdiNRqesy87gcuQ==}
+ engines: {node: '>=20.0.0'}
+ peerDependencies:
+ '@aws-sdk/client-s3': ^3.1003.0
+
'@aws-sdk/[email protected]':
resolution: {integrity: sha512-goX+axlJ6PQlRnzE2bQisZ8wVrlm6dXJfBzMJhd8LhAIBan/w1Kl73fJnalM/S+18VnpzIHumyV6DtgmvqG5IA==}
engines: {node: '>=20.0.0'}
@@ -7289,6 +7298,10 @@ packages:
resolution: {integrity: sha512-COuLsZILbbQsdrwKQpkkpyep7lCsByxwj7m0Mg5v66/ZTyenlfBc40/QFQ5chO0YN/PNEH1Bi3fGtfXPnYNeDw==}
engines: {node: '>=18.0.0'}
+ '@smithy/[email protected]':
+ resolution: {integrity: sha512-CgB6HHWer/vrKps24ulRIbpcpb7K4xAU7SkZ7YHzBPlwHsvsrCJFEXK421s+cJzX+ZrqtA/TuU5w1HzI7k9N8A==}
+ engines: {node: '>=18.0.0'}
+
'@smithy/[email protected]':
resolution: {integrity: sha512-oTAGGHo8ZYc5VZsBREzuf5lf2pAurJQsccMusVZ85wDkX66ojEc/XauiGjzCj50A61ObFTPe6d7Pyt6UBYaing==}
engines: {node: '>=18.0.0'}
@@ -10131,6 +10144,9 @@ packages:
resolution: {integrity: sha512-571s0T7nZWK6vB67HI5dyUF7wXiNcfaPPPTl6zYCNApANjIvYJTg7hlud/+cJpdAhS7dVzqMLmfhfHR3rAcOjQ==}
+ resolution: {integrity: sha512-/gDYp/UtU0eA1ys8bOs9J6a+E/KWIY+DZ+Q2WESNUA0jFRsJOc0SNUO6xJ5SGA1xueg3NL65W6s+NY5l9cunuw==}
+
resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==}
@@ -19131,7 +19147,7 @@ snapshots:
'@smithy/property-provider': 4.2.11
'@smithy/protocol-http': 5.3.11
'@smithy/shared-ini-file-loader': 4.4.6
- '@smithy/types': 4.13.0
+ '@smithy/types': 4.18.0
tslib: 2.8.1
transitivePeerDependencies:
- aws-crt
@@ -19191,7 +19207,18 @@ snapshots:
dependencies:
'@aws-sdk/types': 3.973.5
'@smithy/eventstream-codec': 4.2.11
- '@smithy/types': 4.13.0
+ '@smithy/types': 4.18.0
+ tslib: 2.8.1
+
+ '@aws-sdk/[email protected](@aws-sdk/[email protected])':
+ dependencies:
+ '@aws-sdk/client-s3': 3.1003.0
+ '@smithy/abort-controller': 4.2.11
+ '@smithy/middleware-endpoint': 4.4.22
+ '@smithy/smithy-client': 4.12.2
+ buffer: 5.6.0
+ events: 3.3.0
+ stream-browserify: 3.0.0
tslib: 2.8.1
'@aws-sdk/[email protected]':
@@ -19208,7 +19235,7 @@ snapshots:
dependencies:
'@aws-sdk/types': 3.973.5
'@smithy/protocol-http': 5.3.11
- '@smithy/types': 4.13.0
+ '@smithy/types': 4.18.0
tslib: 2.8.1
'@aws-sdk/[email protected]':
@@ -19304,7 +19331,7 @@ snapshots:
'@smithy/fetch-http-handler': 5.3.13
'@smithy/protocol-http': 5.3.11
'@smithy/signature-v4': 5.3.11
- '@smithy/types': 4.13.0
+ '@smithy/types': 4.18.0
'@smithy/util-base64': 4.3.2
'@smithy/util-hex-encoding': 4.2.2
'@smithy/util-utf8': 4.2.2
@@ -19338,7 +19365,7 @@ snapshots:
'@smithy/node-http-handler': 4.4.14
'@smithy/protocol-http': 5.3.11
'@smithy/smithy-client': 4.12.2
- '@smithy/types': 4.13.0
+ '@smithy/types': 4.18.0
'@smithy/url-parser': 4.2.11
'@smithy/util-base64': 4.3.2
'@smithy/util-body-length-browser': 4.2.2
@@ -19388,7 +19415,7 @@ snapshots:
'@aws-sdk/types': 3.973.5
'@smithy/property-provider': 4.2.11
'@smithy/shared-ini-file-loader': 4.4.6
- '@smithy/types': 4.13.0
+ '@smithy/types': 4.18.0
tslib: 2.8.1
transitivePeerDependencies:
- aws-crt
@@ -25886,7 +25913,7 @@ snapshots:
'@smithy/[email protected]':
dependencies:
- '@smithy/types': 4.13.0
+ '@smithy/types': 4.18.0
tslib: 2.8.1
'@smithy/[email protected]':
@@ -25931,7 +25958,7 @@ snapshots:
'@smithy/[email protected]':
dependencies:
'@aws-crypto/crc32': 5.2.0
- '@smithy/types': 4.13.0
+ '@smithy/types': 4.18.0
'@smithy/util-hex-encoding': 4.2.2
tslib: 2.8.1
@@ -26115,6 +26142,10 @@ snapshots:
dependencies:
tslib: 2.8.1
+ '@smithy/[email protected]':
+ dependencies:
+ tslib: 2.8.1
+
'@smithy/[email protected]':
dependencies:
'@smithy/querystring-parser': 4.2.11
@@ -30007,6 +30038,11 @@ snapshots:
+ dependencies:
+ base64-js: 1.5.1
+ ieee754: 1.2.1
+
dependencies:
base64-js: 1.5.1