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(document): reject unsupported file parser types (#14966)

Inneid6dae46261e6
diff --git a/packages/file-loaders/src/loadFile.test.ts b/packages/file-loaders/src/loadFile.test.ts
index 25e3c63a75a..cea88c799ae 100644
--- a/packages/file-loaders/src/loadFile.test.ts
+++ b/packages/file-loaders/src/loadFile.test.ts
@@ -1,4 +1,6 @@
// @vitest-environment node
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
import path from 'node:path';
import { describe, expect, it, vi } from 'vitest';
@@ -38,12 +40,25 @@ describe('loadFile', () => {
expect(doc.metadata.error).toContain('Failed to access file stats:');
});
- it('falls back to TextLoader for unsupported type and warns', async () => {
+ it('rejects unsupported binary-like file types before text parsing', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
- const doc = await loadFile(fp('test.epub')); // epub is unsupported in current mapping
- expect(warn).toHaveBeenCalled();
- expect(doc.content.length).toBeGreaterThanOrEqual(0);
- warn.mockRestore();
+ const tempDir = await mkdtemp(path.join(tmpdir(), 'lobe-file-loaders-'));
+
+ try {
+ const file = path.join(tempDir, 'archive.zip');
+ await writeFile(file, Buffer.from([80, 75, 3, 4, 0, 0]));
+
+ await expect(loadFile(file)).rejects.toMatchObject({
+ fileType: 'zip',
+ name: 'UnsupportedFileTypeError',
+ });
+ expect(warn).toHaveBeenCalledWith(
+ "No specific loader found for file type 'zip'. Rejecting unsupported file type.",
+ );
+ } finally {
+ warn.mockRestore();
+ await rm(tempDir, { force: true, recursive: true });
+ }
});
it('allows overriding metadata via second parameter', async () => {
diff --git a/packages/file-loaders/src/loadFile.ts b/packages/file-loaders/src/loadFile.ts
index dae0617e4c8..304d45ae9a1 100644
--- a/packages/file-loaders/src/loadFile.ts
+++ b/packages/file-loaders/src/loadFile.ts
@@ -1,5 +1,5 @@
import { stat } from 'node:fs/promises';
-import * as path from 'node:path';
+import path from 'node:path';
import debug from 'debug';
@@ -9,6 +9,16 @@ import { isTextReadableFile } from './utils/isTextReadableFile';
const log = debug('file-loaders:loadFile');
+export class UnsupportedFileTypeError extends Error {
+ fileType: string;
+
+ constructor(fileType: string, filename: string) {
+ super(`Unsupported file type '${fileType || 'unknown'}' for file '${filename}'.`);
+ this.name = 'UnsupportedFileTypeError';
+ this.fileType = fileType;
+ }
+}
+
/**
* Determines the file type based on the filename extension.
* @param filePath The path to the file.
@@ -112,19 +122,19 @@ export const loadFile = async (
const parserType = getFileType(filePath);
log('Parser type determined as:', parserType);
- // Use lazy loading to get the loader class - this prevents heavy dependencies
- // like pdfjs-dist from being loaded until they're actually needed
- const loaderType = parserType ?? 'txt';
- const LoaderClass = await getFileLoader(loaderType);
- log('Selected loader class:', LoaderClass.name);
-
- if (!parserType) {
+ if (!parserType && !fsError) {
console.warn(
- `No specific loader found for file type '${fileType}'. Using default loader (TextLoader) as fallback.`,
+ `No specific loader found for file type '${fileType}'. Rejecting unsupported file type.`,
);
+ throw new UnsupportedFileTypeError(fileType, filename);
}
- let pages: DocumentPage[] = [];
+ // Use lazy loading to get the loader class - this prevents heavy dependencies
+ // like pdfjs-dist from being loaded until they're actually needed
+ const LoaderClass = await getFileLoader(parserType ?? 'txt');
+ log('Selected loader class:', LoaderClass.name);
+
+ let pages: DocumentPage[];
let aggregatedContent = '';
let loaderError: string | undefined;
let aggregationError: string | undefined;
diff --git a/src/locales/default/chat.ts b/src/locales/default/chat.ts
index eb083e03312..a19ac69d27b 100644
--- a/src/locales/default/chat.ts
+++ b/src/locales/default/chat.ts
@@ -846,6 +846,8 @@ export default {
'upload.preview.prepareTasks': 'Preparing chunks...',
'upload.preview.status.pending': 'Preparing to upload...',
'upload.preview.status.processing': 'Processing file...',
+ 'upload.validation.unsupportedFileType':
+ 'Unsupported file type: {{files}}. Supported images: JPG, PNG, GIF, WebP. Supported documents include PDF, Word, Excel, PowerPoint, Markdown, text, CSV, JSON, and code files.',
'upload.validation.videoSizeExceeded':
'Video file size must not exceed 20MB. Current file size is {{actualSize}}.',
'viewMode.fullWidth': 'Full Width',
diff --git a/src/server/services/document/__tests__/index.test.ts b/src/server/services/document/__tests__/index.test.ts
index fa10c357549..d4d9c8519a1 100644
--- a/src/server/services/document/__tests__/index.test.ts
+++ b/src/server/services/document/__tests__/index.test.ts
@@ -1,4 +1,5 @@
import { type LobeChatDatabase } from '@lobechat/database';
+import { TRPCError } from '@trpc/server';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { DocumentModel } from '@/database/models/document';
@@ -14,12 +15,21 @@ vi.mock('../../file');
vi.mock('../history');
vi.mock('@lobechat/file-loaders', () => ({
loadFile: vi.fn(),
+ UnsupportedFileTypeError: class UnsupportedFileTypeError extends Error {
+ fileType: string;
+
+ constructor(fileType: string, filename: string) {
+ super(`Unsupported file type '${fileType || 'unknown'}' for file '${filename}'.`);
+ this.name = 'UnsupportedFileTypeError';
+ this.fileType = fileType;
+ }
+ },
}));
vi.mock('debug', () => ({
default: () => vi.fn(),
}));
-const { loadFile } = await import('@lobechat/file-loaders');
+const { loadFile, UnsupportedFileTypeError } = await import('@lobechat/file-loaders');
const createEditorDataWithDiffNode = () => ({
root: {
@@ -1067,6 +1077,23 @@ describe('DocumentService', () => {
expect(mockCleanup).toHaveBeenCalled();
});
+ it('should surface unsupported file types as BAD_REQUEST', async () => {
+ vi.mocked(loadFile).mockRejectedValue(new UnsupportedFileTypeError('zip', 'archive.zip'));
+
+ try {
+ await service.parseFile('file-1');
+ throw new Error('parseFile should reject unsupported file types');
+ } catch (error) {
+ expect(error).toBeInstanceOf(TRPCError);
+ expect(error).toMatchObject({
+ code: 'BAD_REQUEST',
+ message: "Unsupported file type 'zip' for file 'archive.zip'.",
+ });
+ }
+
+ expect(mockCleanup).toHaveBeenCalled();
+ });
+
it('should NOT strip page tags in parseFile (unlike parseDocument)', async () => {
const contentWithPageTags =
'<page number="1">First page</page><page number="2">Second page</page>';
diff --git a/src/server/services/document/index.ts b/src/server/services/document/index.ts
index b6ff385e037..f31873e67c8 100644
--- a/src/server/services/document/index.ts
+++ b/src/server/services/document/index.ts
@@ -1,7 +1,8 @@
import { type LobeChatDatabase } from '@lobechat/database';
import { type DocumentItem } from '@lobechat/database/schemas';
import { documents, files } from '@lobechat/database/schemas';
-import { loadFile } from '@lobechat/file-loaders';
+import { loadFile, UnsupportedFileTypeError } from '@lobechat/file-loaders';
+import { TRPCError } from '@trpc/server';
import debug from 'debug';
import { and, eq } from 'drizzle-orm';
import isEqual from 'fast-deep-equal';
@@ -29,6 +30,18 @@ import type {
const log = debug('lobe-chat:service:document');
+const normalizeParseFileError = (error: unknown) => {
+ if (error instanceof UnsupportedFileTypeError) {
+ return new TRPCError({
+ cause: error,
+ code: 'BAD_REQUEST',
+ message: error.message,
+ });
+ }
+
+ return error;
+};
+
export class DocumentService {
userId: string;
private fileModel: FileModel;
@@ -433,8 +446,9 @@ export class DocumentService {
return document as LobeDocument;
} catch (error) {
- console.error(`${logPrefix} File parsing failed:`, error);
- throw error;
+ const parseError = normalizeParseFileError(error);
+ console.error(`${logPrefix} File parsing failed:`, parseError);
+ throw parseError;
} finally {
cleanup();
}
@@ -486,8 +500,9 @@ export class DocumentService {
return document as LobeDocument;
} catch (error) {
- console.error(`${logPrefix} File parsing failed:`, error);
- throw error;
+ const parseError = normalizeParseFileError(error);
+ console.error(`${logPrefix} File parsing failed:`, parseError);
+ throw parseError;
} finally {
cleanup();
}
diff --git a/src/store/file/slices/chat/action.test.ts b/src/store/file/slices/chat/action.test.ts
index 8d79e72a9ab..504ea222028 100644
--- a/src/store/file/slices/chat/action.test.ts
+++ b/src/store/file/slices/chat/action.test.ts
@@ -1,3 +1,4 @@
+import { toast } from '@lobehub/ui/base-ui';
import { act, renderHook } from '@testing-library/react';
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -5,6 +6,12 @@ import { useFileStore as useStore } from '../../store';
vi.mock('zustand/traditional');
+vi.mock('@lobehub/ui/base-ui', () => ({
+ toast: {
+ error: vi.fn(),
+ },
+}));
+
// Mock necessary modules and functions
vi.mock('@/components/AntdStaticMethods', () => ({
notification: {
@@ -47,4 +54,27 @@ describe('useFileStore:chat', () => {
expect(result.current.chatUploadFileList).toEqual([]);
});
+
+ it('uploadChatFiles should reject unsupported files before upload', async () => {
+ const { result } = renderHook(() => useStore());
+ const uploadWithProgress = vi.fn();
+
+ act(() => {
+ useStore.setState({
+ chatUploadFileList: [],
+ uploadWithProgress: uploadWithProgress as any,
+ });
+ });
+
+ await act(async () => {
+ await result.current.uploadChatFiles([
+ new File(['<svg />'], 'icon.svg', { type: 'image/svg+xml' }),
+ new File(['zip'], 'archive.zip', { type: 'application/zip' }),
+ ]);
+ });
+
+ expect(uploadWithProgress).not.toHaveBeenCalled();
+ expect(result.current.chatUploadFileList).toEqual([]);
+ expect(toast.error).toHaveBeenCalledWith(expect.any(String));
+ });
});
diff --git a/src/store/file/slices/chat/action.ts b/src/store/file/slices/chat/action.ts
index 3834350af70..fd699373bb5 100644
--- a/src/store/file/slices/chat/action.ts
+++ b/src/store/file/slices/chat/action.ts
@@ -1,5 +1,6 @@
import { type ChatContextContent } from '@lobechat/types';
import { COMPRESSIBLE_IMAGE_TYPES, compressImageFile } from '@lobechat/utils/compressImage';
+import { toast } from '@lobehub/ui/base-ui';
import { Buffer } from 'buffer.js';
import { t } from 'i18next';
@@ -18,6 +19,7 @@ import { sleep } from '@/utils/sleep';
import { setNamespace } from '@/utils/storeDebug';
import { type FileStore } from '../../store';
+import { filterSupportedChatUploadFiles } from './uploadGuard';
const n = setNamespace('chat');
@@ -111,9 +113,22 @@ export class FileActionImpl {
const { dispatchChatUploadFileList } = this.#get();
// 0. skip file in blacklist
const filteredFiles = rawFiles.filter((file) => !FILE_UPLOAD_BLACKLIST.includes(file.name));
+ const { supportedFiles, unsupportedFiles } = filterSupportedChatUploadFiles(filteredFiles);
+
+ if (unsupportedFiles.length > 0) {
+ toast.error(
+ t('upload.validation.unsupportedFileType', {
+ files: unsupportedFiles.map((file) => file.name).join(', '),
+ ns: 'chat',
+ }),
+ );
+ }
+
+ if (supportedFiles.length === 0) return;
+
// 1. compress images and add files with base64
const files = await Promise.all(
- filteredFiles.map((file) =>
+ supportedFiles.map((file) =>
COMPRESSIBLE_IMAGE_TYPES.has(file.type) ? compressImageFile(file) : file,
),
);
diff --git a/src/store/file/slices/chat/uploadGuard.test.ts b/src/store/file/slices/chat/uploadGuard.test.ts
new file mode 100644
index 00000000000..92cb7b462ee
--- /dev/null
+++ b/src/store/file/slices/chat/uploadGuard.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, it } from 'vitest';
+
+import { isSupportedChatUploadFile } from './uploadGuard';
+
+describe('isSupportedChatUploadFile', () => {
+ it('accepts supported chat image formats', () => {
+ expect(isSupportedChatUploadFile(new File(['image'], 'image.png', { type: 'image/png' }))).toBe(
+ true,
+ );
+ expect(
+ isSupportedChatUploadFile(new File(['image'], 'image.webp', { type: 'image/webp' })),
+ ).toBe(true);
+ });
+
+ it('rejects unsupported image formats before upload', () => {
+ expect(
+ isSupportedChatUploadFile(new File(['<svg />'], 'icon.svg', { type: 'image/svg+xml' })),
+ ).toBe(false);
+ expect(
+ isSupportedChatUploadFile(new File(['image'], 'photo.heic', { type: 'image/heic' })),
+ ).toBe(false);
+ });
+
+ it('accepts supported document formats', () => {
+ expect(
+ isSupportedChatUploadFile(
+ new File(['document'], 'document.pdf', { type: 'application/pdf' }),
+ ),
+ ).toBe(true);
+ expect(
+ isSupportedChatUploadFile(new File(['{}'], 'data.json', { type: 'application/json' })),
+ ).toBe(true);
+ });
+
+ it('rejects unsupported archive formats before upload', () => {
+ expect(
+ isSupportedChatUploadFile(new File(['zip'], 'archive.zip', { type: 'application/zip' })),
+ ).toBe(false);
+ });
+});
diff --git a/src/store/file/slices/chat/uploadGuard.ts b/src/store/file/slices/chat/uploadGuard.ts
new file mode 100644
index 00000000000..c110d742909
--- /dev/null
+++ b/src/store/file/slices/chat/uploadGuard.ts
@@ -0,0 +1,128 @@
+const SUPPORTED_CHAT_IMAGE_TYPES = new Set([
+ 'image/gif',
+ 'image/jpeg',
+ 'image/jpg',
+ 'image/png',
+ 'image/webp',
+]);
+
+const SUPPORTED_CHAT_IMAGE_EXTENSIONS = new Set(['gif', 'jpeg', 'jpg', 'png', 'webp']);
+
+const SUPPORTED_CHAT_DOCUMENT_EXTENSIONS = new Set([
+ 'bat',
+ 'bash',
+ 'c',
+ 'cfg',
+ 'conf',
+ 'cpp',
+ 'cs',
+ 'csv',
+ 'cts',
+ 'dart',
+ 'db',
+ 'diff',
+ 'doc',
+ 'docx',
+ 'env',
+ 'go',
+ 'gradle',
+ 'groovy',
+ 'h',
+ 'hpp',
+ 'htm',
+ 'html',
+ 'ini',
+ 'java',
+ 'js',
+ 'json',
+ 'json5',
+ 'jsonc',
+ 'jsx',
+ 'kt',
+ 'less',
+ 'log',
+ 'lua',
+ 'markdown',
+ 'md',
+ 'mdx',
+ 'mjs',
+ 'mts',
+ 'patch',
+ 'pdf',
+ 'php',
+ 'properties',
+ 'pptx',
+ 'ps1',
+ 'py',
+ 'rb',
+ 'rs',
+ 'scala',
+ 'scss',
+ 'sh',
+ 'sql',
+ 'svelte',
+ 'svg',
+ 'swift',
+ 'toml',
+ 'ts',
+ 'tsx',
+ 'txt',
+ 'vue',
+ 'xls',
+ 'xlsx',
+ 'xml',
+ 'yaml',
+ 'yml',
+]);
+
+const SUPPORTED_CHAT_DOCUMENT_MIME_TYPES = new Set([
+ 'application/json',
+ 'application/pdf',
+ 'application/vnd.ms-excel',
+ 'application/vnd.ms-powerpoint',
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
+ 'application/msword',
+ 'text/csv',
+ 'text/markdown',
+ 'text/plain',
+]);
+
+const getExtension = (filename: string) => filename.split('.').pop()?.toLowerCase() || '';
+
+export const isSupportedChatUploadFile = (file: File) => {
+ const fileType = file.type.toLowerCase();
+ const extension = getExtension(file.name);
+
+ if (fileType.startsWith('image/')) {
+ return SUPPORTED_CHAT_IMAGE_TYPES.has(fileType);
+ }
+
+ if (!fileType && SUPPORTED_CHAT_IMAGE_EXTENSIONS.has(extension)) return true;
+
+ if (fileType.startsWith('video/')) return true;
+
+ if (fileType.startsWith('audio/')) return false;
+
+ if (extension) return SUPPORTED_CHAT_DOCUMENT_EXTENSIONS.has(extension);
+
+ if (fileType.startsWith('text/')) return true;
+
+ return SUPPORTED_CHAT_DOCUMENT_MIME_TYPES.has(fileType);
+};
+
+export const filterSupportedChatUploadFiles = (files: File[]) => {
+ const supportedFiles: File[] = [];
+ const unsupportedFiles: File[] = [];
+
+ for (const file of files) {
+ if (isSupportedChatUploadFile(file)) {
+ supportedFiles.push(file);
+ } else {
+ unsupportedFiles.push(file);
+ }
+ }
+
+ return { supportedFiles, unsupportedFiles };
+};