Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

🐛 fix(user): limit avatar image uploads to PNG and WebP (#21213)

Bryan0b452a4dc45e
diff --git a/apps/server/src/routers/lambda/user/profile.ts b/apps/server/src/routers/lambda/user/profile.ts
index 4a3db6ddf4d..80cb2e33f43 100644
--- a/apps/server/src/routers/lambda/user/profile.ts
+++ b/apps/server/src/routers/lambda/user/profile.ts
@@ -147,19 +147,12 @@ export const profileRouter = router({
// If it's Base64 data, need to upload to S3
if (input.startsWith('data:image')) {
try {
- // Extract mimeType, e.g., "image/png"
- const prefix = 'data:';
- const semicolonIndex = input.indexOf(';');
- const mimeType =
- semicolonIndex !== -1 ? input.slice(prefix.length, semicolonIndex) : 'image/png';
- const fileType = mimeType.split('/')[1];
-
- // Split string to get the Base64 part
- const commaIndex = input.indexOf(',');
- if (commaIndex === -1) {
- throw new Error('Invalid Base64 data');
+ const prefix = /^data:(image\/(webp|png));base64,/.exec(input);
+ if (!prefix) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'INVALID_AVATAR_IMAGE' });
}
- const base64Data = input.slice(commaIndex + 1);
+ const [, mimeType, fileType] = prefix;
+ const buffer = Buffer.from(input.slice(prefix[0].length), 'base64');
// Create S3 client
const s3 = new FileS3();
@@ -172,9 +165,6 @@ export const profileRouter = router({
const fileName = `${uuidv4()}.${fileType}`;
const filePath = `user/avatar/${ctx.userId}/${fileName}`;
- // Convert Base64 data to Buffer and upload to S3
- const buffer = Buffer.from(base64Data, 'base64');
-
await s3.uploadBuffer(filePath, buffer, mimeType);
// Delete old avatar — defense in depth: only touch keys inside the
@@ -193,6 +183,7 @@ export const profileRouter = router({
return ctx.userModel.updateUser({ avatar: avatarUrl });
} catch (error) {
+ if (error instanceof TRPCError) throw error;
throw new Error(
'Error uploading avatar: ' + (error instanceof Error ? error.message : String(error)),
{ cause: error },
diff --git a/src/app/(backend)/webapi/user/avatar/[id]/[image]/route.ts b/src/app/(backend)/webapi/user/avatar/[id]/[image]/route.ts
index cda2619d285..e5136623a6a 100644
--- a/src/app/(backend)/webapi/user/avatar/[id]/[image]/route.ts
+++ b/src/app/(backend)/webapi/user/avatar/[id]/[image]/route.ts
@@ -42,6 +42,7 @@ export const GET = async (req: Request, segmentData: { params: Params }) => {
return new Response(userAvatar, {
headers: {
'Cache-Control': 'public, max-age=31536000, immutable',
+ 'Content-Security-Policy': "default-src 'none'; sandbox",
'Content-Type': type,
},
status: 200,