Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🏷️ fix: Record the Media Type of Saved Images, Not the Declared One (#15606)

Danny Avilaa21c7944eee3
diff --git a/api/server/services/Files/images/resize.js b/api/server/services/Files/images/resize.js
index c2cdaacb63..6cbbb16c53 100644
--- a/api/server/services/Files/images/resize.js
+++ b/api/server/services/Files/images/resize.js
@@ -1,4 +1,5 @@
const sharp = require('sharp');
+const { resolveImageMimeType } = require('@librechat/api');
const { EModelEndpoint } = require('librechat-data-provider');
/**
@@ -10,7 +11,9 @@ const { EModelEndpoint } = require('librechat-data-provider');
* 'high' for a maximum of 768x2000 resolution,
* or a custom object with percentage or px values.
* @param {EModelEndpoint} endpoint - Identifier for specific endpoint handling
- * @returns {Promise<{buffer: Buffer, width: number, height: number}>} An object containing the resized image buffer and its dimensions.
+ * @returns {Promise<{buffer: Buffer, bytes: number, width: number, height: number, type: string | undefined}>}
+ * The resized image buffer, its dimensions, and the media type of the re-encoded bytes.
+ * `type` is `undefined` when sharp reports a format with no media type of its own.
* @throws Will throw an error if the resolution parameter is invalid.
*/
async function resizeImageBuffer(inputBuffer, resolution, endpoint) {
@@ -86,6 +89,7 @@ async function resizeImageBuffer(inputBuffer, resolution, endpoint) {
bytes: resizedMetadata.size,
width: resizedMetadata.width,
height: resizedMetadata.height,
+ type: resolveImageMimeType(resizedMetadata),
};
}
diff --git a/api/server/services/Files/process.js b/api/server/services/Files/process.js
index 325645a28b..c4e7d307b3 100644
--- a/api/server/services/Files/process.js
+++ b/api/server/services/Files/process.js
@@ -1314,7 +1314,14 @@ async function saveBase64Image(
const effectiveResolution = resolution ?? appConfig.fileConfig?.imageGeneration ?? 'high';
const file_id = _file_id ?? v4();
let filename = `${file_id}-${_filename}`;
- const { buffer: inputBuffer, type } = base64ToBuffer(url);
+ const { buffer: inputBuffer, type: declaredType } = base64ToBuffer(url);
+
+ const image = await resizeImageBuffer(inputBuffer, effectiveResolution, endpoint);
+ /** Sharp re-encodes what it resizes, so the bytes being saved are not necessarily in the
+ * format the data URL declared — an SVG arrives here and is rasterized to PNG. The record has
+ * to describe the bytes, because `file.type` is handed to providers verbatim as `media_type`
+ * (Anthropic), `inlineData.mimeType` (Google), and the `data:` prefix (OpenAI). */
+ const type = image.type ?? declaredType;
if (!path.extname(_filename)) {
const extension = mime.getExtension(type);
if (extension) {
@@ -1323,8 +1330,6 @@ async function saveBase64Image(
throw new Error(`Could not determine file extension from MIME type: ${type}`);
}
}
-
- const image = await resizeImageBuffer(inputBuffer, effectiveResolution, endpoint);
const source = getFileStrategy(appConfig, { isImage: true });
const { saveBuffer } = getStrategyFunctions(source);
const filepath = await saveBuffer({
diff --git a/api/server/services/Files/saveBase64Image.spec.js b/api/server/services/Files/saveBase64Image.spec.js
new file mode 100644
index 0000000000..58c6e6b4ab
--- /dev/null
+++ b/api/server/services/Files/saveBase64Image.spec.js
@@ -0,0 +1,103 @@
+const sharp = require('sharp');
+const { resolveImageMimeType } = require('@librechat/api');
+
+jest.mock('~/models', () => ({ createFile: jest.fn(async (doc) => doc) }));
+jest.mock('~/server/utils/getFileStrategy', () => ({
+ getFileStrategy: jest.fn(() => 'local'),
+}));
+jest.mock('~/server/services/Files/strategies', () => ({
+ getStrategyFunctions: jest.fn(() => ({
+ saveBuffer: jest.fn(async ({ fileName }) => `/images/user-1/${fileName}`),
+ })),
+}));
+jest.mock('./retention', () => ({
+ getRetentionExpiry: jest.fn(async () => ({})),
+ getAgentFileRetentionExpiry: jest.fn(async () => ({})),
+}));
+jest.mock('./Audio/STTService', () => ({ STTService: class {} }));
+jest.mock('~/server/controllers/assistants/v2', () => ({
+ addResourceFileId: jest.fn(),
+ deleteResourceFileId: jest.fn(),
+}));
+jest.mock('~/server/controllers/assistants/helpers', () => ({ getOpenAIClient: jest.fn() }));
+jest.mock('~/server/services/Tools/credentials', () => ({ loadAuthValues: jest.fn() }));
+jest.mock('~/server/services/Config', () => ({ checkCapability: jest.fn() }));
+jest.mock('~/server/utils/queue', () => ({ LB_QueueAsyncCall: jest.fn() }));
+
+const db = require('~/models');
+const { saveBase64Image } = require('./process');
+
+const req = {
+ user: { id: 'user-1', tenantId: null },
+ config: { fileConfig: { imageGeneration: 'high' }, paths: {} },
+};
+
+const dataUrl = (mimeType, buffer) => `data:${mimeType};base64,${buffer.toString('base64')}`;
+
+const save = (url) =>
+ saveBase64Image(url, {
+ req,
+ file_id: 'file-1',
+ filename: 'tool_img_abc',
+ endpoint: 'openAI',
+ context: 'image_generation',
+ });
+
+describe('saveBase64Image records the media type of the bytes it saves', () => {
+ it('records PNG for an SVG that sharp rasterizes', async () => {
+ const svg = Buffer.from(
+ '<svg xmlns="http://www.w3.org/2000/svg" width="80" height="40">' +
+ '<rect width="80" height="40" fill="red"/></svg>',
+ );
+
+ const file = await save(dataUrl('image/svg+xml', svg));
+
+ expect(file.type).toBe('image/png');
+ expect(file.filename).toBe('file-1-tool_img_abc.png');
+ expect(db.createFile).toHaveBeenCalledWith(
+ expect.objectContaining({ type: 'image/png' }),
+ true,
+ );
+ });
+
+ it('leaves a genuine PNG labeled as PNG', async () => {
+ const png = await sharp({
+ create: { width: 40, height: 20, channels: 4, background: { r: 1, g: 2, b: 3, alpha: 1 } },
+ })
+ .png()
+ .toBuffer();
+
+ const file = await save(dataUrl('image/png', png));
+
+ expect(file.type).toBe('image/png');
+ expect(file.filename).toBe('file-1-tool_img_abc.png');
+ });
+
+ it('corrects a WebP mislabeled by the producer as PNG', async () => {
+ const webp = await sharp({
+ create: { width: 40, height: 20, channels: 3, background: { r: 1, g: 2, b: 3 } },
+ })
+ .webp()
+ .toBuffer();
+
+ const file = await save(dataUrl('image/png', webp));
+
+ expect(file.type).toBe('image/webp');
+ expect(file.filename).toBe('file-1-tool_img_abc.webp');
+ });
+
+ it('records a type that matches the bytes actually written to storage', async () => {
+ const svg = Buffer.from(
+ '<svg xmlns="http://www.w3.org/2000/svg" width="80" height="40">' +
+ '<rect width="80" height="40" fill="blue"/></svg>',
+ );
+
+ const file = await save(dataUrl('image/svg+xml', svg));
+
+ const { getStrategyFunctions } = require('~/server/services/Files/strategies');
+ const { saveBuffer } = getStrategyFunctions.mock.results.at(-1).value;
+ const savedBuffer = saveBuffer.mock.calls.at(-1)[0].buffer;
+
+ expect(file.type).toBe(resolveImageMimeType(await sharp(savedBuffer).metadata()));
+ });
+});
diff --git a/packages/api/src/files/index.ts b/packages/api/src/files/index.ts
index 8844750cd6..9ca5a4135e 100644
--- a/packages/api/src/files/index.ts
+++ b/packages/api/src/files/index.ts
@@ -7,6 +7,7 @@ export * from './extract';
export * from './documents/crud';
export * from './encode';
export * from './filter';
+export * from './mime';
export * from './mistral/crud';
export * from './ocr';
export * from './parse';
diff --git a/packages/api/src/files/mime.spec.ts b/packages/api/src/files/mime.spec.ts
new file mode 100644
index 0000000000..b841c7f7eb
--- /dev/null
+++ b/packages/api/src/files/mime.spec.ts
@@ -0,0 +1,43 @@
+import sharp from 'sharp';
+import { resolveImageMimeType } from './mime';
+
+describe('resolveImageMimeType', () => {
+ const encode = async (format: 'png' | 'jpeg' | 'webp' | 'gif' | 'tiff'): Promise<Buffer> =>
+ await sharp({
+ create: { width: 8, height: 8, channels: 4, background: { r: 1, g: 2, b: 3, alpha: 1 } },
+ })
+ [format]()
+ .toBuffer();
+
+ it.each([
+ ['png', 'image/png'],
+ ['jpeg', 'image/jpeg'],
+ ['webp', 'image/webp'],
+ ['gif', 'image/gif'],
+ ['tiff', 'image/tiff'],
+ ] as const)('reads %s bytes back as %s', async (format, expected) => {
+ const metadata = await sharp(await encode(format)).metadata();
+ expect(resolveImageMimeType(metadata)).toBe(expected);
+ });
+
+ it('reports the rasterized format for an SVG, not the source format', async () => {
+ const svg = Buffer.from(
+ '<svg xmlns="http://www.w3.org/2000/svg" width="8" height="8">' +
+ '<rect width="8" height="8" fill="red"/></svg>',
+ );
+ const rasterized = await sharp(svg).resize({ width: 8 }).toBuffer();
+
+ expect((await sharp(svg).metadata()).format).toBe('svg');
+ expect(resolveImageMimeType(await sharp(rasterized).metadata())).toBe('image/png');
+ });
+
+ it('distinguishes AVIF from HEIC, which share the heif container', () => {
+ expect(resolveImageMimeType({ format: 'heif', compression: 'av1' })).toBe('image/avif');
+ expect(resolveImageMimeType({ format: 'heif', compression: 'hevc' })).toBe('image/heic');
+ });
+
+ it('returns undefined for a format with no media type of its own', () => {
+ expect(resolveImageMimeType({ format: 'svg' })).toBeUndefined();
+ expect(resolveImageMimeType({ format: 'raw' })).toBeUndefined();
+ });
+});
diff --git a/packages/api/src/files/mime.ts b/packages/api/src/files/mime.ts
new file mode 100644
index 0000000000..a4bebb9fe8
--- /dev/null
+++ b/packages/api/src/files/mime.ts
@@ -0,0 +1,42 @@
+import type { Metadata } from 'sharp';
+
+/**
+ * Media types for the image formats sharp encodes. `heif` covers both AVIF and HEIC, which share
+ * a container and are told apart by the compression inside it, so that entry is resolved
+ * separately rather than being keyed on the format name alone.
+ */
+const SHARP_FORMAT_MIME_TYPES: Readonly<Record<string, string>> = {
+ avif: 'image/avif',
+ gif: 'image/gif',
+ jp2: 'image/jp2',
+ jpeg: 'image/jpeg',
+ jpg: 'image/jpeg',
+ jxl: 'image/jxl',
+ png: 'image/png',
+ tiff: 'image/tiff',
+ webp: 'image/webp',
+};
+
+export type EncodedImageMetadata = Pick<Metadata, 'format' | 'compression'>;
+
+/**
+ * Resolves the media type of an encoded image from what sharp read back out of it.
+ *
+ * Sharp re-encodes whatever it resizes, and the format that comes out need not be the one that
+ * went in — an SVG is rasterized to PNG. Recording a caller's declared type against re-encoded
+ * bytes leaves a file whose `type` misdescribes its own contents, and that type is later handed
+ * to providers verbatim as `media_type`/`mimeType`, so it has to describe the bytes on disk.
+ *
+ * Returns `undefined` when sharp reports a format with no media type of its own, leaving the
+ * caller to decide what to record rather than guessing here.
+ */
+export function resolveImageMimeType(metadata: EncodedImageMetadata): string | undefined {
+ const { format } = metadata;
+ if (!format) {
+ return undefined;
+ }
+ if (format === 'heif') {
+ return metadata.compression === 'av1' ? 'image/avif' : 'image/heic';
+ }
+ return SHARP_FORMAT_MIME_TYPES[format];
+}