2025-05-16 23:18:52 +09:00
|
|
|
const fs = require('fs');
|
|
|
|
|
const request = require('supertest');
|
|
|
|
|
const { MongoMemoryServer } = require('mongodb-memory-server');
|
|
|
|
|
const mongoose = require('mongoose');
|
|
|
|
|
|
2025-08-26 12:10:18 -04:00
|
|
|
jest.mock('~/server/services/Config', () => ({
|
|
|
|
|
loadCustomConfig: jest.fn(() => Promise.resolve({})),
|
|
|
|
|
getAppConfig: jest.fn().mockResolvedValue({
|
|
|
|
|
paths: {
|
|
|
|
|
uploads: '/tmp',
|
|
|
|
|
dist: '/tmp/dist',
|
|
|
|
|
fonts: '/tmp/fonts',
|
|
|
|
|
assets: '/tmp/assets',
|
|
|
|
|
},
|
|
|
|
|
fileStrategy: 'local',
|
|
|
|
|
imageOutputType: 'PNG',
|
|
|
|
|
}),
|
|
|
|
|
setCachedTools: jest.fn(),
|
|
|
|
|
}));
|
|
|
|
|
|
|
|
|
|
jest.mock('~/app/clients/tools', () => ({
|
|
|
|
|
createOpenAIImageTools: jest.fn(() => []),
|
|
|
|
|
createYouTubeTools: jest.fn(() => []),
|
|
|
|
|
manifestToolMap: {},
|
|
|
|
|
toolkits: [],
|
|
|
|
|
}));
|
2025-05-25 23:40:37 -04:00
|
|
|
|
2026-01-01 11:10:56 -05:00
|
|
|
jest.mock('~/config', () => ({
|
|
|
|
|
createMCPServersRegistry: jest.fn(),
|
|
|
|
|
createMCPManager: jest.fn().mockResolvedValue({
|
|
|
|
|
getAppToolFunctions: jest.fn().mockResolvedValue({}),
|
|
|
|
|
}),
|
|
|
|
|
}));
|
|
|
|
|
|
2025-05-16 23:18:52 +09:00
|
|
|
describe('Server Configuration', () => {
|
|
|
|
|
// Increase the default timeout to allow for Mongo cleanup
|
|
|
|
|
jest.setTimeout(30_000);
|
|
|
|
|
|
|
|
|
|
let mongoServer;
|
|
|
|
|
let app;
|
|
|
|
|
|
|
|
|
|
/** Mocked fs.readFileSync for index.html */
|
|
|
|
|
const originalReadFileSync = fs.readFileSync;
|
|
|
|
|
beforeAll(() => {
|
|
|
|
|
fs.readFileSync = function (filepath, options) {
|
|
|
|
|
if (filepath.includes('index.html')) {
|
|
|
|
|
return '<!DOCTYPE html><html><head><title>LibreChat</title></head><body><div id="root"></div></body></html>';
|
|
|
|
|
}
|
|
|
|
|
return originalReadFileSync(filepath, options);
|
|
|
|
|
};
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
afterAll(() => {
|
|
|
|
|
// Restore original fs.readFileSync
|
|
|
|
|
fs.readFileSync = originalReadFileSync;
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
beforeAll(async () => {
|
2025-08-26 12:10:18 -04:00
|
|
|
// Create the required directories and files for the test
|
|
|
|
|
const fs = require('fs');
|
|
|
|
|
const path = require('path');
|
|
|
|
|
|
|
|
|
|
const dirs = ['/tmp/dist', '/tmp/fonts', '/tmp/assets'];
|
|
|
|
|
dirs.forEach((dir) => {
|
|
|
|
|
if (!fs.existsSync(dir)) {
|
|
|
|
|
fs.mkdirSync(dir, { recursive: true });
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
fs.writeFileSync(
|
|
|
|
|
path.join('/tmp/dist', 'index.html'),
|
|
|
|
|
'<!DOCTYPE html><html><head><title>LibreChat</title></head><body><div id="root"></div></body></html>',
|
|
|
|
|
);
|
|
|
|
|
|
2025-05-16 23:18:52 +09:00
|
|
|
mongoServer = await MongoMemoryServer.create();
|
|
|
|
|
process.env.MONGO_URI = mongoServer.getUri();
|
|
|
|
|
process.env.PORT = '0'; // Use a random available port
|
|
|
|
|
app = require('~/server');
|
|
|
|
|
|
|
|
|
|
// Wait for the app to be healthy
|
|
|
|
|
await healthCheckPoll(app);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
afterAll(async () => {
|
|
|
|
|
await mongoServer.stop();
|
|
|
|
|
await mongoose.disconnect();
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should return OK for /health', async () => {
|
|
|
|
|
const response = await request(app).get('/health');
|
|
|
|
|
expect(response.status).toBe(200);
|
|
|
|
|
expect(response.text).toBe('OK');
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should not cache index page', async () => {
|
|
|
|
|
const response = await request(app).get('/');
|
|
|
|
|
expect(response.status).toBe(200);
|
|
|
|
|
expect(response.headers['cache-control']).toBe('no-cache, no-store, must-revalidate');
|
|
|
|
|
expect(response.headers['pragma']).toBe('no-cache');
|
|
|
|
|
expect(response.headers['expires']).toBe('0');
|
|
|
|
|
});
|
2025-07-05 00:51:46 +09:00
|
|
|
|
🚦 fix: 404 JSON Responses for Unmatched API Routes (#11976)
* feat: Implement 404 JSON response for unmatched API routes
- Added middleware to return a 404 JSON response with a message for undefined API routes.
- Updated SPA fallback to serve index.html for non-API unmatched routes.
- Ensured the error handler is positioned correctly as the last middleware in the stack.
* fix: Enhance logging in BaseClient for better token usage tracking
- Updated `getTokenCountForResponse` to log the messageId of the response for improved debugging.
- Enhanced userMessage logging to include messageId, tokenCount, and conversationId for clearer context during token count mapping.
* chore: Improve logging in processAddedConvo for better debugging
- Updated the logging structure in the processAddedConvo function to provide clearer context when processing added conversations.
- Removed redundant logging and enhanced the output to include model, agent ID, and endpoint details for improved traceability.
* chore: Enhance logging in BaseClient for improved token usage tracking
- Added debug logging in the BaseClient to track response token usage, including messageId, model, promptTokens, and completionTokens for better debugging and traceability.
* chore: Enhance logging in MemoryAgent for improved context
- Updated logging in the MemoryAgent to include userId, conversationId, messageId, and provider details for better traceability during memory processing.
- Adjusted log messages to provide clearer context when content is returned or not, aiding in debugging efforts.
* chore: Refactor logging in initializeClient for improved clarity
- Consolidated multiple debug log statements into a single message that provides a comprehensive overview of the tool context being stored for the primary agent, including the number of tools and the size of the tool registry. This enhances traceability and debugging efficiency.
* feat: Implement centralized 404 handling for unmatched API routes
- Introduced a new middleware function `apiNotFound` to standardize 404 JSON responses for undefined API routes.
- Updated the server configuration to utilize the new middleware, enhancing code clarity and maintainability.
- Added tests to ensure correct 404 responses for various non-GET methods and the `/api` root path.
* fix: Enhance logging in apiNotFound middleware for improved safety
- Updated the `apiNotFound` function to sanitize the request path by replacing problematic characters and limiting its length, ensuring safer logging of 404 errors.
* refactor: Move apiNotFound middleware to a separate file for better organization
- Extracted the `apiNotFound` function from the error middleware into its own file, enhancing code organization and maintainability.
- Updated the index file to export the new `notFound` middleware, ensuring it is included in the middleware stack.
* docs: Add comment to clarify usage of unsafeChars regex in notFound middleware
- Included a comment in the notFound middleware file to explain that the unsafeChars regex is safe to reuse with .replace() at the module scope, as it does not retain lastIndex state.
2026-02-27 22:49:54 -05:00
|
|
|
it('should return 404 JSON for undefined API routes', async () => {
|
|
|
|
|
const response = await request(app).get('/api/nonexistent');
|
|
|
|
|
expect(response.status).toBe(404);
|
|
|
|
|
expect(response.body).toEqual({ message: 'Endpoint not found' });
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should return 404 JSON for nested undefined API routes', async () => {
|
|
|
|
|
const response = await request(app).get('/api/nonexistent/nested/path');
|
|
|
|
|
expect(response.status).toBe(404);
|
|
|
|
|
expect(response.body).toEqual({ message: 'Endpoint not found' });
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should return 404 JSON for non-GET methods on undefined API routes', async () => {
|
|
|
|
|
const post = await request(app).post('/api/nonexistent');
|
|
|
|
|
expect(post.status).toBe(404);
|
|
|
|
|
expect(post.body).toEqual({ message: 'Endpoint not found' });
|
|
|
|
|
|
|
|
|
|
const del = await request(app).delete('/api/nonexistent');
|
|
|
|
|
expect(del.status).toBe(404);
|
|
|
|
|
expect(del.body).toEqual({ message: 'Endpoint not found' });
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should return 404 JSON for the /api root path', async () => {
|
|
|
|
|
const response = await request(app).get('/api');
|
|
|
|
|
expect(response.status).toBe(404);
|
|
|
|
|
expect(response.body).toEqual({ message: 'Endpoint not found' });
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
it('should serve SPA HTML for non-API unmatched routes', async () => {
|
|
|
|
|
const response = await request(app).get('/this/does/not/exist');
|
|
|
|
|
expect(response.status).toBe(200);
|
|
|
|
|
expect(response.headers['content-type']).toMatch(/html/);
|
|
|
|
|
});
|
|
|
|
|
|
2025-07-05 00:51:46 +09:00
|
|
|
it('should return 500 for unknown errors via ErrorController', async () => {
|
|
|
|
|
// Testing the error handling here on top of unit tests to ensure the middleware is correctly integrated
|
|
|
|
|
|
|
|
|
|
// Mock MongoDB operations to fail
|
|
|
|
|
const originalFindOne = mongoose.models.User.findOne;
|
|
|
|
|
const mockError = new Error('MongoDB operation failed');
|
|
|
|
|
mongoose.models.User.findOne = jest.fn().mockImplementation(() => {
|
|
|
|
|
throw mockError;
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const response = await request(app).post('/api/auth/login').send({
|
|
|
|
|
email: 'test@example.com',
|
|
|
|
|
password: 'password123',
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
expect(response.status).toBe(500);
|
|
|
|
|
expect(response.text).toBe('An unknown error occurred.');
|
|
|
|
|
} finally {
|
|
|
|
|
// Restore original function
|
|
|
|
|
mongoose.models.User.findOne = originalFindOne;
|
|
|
|
|
}
|
|
|
|
|
});
|
2025-05-16 23:18:52 +09:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// Polls the /health endpoint every 30ms for up to 10 seconds to wait for the server to start completely
|
|
|
|
|
async function healthCheckPoll(app, retries = 0) {
|
|
|
|
|
const maxRetries = Math.floor(10000 / 30); // 10 seconds / 30ms
|
|
|
|
|
try {
|
|
|
|
|
const response = await request(app).get('/health');
|
|
|
|
|
if (response.status === 200) {
|
|
|
|
|
return; // App is healthy
|
|
|
|
|
}
|
2025-08-11 18:49:34 -04:00
|
|
|
} catch {
|
2025-05-16 23:18:52 +09:00
|
|
|
// Ignore connection errors during polling
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (retries < maxRetries) {
|
|
|
|
|
await new Promise((resolve) => setTimeout(resolve, 30));
|
|
|
|
|
await healthCheckPoll(app, retries + 1);
|
|
|
|
|
} else {
|
|
|
|
|
throw new Error('App did not become healthy within 10 seconds.');
|
|
|
|
|
}
|
|
|
|
|
}
|