fix: Profilbild-Upload auf JSON/Base64 umgestellt statt multipart
POST /profile/avatar schlug live mit net::ERR_FAILED fehl (Verbindung abgebrochen, keine Antwort) - selbst bei einer winzigen Testdatei. CORS-Preflight lief sauber durch, nur der eigentliche multipart-POST nicht; passt zum bereits dokumentierten Cloudflare-Verhalten bei multipart-Uploads (siehe .gitea/workflows/*-image.yml). Umgangen durch Umstellung auf denselben JSON-Content-Type, der fuer alle anderen Endpunkte nachweislich zuverlaessig funktioniert: Bild wird clientseitig als data:-URL kodiert und im JSON-Body gesendet. Globales JSON-Body-Limit auf 5mb angehoben (deckt 2MB-Bild plus Base64-Overhead).
This commit is contained in:
1 parent
abe1f6e8cf
commit
135738fdfc
7 files changed
+81
-49
No files matched your search
@@ -10,6 +10,11 @@ export function configureApp(app: NestExpressApplication): void {
|
||||
// real client IP from X-Forwarded-For — required for per-client throttling
|
||||
// to work correctly rather than rate-limiting all traffic together.
|
||||
app.set('trust proxy', 1);
|
||||
// Default 100kb JSON body limit is too small for the avatar upload, which
|
||||
// sends the image as a base64 data: URL in the JSON body (not multipart -
|
||||
// see profile/dto/upload-avatar.dto.ts for why) - 5mb comfortably covers
|
||||
// the 2MB decoded size cap plus base64 overhead.
|
||||
app.useBodyParser('json', { limit: '5mb' });
|
||||
app.use(helmet());
|
||||
app.use(cookieParser());
|
||||
app.use(requestLoggerMiddleware);
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
export const MAX_AVATAR_SIZE_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
export const ALLOWED_AVATAR_MIME_TYPES: Record<string, string> = {
|
||||
'image/jpeg': '.jpg',
|
||||
'image/png': '.png',
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsString, MaxLength } from 'class-validator';
|
||||
|
||||
// Base64 data: URL instead of multipart/form-data - some reverse-proxy
|
||||
// setups mishandle multipart uploads (seen with this deployment's own
|
||||
// container registry pushes, see .gitea/workflows/*-image.yml), while plain
|
||||
// JSON POSTs have proven reliable end to end. 3_000_000 chars covers the
|
||||
// 2 MB size cap (MAX_AVATAR_SIZE_BYTES) plus base64's ~33% overhead and the
|
||||
// data: URL prefix, with headroom.
|
||||
export class UploadAvatarDto {
|
||||
@ApiProperty({
|
||||
description:
|
||||
'Bild als data: URL, z.B. "data:image/png;base64,...". Erlaubt: image/jpeg, image/png, image/webp.',
|
||||
})
|
||||
@IsString()
|
||||
@MaxLength(3_000_000)
|
||||
data!: string;
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
@@ -8,26 +7,21 @@ import {
|
||||
Patch,
|
||||
Post,
|
||||
Res,
|
||||
UploadedFile,
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import { ApiBearerAuth, ApiConsumes, ApiTags } from '@nestjs/swagger';
|
||||
import { ApiBearerAuth, ApiTags } from '@nestjs/swagger';
|
||||
import { Throttle } from '@nestjs/throttler';
|
||||
import type { Response } from 'express';
|
||||
import { CurrentUser } from '../auth/decorators/current-user.decorator';
|
||||
import type { AuthenticatedUser } from '../auth/types/authenticated-user';
|
||||
import { SENSITIVE_ACTION_THROTTLE } from '../auth/util/throttle';
|
||||
import { isAllowedAvatarMimeType } from './avatar-mime-types';
|
||||
import { ChangePasswordDto } from './dto/change-password.dto';
|
||||
import { DeactivateAccountDto } from './dto/deactivate-account.dto';
|
||||
import { DisableMfaDto } from './dto/disable-mfa.dto';
|
||||
import { MfaConfirmDto } from './dto/mfa-confirm.dto';
|
||||
import { UpdateProfileDto } from './dto/update-profile.dto';
|
||||
import { UploadAvatarDto } from './dto/upload-avatar.dto';
|
||||
import { ProfileService } from './profile.service';
|
||||
|
||||
const MAX_AVATAR_SIZE_BYTES = 2 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Deliberately its own top-level path, not nested under /users/:id -
|
||||
* "/users/me" would collide with UsersController's PATCH/GET ":id" route
|
||||
@@ -76,31 +70,12 @@ export class ProfileController {
|
||||
}
|
||||
|
||||
@Post('avatar')
|
||||
@ApiConsumes('multipart/form-data')
|
||||
@UseInterceptors(
|
||||
FileInterceptor('file', {
|
||||
limits: { fileSize: MAX_AVATAR_SIZE_BYTES },
|
||||
fileFilter: (_req, file, callback) => {
|
||||
if (!isAllowedAvatarMimeType(file.mimetype)) {
|
||||
callback(
|
||||
new BadRequestException('Nicht unterstützter Dateityp'),
|
||||
false,
|
||||
);
|
||||
return;
|
||||
}
|
||||
callback(null, true);
|
||||
},
|
||||
}),
|
||||
)
|
||||
@HttpCode(204)
|
||||
uploadAvatar(
|
||||
@UploadedFile() file: Express.Multer.File | undefined,
|
||||
@Body() dto: UploadAvatarDto,
|
||||
@CurrentUser() actor: AuthenticatedUser,
|
||||
) {
|
||||
if (!file) {
|
||||
throw new BadRequestException('No file uploaded');
|
||||
}
|
||||
return this.profileService.uploadAvatar(actor.id, file);
|
||||
return this.profileService.uploadAvatar(actor.id, dto.data);
|
||||
}
|
||||
|
||||
@Delete('avatar')
|
||||
|
||||
@@ -178,19 +178,25 @@ describe('ProfileService', () => {
|
||||
});
|
||||
|
||||
describe('uploadAvatar', () => {
|
||||
const file = {
|
||||
buffer: Buffer.from('binary'),
|
||||
originalname: 'me.jpg',
|
||||
mimetype: 'image/jpeg',
|
||||
size: 1234,
|
||||
} as Express.Multer.File;
|
||||
const dataUrl = `data:image/jpeg;base64,${Buffer.from('binary').toString('base64')}`;
|
||||
|
||||
it('rejects a value that is not a data: URL', async () => {
|
||||
await expect(
|
||||
service.uploadAvatar('user-1', 'not-a-data-url'),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
|
||||
it('rejects an unsupported mime type', async () => {
|
||||
const zipDataUrl = dataUrl.replace('image/jpeg', 'application/zip');
|
||||
await expect(
|
||||
service.uploadAvatar('user-1', {
|
||||
...file,
|
||||
mimetype: 'application/zip',
|
||||
}),
|
||||
service.uploadAvatar('user-1', zipDataUrl),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
|
||||
it('rejects a file larger than the 2 MB cap', async () => {
|
||||
const oversized = `data:image/jpeg;base64,${Buffer.alloc(3 * 1024 * 1024).toString('base64')}`;
|
||||
await expect(
|
||||
service.uploadAvatar('user-1', oversized),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
|
||||
@@ -201,7 +207,7 @@ describe('ProfileService', () => {
|
||||
});
|
||||
prisma.user.update.mockResolvedValue({});
|
||||
|
||||
await service.uploadAvatar('user-1', file);
|
||||
await service.uploadAvatar('user-1', dataUrl);
|
||||
|
||||
expect(fs.writeFile).toHaveBeenCalled();
|
||||
expect(fs.unlink).toHaveBeenCalledWith('/uploads/avatars/old.jpg');
|
||||
|
||||
@@ -16,6 +16,7 @@ import { PermissionResolverService } from '../auth/permissions/permission-resolv
|
||||
import { UsersService } from '../users/users.service';
|
||||
import {
|
||||
ALLOWED_AVATAR_MIME_TYPES,
|
||||
MAX_AVATAR_SIZE_BYTES,
|
||||
mimeTypeForExtension,
|
||||
} from './avatar-mime-types';
|
||||
import { UpdateProfileDto } from './dto/update-profile.dto';
|
||||
@@ -141,19 +142,28 @@ export class ProfileService {
|
||||
await this.usersService.deactivate(userId, userId);
|
||||
}
|
||||
|
||||
async uploadAvatar(userId: string, file: Express.Multer.File): Promise<void> {
|
||||
if (!(file.mimetype in ALLOWED_AVATAR_MIME_TYPES)) {
|
||||
async uploadAvatar(userId: string, dataUrl: string): Promise<void> {
|
||||
const match = /^data:(image\/(?:jpeg|png|webp));base64,(.+)$/.exec(dataUrl);
|
||||
if (!match) {
|
||||
throw new BadRequestException('Ungültiges Bildformat');
|
||||
}
|
||||
const [, mimeType, base64] = match;
|
||||
if (!(mimeType in ALLOWED_AVATAR_MIME_TYPES)) {
|
||||
throw new BadRequestException('Nicht unterstützter Dateityp');
|
||||
}
|
||||
const buffer = Buffer.from(base64, 'base64');
|
||||
if (buffer.length > MAX_AVATAR_SIZE_BYTES) {
|
||||
throw new BadRequestException('Datei zu groß (max. 2 MB)');
|
||||
}
|
||||
const user = await this.requireUser(userId);
|
||||
const extension = ALLOWED_AVATAR_MIME_TYPES[file.mimetype];
|
||||
const extension = ALLOWED_AVATAR_MIME_TYPES[mimeType];
|
||||
const directory = avatarStorageRoot();
|
||||
await fs.mkdir(directory, { recursive: true });
|
||||
const avatarPath = path.join(
|
||||
directory,
|
||||
`${crypto.randomUUID()}${extension}`,
|
||||
);
|
||||
await fs.writeFile(avatarPath, file.buffer);
|
||||
await fs.writeFile(avatarPath, buffer);
|
||||
if (user.avatarPath) {
|
||||
await fs.unlink(user.avatarPath).catch(() => undefined);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user