LibreChat/packages/api/src/middleware/balance.spec.ts
Danny Avila 9a210971f5
🛜 refactor: Streamline App Config Usage (#9234)
* WIP: app.locals refactoring

WIP: appConfig

fix: update memory configuration retrieval to use getAppConfig based on user role

fix: update comment for AppConfig interface to clarify purpose

🏷️ refactor: Update tests to use getAppConfig for endpoint configurations

ci: Update AppService tests to initialize app config instead of app.locals

ci: Integrate getAppConfig into remaining tests

refactor: Update multer storage destination to use promise-based getAppConfig and improve error handling in tests

refactor: Rename initializeAppConfig to setAppConfig and update related tests

ci: Mock getAppConfig in various tests to provide default configurations

refactor: Update convertMCPToolsToPlugins to use mcpManager for server configuration and adjust related tests

chore: rename `Config/getAppConfig` -> `Config/app`

fix: streamline OpenAI image tools configuration by removing direct appConfig dependency and using function parameters

chore: correct parameter documentation for imageOutputType in ToolService.js

refactor: remove `getCustomConfig` dependency in config route

refactor: update domain validation to use appConfig for allowed domains

refactor: use appConfig registration property

chore: remove app parameter from AppService invocation

refactor: update AppConfig interface to correct registration and turnstile configurations

refactor: remove getCustomConfig dependency and use getAppConfig in PluginController, multer, and MCP services

refactor: replace getCustomConfig with getAppConfig in STTService, TTSService, and related files

refactor: replace getCustomConfig with getAppConfig in Conversation and Message models, update tempChatRetention functions to use AppConfig type

refactor: update getAppConfig calls in Conversation and Message models to include user role for temporary chat expiration

ci: update related tests

refactor: update getAppConfig call in getCustomConfigSpeech to include user role

fix: update appConfig usage to access allowedDomains from actions instead of registration

refactor: enhance AppConfig to include fileStrategies and update related file strategy logic

refactor: update imports to use normalizeEndpointName from @librechat/api and remove redundant definitions

chore: remove deprecated unused RunManager

refactor: get balance config primarily from appConfig

refactor: remove customConfig dependency for appConfig and streamline loadConfigModels logic

refactor: remove getCustomConfig usage and use app config in file citations

refactor: consolidate endpoint loading logic into loadEndpoints function

refactor: update appConfig access to use endpoints structure across various services

refactor: implement custom endpoints configuration and streamline endpoint loading logic

refactor: update getAppConfig call to include user role parameter

refactor: streamline endpoint configuration and enhance appConfig usage across services

refactor: replace getMCPAuthMap with getUserMCPAuthMap and remove unused getCustomConfig file

refactor: add type annotation for loadedEndpoints in loadEndpoints function

refactor: move /services/Files/images/parse to TS API

chore: add missing FILE_CITATIONS permission to IRole interface

refactor: restructure toolkits to TS API

refactor: separate manifest logic into its own module

refactor: consolidate tool loading logic into a new tools module for startup logic

refactor: move interface config logic to TS API

refactor: migrate checkEmailConfig to TypeScript and update imports

refactor: add FunctionTool interface and availableTools to AppConfig

refactor: decouple caching and DB operations from AppService, make part of consolidated `getAppConfig`

WIP: fix tests

* fix: rebase conflicts

* refactor: remove app.locals references

* refactor: replace getBalanceConfig with getAppConfig in various strategies and middleware

* refactor: replace appConfig?.balance with getBalanceConfig in various controllers and clients

* test: add balance configuration to titleConvo method in AgentClient tests

* chore: remove unused `openai-chat-tokens` package

* chore: remove unused imports in initializeMCPs.js

* refactor: update balance configuration to use getAppConfig instead of getBalanceConfig

* refactor: integrate configMiddleware for centralized configuration handling

* refactor: optimize email domain validation by removing unnecessary async calls

* refactor: simplify multer storage configuration by removing async calls

* refactor: reorder imports for better readability in user.js

* refactor: replace getAppConfig calls with req.config for improved performance

* chore: replace getAppConfig calls with req.config in tests for centralized configuration handling

* chore: remove unused override config

* refactor: add configMiddleware to endpoint route and replace getAppConfig with req.config

* chore: remove customConfig parameter from TTSService constructor

* refactor: pass appConfig from request to processFileCitations for improved configuration handling

* refactor: remove configMiddleware from endpoint route and retrieve appConfig directly in getEndpointsConfig if not in `req.config`

* test: add mockAppConfig to processFileCitations tests for improved configuration handling

* fix: pass req.config to hasCustomUserVars and call without await after synchronous refactor

* fix: type safety in useExportConversation

* refactor: retrieve appConfig using getAppConfig in PluginController and remove configMiddleware from plugins route, to avoid always retrieving when plugins are cached

* chore: change `MongoUser` typedef to `IUser`

* fix: Add `user` and `config` fields to ServerRequest and update JSDoc type annotations from Express.Request to ServerRequest

* fix: remove unused setAppConfig mock from Server configuration tests
2025-08-26 12:10:18 -04:00

653 lines
20 KiB
TypeScript

import mongoose from 'mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';
import { logger, balanceSchema } from '@librechat/data-schemas';
import type { NextFunction, Request as ServerRequest, Response as ServerResponse } from 'express';
import type { IBalance } from '@librechat/data-schemas';
import { createSetBalanceConfig } from './balance';
jest.mock('@librechat/data-schemas', () => ({
...jest.requireActual('@librechat/data-schemas'),
logger: {
error: jest.fn(),
},
}));
let mongoServer: MongoMemoryServer;
let Balance: mongoose.Model<IBalance>;
beforeAll(async () => {
mongoServer = await MongoMemoryServer.create();
const mongoUri = mongoServer.getUri();
Balance = mongoose.models.Balance || mongoose.model('Balance', balanceSchema);
await mongoose.connect(mongoUri);
});
afterAll(async () => {
await mongoose.disconnect();
await mongoServer.stop();
});
beforeEach(async () => {
await mongoose.connection.dropDatabase();
jest.clearAllMocks();
jest.restoreAllMocks();
});
describe('createSetBalanceConfig', () => {
const createMockRequest = (userId: string | mongoose.Types.ObjectId): Partial<ServerRequest> => ({
user: {
_id: userId,
id: userId.toString(),
email: 'test@example.com',
},
});
const createMockResponse = (): Partial<ServerResponse> => ({
status: jest.fn().mockReturnThis(),
json: jest.fn().mockReturnThis(),
});
const mockNext: NextFunction = jest.fn();
describe('Basic Functionality', () => {
test('should create balance record for new user with start balance', async () => {
const userId = new mongoose.Types.ObjectId();
const getAppConfig = jest.fn().mockResolvedValue({
balance: {
enabled: true,
startBalance: 1000,
autoRefillEnabled: true,
refillIntervalValue: 30,
refillIntervalUnit: 'days',
refillAmount: 500,
},
});
const middleware = createSetBalanceConfig({
getAppConfig,
Balance,
});
const req = createMockRequest(userId);
const res = createMockResponse();
await middleware(req as ServerRequest, res as ServerResponse, mockNext);
expect(getAppConfig).toHaveBeenCalled();
expect(mockNext).toHaveBeenCalled();
const balanceRecord = await Balance.findOne({ user: userId });
expect(balanceRecord).toBeTruthy();
expect(balanceRecord?.tokenCredits).toBe(1000);
expect(balanceRecord?.autoRefillEnabled).toBe(true);
expect(balanceRecord?.refillIntervalValue).toBe(30);
expect(balanceRecord?.refillIntervalUnit).toBe('days');
expect(balanceRecord?.refillAmount).toBe(500);
expect(balanceRecord?.lastRefill).toBeInstanceOf(Date);
});
test('should skip if balance config is not enabled', async () => {
const userId = new mongoose.Types.ObjectId();
const getAppConfig = jest.fn().mockResolvedValue({
balance: {
enabled: false,
},
});
const middleware = createSetBalanceConfig({
getAppConfig,
Balance,
});
const req = createMockRequest(userId);
const res = createMockResponse();
await middleware(req as ServerRequest, res as ServerResponse, mockNext);
expect(mockNext).toHaveBeenCalled();
const balanceRecord = await Balance.findOne({ user: userId });
expect(balanceRecord).toBeNull();
});
test('should skip if startBalance is null', async () => {
const userId = new mongoose.Types.ObjectId();
const getAppConfig = jest.fn().mockResolvedValue({
balance: {
enabled: true,
startBalance: null,
},
});
const middleware = createSetBalanceConfig({
getAppConfig,
Balance,
});
const req = createMockRequest(userId);
const res = createMockResponse();
await middleware(req as ServerRequest, res as ServerResponse, mockNext);
expect(mockNext).toHaveBeenCalled();
const balanceRecord = await Balance.findOne({ user: userId });
expect(balanceRecord).toBeNull();
});
test('should handle user._id as string', async () => {
const userId = new mongoose.Types.ObjectId().toString();
const getAppConfig = jest.fn().mockResolvedValue({
balance: {
enabled: true,
startBalance: 1000,
autoRefillEnabled: true,
refillIntervalValue: 30,
refillIntervalUnit: 'days',
refillAmount: 500,
},
});
const middleware = createSetBalanceConfig({
getAppConfig,
Balance,
});
const req = createMockRequest(userId);
const res = createMockResponse();
await middleware(req as ServerRequest, res as ServerResponse, mockNext);
expect(mockNext).toHaveBeenCalled();
const balanceRecord = await Balance.findOne({ user: userId });
expect(balanceRecord).toBeTruthy();
expect(balanceRecord?.tokenCredits).toBe(1000);
});
test('should skip if user is not present in request', async () => {
const getAppConfig = jest.fn().mockResolvedValue({
balance: {
enabled: true,
startBalance: 1000,
autoRefillEnabled: true,
refillIntervalValue: 30,
refillIntervalUnit: 'days',
refillAmount: 500,
},
});
const middleware = createSetBalanceConfig({
getAppConfig,
Balance,
});
const req = {} as ServerRequest;
const res = createMockResponse();
await middleware(req, res as ServerResponse, mockNext);
expect(mockNext).toHaveBeenCalled();
expect(getAppConfig).toHaveBeenCalled();
});
});
describe('Edge Case: Auto-refill without lastRefill', () => {
test('should initialize lastRefill when enabling auto-refill for existing user without lastRefill', async () => {
const userId = new mongoose.Types.ObjectId();
// Create existing balance record without lastRefill
// Note: We need to unset lastRefill after creation since the schema has a default
const doc = await Balance.create({
user: userId,
tokenCredits: 500,
autoRefillEnabled: false,
});
// Remove lastRefill to simulate existing user without it
await Balance.updateOne({ _id: doc._id }, { $unset: { lastRefill: 1 } });
const getAppConfig = jest.fn().mockResolvedValue({
balance: {
enabled: true,
startBalance: 1000,
autoRefillEnabled: true,
refillIntervalValue: 30,
refillIntervalUnit: 'days',
refillAmount: 500,
},
});
const middleware = createSetBalanceConfig({
getAppConfig,
Balance,
});
const req = createMockRequest(userId);
const res = createMockResponse();
const beforeTime = new Date();
await middleware(req as ServerRequest, res as ServerResponse, mockNext);
const afterTime = new Date();
expect(mockNext).toHaveBeenCalled();
const balanceRecord = await Balance.findOne({ user: userId });
expect(balanceRecord).toBeTruthy();
expect(balanceRecord?.tokenCredits).toBe(500); // Should not change existing credits
expect(balanceRecord?.autoRefillEnabled).toBe(true);
expect(balanceRecord?.lastRefill).toBeInstanceOf(Date);
// Verify lastRefill was set to current time
const lastRefillTime = balanceRecord?.lastRefill?.getTime() || 0;
expect(lastRefillTime).toBeGreaterThanOrEqual(beforeTime.getTime());
expect(lastRefillTime).toBeLessThanOrEqual(afterTime.getTime());
});
test('should not update lastRefill if it already exists', async () => {
const userId = new mongoose.Types.ObjectId();
const existingLastRefill = new Date('2024-01-01');
// Create existing balance record with lastRefill
await Balance.create({
user: userId,
tokenCredits: 500,
autoRefillEnabled: true,
refillIntervalValue: 30,
refillIntervalUnit: 'days',
refillAmount: 500,
lastRefill: existingLastRefill,
});
const getAppConfig = jest.fn().mockResolvedValue({
balance: {
enabled: true,
startBalance: 1000,
autoRefillEnabled: true,
refillIntervalValue: 30,
refillIntervalUnit: 'days',
refillAmount: 500,
},
});
const middleware = createSetBalanceConfig({
getAppConfig,
Balance,
});
const req = createMockRequest(userId);
const res = createMockResponse();
await middleware(req as ServerRequest, res as ServerResponse, mockNext);
expect(mockNext).toHaveBeenCalled();
const balanceRecord = await Balance.findOne({ user: userId });
expect(balanceRecord?.lastRefill?.getTime()).toBe(existingLastRefill.getTime());
});
test('should handle existing user with auto-refill enabled but missing lastRefill', async () => {
const userId = new mongoose.Types.ObjectId();
// Create a balance record with auto-refill enabled but missing lastRefill
// This simulates the exact edge case reported by the user
const doc = await Balance.create({
user: userId,
tokenCredits: 500,
autoRefillEnabled: true,
refillIntervalValue: 30,
refillIntervalUnit: 'days',
refillAmount: 500,
});
// Remove lastRefill to simulate the edge case
await Balance.updateOne({ _id: doc._id }, { $unset: { lastRefill: 1 } });
const getAppConfig = jest.fn().mockResolvedValue({
balance: {
enabled: true,
startBalance: 1000,
autoRefillEnabled: true,
refillIntervalValue: 30,
refillIntervalUnit: 'days',
refillAmount: 500,
},
});
const middleware = createSetBalanceConfig({
getAppConfig,
Balance,
});
const req = createMockRequest(userId);
const res = createMockResponse();
await middleware(req as ServerRequest, res as ServerResponse, mockNext);
expect(mockNext).toHaveBeenCalled();
const balanceRecord = await Balance.findOne({ user: userId });
expect(balanceRecord).toBeTruthy();
expect(balanceRecord?.autoRefillEnabled).toBe(true);
expect(balanceRecord?.lastRefill).toBeInstanceOf(Date);
// This should have fixed the issue - user should no longer get the error
});
test('should not set lastRefill when auto-refill is disabled', async () => {
const userId = new mongoose.Types.ObjectId();
const getAppConfig = jest.fn().mockResolvedValue({
balance: {
enabled: true,
startBalance: 1000,
autoRefillEnabled: false,
},
});
const middleware = createSetBalanceConfig({
getAppConfig,
Balance,
});
const req = createMockRequest(userId);
const res = createMockResponse();
await middleware(req as ServerRequest, res as ServerResponse, mockNext);
expect(mockNext).toHaveBeenCalled();
const balanceRecord = await Balance.findOne({ user: userId });
expect(balanceRecord).toBeTruthy();
expect(balanceRecord?.tokenCredits).toBe(1000);
expect(balanceRecord?.autoRefillEnabled).toBe(false);
// lastRefill should have default value from schema
expect(balanceRecord?.lastRefill).toBeInstanceOf(Date);
});
});
describe('Update Scenarios', () => {
test('should update auto-refill settings for existing user', async () => {
const userId = new mongoose.Types.ObjectId();
// Create existing balance record
await Balance.create({
user: userId,
tokenCredits: 500,
autoRefillEnabled: false,
refillIntervalValue: 7,
refillIntervalUnit: 'days',
refillAmount: 100,
});
const getAppConfig = jest.fn().mockResolvedValue({
balance: {
enabled: true,
startBalance: 1000,
autoRefillEnabled: true,
refillIntervalValue: 30,
refillIntervalUnit: 'days',
refillAmount: 500,
},
});
const middleware = createSetBalanceConfig({
getAppConfig,
Balance,
});
const req = createMockRequest(userId);
const res = createMockResponse();
await middleware(req as ServerRequest, res as ServerResponse, mockNext);
const balanceRecord = await Balance.findOne({ user: userId });
expect(balanceRecord?.tokenCredits).toBe(500); // Should not change
expect(balanceRecord?.autoRefillEnabled).toBe(true);
expect(balanceRecord?.refillIntervalValue).toBe(30);
expect(balanceRecord?.refillIntervalUnit).toBe('days');
expect(balanceRecord?.refillAmount).toBe(500);
});
test('should not update if values are already the same', async () => {
const userId = new mongoose.Types.ObjectId();
const lastRefillTime = new Date();
// Create existing balance record with same values
await Balance.create({
user: userId,
tokenCredits: 1000,
autoRefillEnabled: true,
refillIntervalValue: 30,
refillIntervalUnit: 'days',
refillAmount: 500,
lastRefill: lastRefillTime,
});
const getAppConfig = jest.fn().mockResolvedValue({
balance: {
enabled: true,
startBalance: 1000,
autoRefillEnabled: true,
refillIntervalValue: 30,
refillIntervalUnit: 'days',
refillAmount: 500,
},
});
const middleware = createSetBalanceConfig({
getAppConfig,
Balance,
});
const req = createMockRequest(userId);
const res = createMockResponse();
// Spy on Balance.findOneAndUpdate to verify it's not called
const updateSpy = jest.spyOn(Balance, 'findOneAndUpdate');
await middleware(req as ServerRequest, res as ServerResponse, mockNext);
expect(mockNext).toHaveBeenCalled();
expect(updateSpy).not.toHaveBeenCalled();
});
test('should set tokenCredits for user with null tokenCredits', async () => {
const userId = new mongoose.Types.ObjectId();
// Create balance record with null tokenCredits
await Balance.create({
user: userId,
tokenCredits: null,
});
const getAppConfig = jest.fn().mockResolvedValue({
balance: {
enabled: true,
startBalance: 2000,
},
});
const middleware = createSetBalanceConfig({
getAppConfig,
Balance,
});
const req = createMockRequest(userId);
const res = createMockResponse();
await middleware(req as ServerRequest, res as ServerResponse, mockNext);
const balanceRecord = await Balance.findOne({ user: userId });
expect(balanceRecord?.tokenCredits).toBe(2000);
});
});
describe('Error Handling', () => {
test('should handle database errors gracefully', async () => {
const userId = new mongoose.Types.ObjectId();
const getAppConfig = jest.fn().mockResolvedValue({
balance: {
enabled: true,
startBalance: 1000,
autoRefillEnabled: true,
refillIntervalValue: 30,
refillIntervalUnit: 'days',
refillAmount: 500,
},
});
const dbError = new Error('Database error');
// Mock Balance.findOne to throw an error
jest.spyOn(Balance, 'findOne').mockImplementationOnce((() => {
return {
lean: jest.fn().mockRejectedValue(dbError),
};
}) as unknown as mongoose.Model<IBalance>['findOne']);
const middleware = createSetBalanceConfig({
getAppConfig,
Balance,
});
const req = createMockRequest(userId);
const res = createMockResponse();
await middleware(req as ServerRequest, res as ServerResponse, mockNext);
expect(logger.error).toHaveBeenCalledWith('Error setting user balance:', dbError);
expect(mockNext).toHaveBeenCalledWith(dbError);
});
test('should handle getAppConfig errors', async () => {
const userId = new mongoose.Types.ObjectId();
const configError = new Error('Config error');
const getAppConfig = jest.fn().mockRejectedValue(configError);
const middleware = createSetBalanceConfig({
getAppConfig,
Balance,
});
const req = createMockRequest(userId);
const res = createMockResponse();
await middleware(req as ServerRequest, res as ServerResponse, mockNext);
expect(logger.error).toHaveBeenCalledWith('Error setting user balance:', configError);
expect(mockNext).toHaveBeenCalledWith(configError);
});
test('should handle invalid auto-refill configuration', async () => {
const userId = new mongoose.Types.ObjectId();
// Missing required auto-refill fields
const getAppConfig = jest.fn().mockResolvedValue({
balance: {
enabled: true,
startBalance: 1000,
autoRefillEnabled: true,
refillIntervalValue: null, // Invalid
refillIntervalUnit: 'days',
refillAmount: 500,
},
});
const middleware = createSetBalanceConfig({
getAppConfig,
Balance,
});
const req = createMockRequest(userId);
const res = createMockResponse();
await middleware(req as ServerRequest, res as ServerResponse, mockNext);
expect(mockNext).toHaveBeenCalled();
const balanceRecord = await Balance.findOne({ user: userId });
expect(balanceRecord).toBeTruthy();
expect(balanceRecord?.tokenCredits).toBe(1000);
// Auto-refill fields should not be updated due to invalid config
expect(balanceRecord?.autoRefillEnabled).toBe(false);
});
});
describe('Concurrent Updates', () => {
test('should handle concurrent middleware calls for same user', async () => {
const userId = new mongoose.Types.ObjectId();
const getAppConfig = jest.fn().mockResolvedValue({
balance: {
enabled: true,
startBalance: 1000,
autoRefillEnabled: true,
refillIntervalValue: 30,
refillIntervalUnit: 'days',
refillAmount: 500,
},
});
const middleware = createSetBalanceConfig({
getAppConfig,
Balance,
});
const req = createMockRequest(userId);
const res1 = createMockResponse();
const res2 = createMockResponse();
const mockNext1 = jest.fn();
const mockNext2 = jest.fn();
// Run middleware concurrently
await Promise.all([
middleware(req as ServerRequest, res1 as ServerResponse, mockNext1),
middleware(req as ServerRequest, res2 as ServerResponse, mockNext2),
]);
expect(mockNext1).toHaveBeenCalled();
expect(mockNext2).toHaveBeenCalled();
// Should only have one balance record
const balanceRecords = await Balance.find({ user: userId });
expect(balanceRecords).toHaveLength(1);
expect(balanceRecords[0].tokenCredits).toBe(1000);
});
});
describe('Integration with Different refillIntervalUnits', () => {
test.each(['seconds', 'minutes', 'hours', 'days', 'weeks', 'months'])(
'should handle refillIntervalUnit: %s',
async (unit) => {
const userId = new mongoose.Types.ObjectId();
const getAppConfig = jest.fn().mockResolvedValue({
balance: {
enabled: true,
startBalance: 1000,
autoRefillEnabled: true,
refillIntervalValue: 10,
refillIntervalUnit: unit,
refillAmount: 100,
},
});
const middleware = createSetBalanceConfig({
getAppConfig,
Balance,
});
const req = createMockRequest(userId);
const res = createMockResponse();
await middleware(req as ServerRequest, res as ServerResponse, mockNext);
const balanceRecord = await Balance.findOne({ user: userId });
expect(balanceRecord?.refillIntervalUnit).toBe(unit);
expect(balanceRecord?.refillIntervalValue).toBe(10);
expect(balanceRecord?.lastRefill).toBeInstanceOf(Date);
},
);
});
});