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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🔑 perf: Cache JWT Users and Batch Auth-Path Reads (#17466)
Marco Beretta2ad2c1c14bb2
diff --git a/api/server/controllers/agents/__tests__/openai.spec.js b/api/server/controllers/agents/__tests__/openai.spec.jsindex 6695e9d04b..fb0128641c 100644--- a/api/server/controllers/agents/__tests__/openai.spec.js+++ b/api/server/controllers/agents/__tests__/openai.spec.js@@ -179,6 +179,7 @@ jest.mock('@librechat/api', () => ({jest.requireActual('@librechat/api').createFileProvisionRecovery(),getAgentErrorMetadata: (...args) =>jest.requireActual('@librechat/api').getAgentErrorMetadata(...args),+ loadSkillAccess: (...args) => jest.requireActual('@librechat/api').loadSkillAccess(...args),isTemporaryTurn: (...args) => jest.requireActual('@librechat/api').isTemporaryTurn(...args),/* Provisioning moved into this package; the controllers build the callback from it. */createProvisionFilesCallback: () => async () => {},diff --git a/api/server/controllers/agents/__tests__/responses.unit.spec.js b/api/server/controllers/agents/__tests__/responses.unit.spec.jsindex 5d38d8c6c6..a7749c5f66 100644--- a/api/server/controllers/agents/__tests__/responses.unit.spec.js+++ b/api/server/controllers/agents/__tests__/responses.unit.spec.js@@ -202,6 +202,7 @@ jest.mock('@librechat/api', () => ({jest.requireActual('@librechat/api').createFileProvisionRecovery(),getAgentErrorMetadata: (...args) =>jest.requireActual('@librechat/api').getAgentErrorMetadata(...args),+ loadSkillAccess: (...args) => jest.requireActual('@librechat/api').loadSkillAccess(...args),getConversationWriteContext: (...args) =>jest.requireActual('@librechat/api').getConversationWriteContext(...args),isTemporaryTurn: (...args) => jest.requireActual('@librechat/api').isTemporaryTurn(...args),diff --git a/api/server/controllers/agents/openai.js b/api/server/controllers/agents/openai.jsindex fd2fc1f259..18d13e5475 100644--- a/api/server/controllers/agents/openai.js+++ b/api/server/controllers/agents/openai.js@@ -26,6 +26,7 @@ const {createAgentExecutionContext,createMCPRuntimeRequestBody,loadSkillStates,+ loadSkillAccess,sendFinalChunk,buildCompletionUsage,createSafeUser,@@ -600,27 +601,14 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {const resolveLinkedInstructions = getLinkedInstructionsResolver();const skillsCapabilityEnabled = enabledCapabilities.has(AgentCapabilities.skills);const ephemeralSkillsToggle = request.ephemeralAgent?.skills === true;- const accessibleSkillIds = skillsCapabilityEnabled- ? withDeploymentSkillIds(- await findAccessibleResources({- userId: principal.userId,- role: principal.role,- resourceType: ResourceType.SKILL,- requiredPermissions: PermissionBits.VIEW,- }),- )- : [];- const editableSkillIds = skillsCapabilityEnabled- ? await findAccessibleResources({- userId: principal.userId,- role: principal.role,- resourceType: ResourceType.SKILL,- requiredPermissions: PermissionBits.EDIT,- })- : [];- const skillCreateAllowed = skillsCapabilityEnabled- ? await getSkillToolDeps().canCreateSkill({ req })- : false;+ const { accessibleSkillIds, editableSkillIds, skillCreateAllowed } = await loadSkillAccess(+ { enabled: skillsCapabilityEnabled, userId: principal.userId, role: principal.role },+ {+ findAccessibleResources,+ withDeploymentSkillIds,+ canCreateSkill: () => getSkillToolDeps().canCreateSkill({ req }),+ },+ );const { skillStates, defaultActiveOnShare } = await loadSkillStates({userId: principal.userId,diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.jsindex ec16419164..0803fe1774 100644--- a/api/server/controllers/agents/responses.js+++ b/api/server/controllers/agents/responses.js@@ -24,6 +24,7 @@ const {createSafeUser,initializeAgent,loadSkillStates,+ loadSkillAccess,getBalanceConfig,injectSkillPrimes,extractManualSkills,@@ -855,27 +856,14 @@ const executeResponse = async (envelope, { req, res }) => {const resolveLinkedInstructions = getLinkedInstructionsResolver();const skillsCapabilityEnabled = enabledCapabilities.has(AgentCapabilities.skills);const ephemeralSkillsToggle = request.ephemeralAgent?.skills === true;- const accessibleSkillIds = skillsCapabilityEnabled- ? withDeploymentSkillIds(- await findAccessibleResources({- userId: principal.userId,- role: principal.role,- resourceType: ResourceType.SKILL,- requiredPermissions: PermissionBits.VIEW,- }),- )- : [];- const editableSkillIds = skillsCapabilityEnabled- ? await findAccessibleResources({- userId: principal.userId,- role: principal.role,- resourceType: ResourceType.SKILL,- requiredPermissions: PermissionBits.EDIT,- })- : [];- const skillCreateAllowed = skillsCapabilityEnabled- ? await getSkillToolDeps().canCreateSkill({ req })- : false;+ const { accessibleSkillIds, editableSkillIds, skillCreateAllowed } = await loadSkillAccess(+ { enabled: skillsCapabilityEnabled, userId: principal.userId, role: principal.role },+ {+ findAccessibleResources,+ withDeploymentSkillIds,+ canCreateSkill: () => getSkillToolDeps().canCreateSkill({ req }),+ },+ );const { skillStates, defaultActiveOnShare } = await loadSkillStates({userId: principal.userId,diff --git a/api/server/middleware/accessResources/fileAccess.js b/api/server/middleware/accessResources/fileAccess.jsindex 1864db4c45..542134e462 100644--- a/api/server/middleware/accessResources/fileAccess.js+++ b/api/server/middleware/accessResources/fileAccess.js@@ -1,73 +1,8 @@const { logger } = require('@librechat/data-schemas');-const { PermissionBits, hasPermissions, ResourceType } = require('librechat-data-provider');-const { getEffectivePermissions } = require('~/server/services/PermissionService');+const { hasAgentBasedFileAccess } = require('@librechat/api');+const { getResourcePermissionsMap } = require('~/server/services/PermissionService');const { getAgents, getFiles } = require('~/models');-/**- * Checks if user has access to a file through agent permissions- * Files inherit permissions from agents they are attached to.- */-const checkAgentBasedFileAccess = async ({ userId, role, fileId, fileOwner }) => {- try {- const fileOwnerId = fileOwner?.toString();- if (!fileOwnerId) {- return false;- }-- /** Agents that have this file in their tool_resources */- const agentsWithFile = await getAgents({- $or: [- { 'tool_resources.execute_code.file_ids': fileId },- { 'tool_resources.file_search.file_ids': fileId },- { 'tool_resources.image_edit.file_ids': fileId },- { 'tool_resources.context.file_ids': fileId },- { 'tool_resources.ocr.file_ids': fileId },- ],- });-- if (!agentsWithFile || agentsWithFile.length === 0) {- return false;- }-- const userIdStr = userId.toString();- for (const agent of agentsWithFile) {- const agentAuthorId = agent.author?.toString();- if (!agentAuthorId) {- continue;- }-- if (agentAuthorId === userIdStr) {- logger.debug(`[fileAccess] User is author of agent ${agent.id}`);- return true;- }-- try {- const permissions = await getEffectivePermissions({- userId,- role,- resourceType: ResourceType.AGENT,- resourceId: agent._id || agent.id,- });-- if (hasPermissions(permissions, PermissionBits.VIEW)) {- logger.debug(`[fileAccess] User ${userId} has VIEW permissions on agent ${agent.id}`);- return true;- }- } catch (permissionError) {- logger.warn(- `[fileAccess] Permission check failed for agent ${agent.id}:`,- permissionError.message,- );- }- }-- return false;- } catch (error) {- logger.error('[fileAccess] Error checking agent-based access:', error);- return false;- }-};-const getTenantId = (value) => value?.toString?.() ?? null;const denyFileAccess = (res) =>@@ -124,12 +59,10 @@ const fileAccess = async (req, res, next) => {}/** Agent-based access (file inherits agent permissions) */- const hasAgentAccess = await checkAgentBasedFileAccess({- userId,- role: userRole,- fileId,- fileOwner: file.user,- });+ const hasAgentAccess = await hasAgentBasedFileAccess(+ { userId, role: userRole, fileId, fileOwner: file.user },+ { getAgents, getResourcePermissionsMap },+ );if (hasAgentAccess) {req.fileAccess = { file };return next();diff --git a/api/server/routes/files/preview.spec.js b/api/server/routes/files/preview.spec.jsindex 20ed436837..ea4e812c4d 100644--- a/api/server/routes/files/preview.spec.js+++ b/api/server/routes/files/preview.spec.js@@ -19,6 +19,8 @@ jest.mock('@librechat/api', () => ({refreshS3FileUrls: jest.fn(),resolveUploadErrorMessage: jest.fn(),verifyAgentUploadPermission: jest.fn(),+ hasAgentBasedFileAccess: (...args) =>+ jest.requireActual('@librechat/api').hasAgentBasedFileAccess(...args),}));const mockFindFileById = jest.fn();@@ -55,6 +57,7 @@ jest.mock('~/server/middleware/roles/capabilities', () => ({jest.mock('~/server/services/PermissionService', () => ({checkPermission: jest.fn(() => (_req, _res, next) => next()),getEffectivePermissions: jest.fn().mockResolvedValue(0),+ getResourcePermissionsMap: jest.fn().mockResolvedValue(new Map()),}));jest.mock('~/server/utils/files', () => ({diff --git a/api/server/services/Config/loadAsyncEndpoints.js b/api/server/services/Config/loadAsyncEndpoints.jsindex 5eaf6afb65..bd7a49d6dc 100644--- a/api/server/services/Config/loadAsyncEndpoints.js+++ b/api/server/services/Config/loadAsyncEndpoints.js@@ -1,7 +1,7 @@const path = require('path');const fs = require('fs/promises');const { logger } = require('@librechat/data-schemas');-const { loadServiceKey, isUserProvided } = require('@librechat/api');+const { isServiceKeyAvailable, isUserProvided } = require('@librechat/api');const { config } = require('./EndpointService');const defaultServiceKeyPath = path.join(__dirname, '../../..', 'data', 'auth.json');@@ -42,7 +42,7 @@ async function loadAsyncEndpoints() {if (serviceKeyPath) {try {- serviceKey = await loadServiceKey(serviceKeyPath);+ serviceKey = await isServiceKeyAvailable(serviceKeyPath);} catch (error) {logger.warn('Error loading Google service key', error);serviceKey = null;diff --git a/api/server/services/Config/loadAsyncEndpoints.spec.js b/api/server/services/Config/loadAsyncEndpoints.spec.jsindex 1c63bf4228..08b8de1ba8 100644--- a/api/server/services/Config/loadAsyncEndpoints.spec.js+++ b/api/server/services/Config/loadAsyncEndpoints.spec.js@@ -24,7 +24,7 @@ function mockDependencies() {mockOptionalModule('@librechat/api', () => ({isEnabled: (value) => value === true || value === 'true' || value === '1',isUserProvided: mockIsUserProvided,- loadServiceKey: mockLoadServiceKey,+ isServiceKeyAvailable: mockLoadServiceKey,}));mockOptionalModule('@librechat/data-schemas', () => ({@@ -82,9 +82,8 @@ describe('loadAsyncEndpoints', () => {});it('loads the default Google service key when the default file exists', async () => {- const serviceKey = { project_id: 'test-project' };mockAccess.mockResolvedValue();- mockLoadServiceKey.mockResolvedValue(serviceKey);+ mockLoadServiceKey.mockResolvedValue(true);const loadAsyncEndpoints = loadModule();const result = await loadAsyncEndpoints();@@ -94,8 +93,7 @@ describe('loadAsyncEndpoints', () => {});it('loads an explicitly configured Google service key path without probing the default file', async () => {- const serviceKey = { project_id: 'test-project' };- mockLoadServiceKey.mockResolvedValue(serviceKey);+ mockLoadServiceKey.mockResolvedValue(true);const loadAsyncEndpoints = loadModule({GOOGLE_SERVICE_KEY_FILE: '/secrets/google-service-account.json',});diff --git a/api/server/services/ToolService.js b/api/server/services/ToolService.jsindex 450f9ebbb9..16bdb21fec 100644--- a/api/server/services/ToolService.js+++ b/api/server/services/ToolService.js@@ -26,6 +26,7 @@ const {buildWebSearchDynamicContext,getCodeApiAuthHeaders,getReplayablePendingMCPOAuthStart,+ getReplayablePendingMCPOAuthStarts,getMCPServerNamesFromTools,createMCPOAuthDeferral,buildMCPAuthToolCall,@@ -1423,20 +1424,15 @@ async function loadToolDefinitionsWrapper({/** OAuth discovery must not reconnect (or prompt for) a server whose* definitions the collision filter deliberately rejected. */- for (const serverName of getMCPServerNamesFromTools(defsFilteredTools, mcpServerNames)) {- if (oauthDeferral.hasSignInDecision(serverName)) {- continue;- }-- const pendingOAuthStart = await getReplayablePendingMCPOAuthStart({- flowManager,- userId: req.user.id,- serverName,- });- if (pendingOAuthStart) {- pendingOAuthServers.add(serverName);- pendingOAuthStarts.set(serverName, pendingOAuthStart);- }+ const discoveredOAuthStarts = await getReplayablePendingMCPOAuthStarts({+ flowManager,+ userId: req.user.id,+ serverNames: getMCPServerNamesFromTools(defsFilteredTools, mcpServerNames),+ skip: (serverName) => oauthDeferral.hasSignInDecision(serverName),+ });+ for (const [serverName, pendingOAuthStart] of discoveredOAuthStarts) {+ pendingOAuthServers.add(serverName);+ pendingOAuthStarts.set(serverName, pendingOAuthStart);}if (pendingOAuthServers.size > 0 && (res || streamId)) {diff --git a/api/server/services/start/__tests__/migration.spec.js b/api/server/services/start/__tests__/migration.spec.jsindex efd10acd29..a9fdd658ac 100644--- a/api/server/services/start/__tests__/migration.spec.js+++ b/api/server/services/start/__tests__/migration.spec.js@@ -1,58 +1,43 @@-const mockWarnOnMissingSearchTokens = jest.fn();+const mockCheckStartupMigrations = jest.fn();const mockCheckAgentPermissionsMigration = jest.fn();const mockCheckPromptPermissionsMigration = jest.fn();+const mockWarnOnMissingSearchTokens = jest.fn();+const mockRunAsSystem = jest.fn((fn) => fn());jest.mock('@librechat/data-schemas', () => ({- logger: { error: jest.fn() },- runAsSystem: (fn) => fn(),+ runAsSystem: (fn) => mockRunAsSystem(fn),warnOnMissingSearchTokens: (...args) => mockWarnOnMissingSearchTokens(...args),}));jest.mock('@librechat/api', () => ({- logAgentMigrationWarning: jest.fn(),- logPromptMigrationWarning: jest.fn(),+ checkStartupMigrations: (...args) => mockCheckStartupMigrations(...args),checkAgentPermissionsMigration: (...args) => mockCheckAgentPermissionsMigration(...args),checkPromptPermissionsMigration: (...args) => mockCheckPromptPermissionsMigration(...args),}));jest.mock('~/models', () => ({ findRoleByIdentifier: jest.fn() }));-const { logger } = require('@librechat/data-schemas');+const mongoose = require('mongoose');+const { findRoleByIdentifier } = require('~/models');const { checkMigrations } = require('../migration');-describe('checkMigrations', () => {- it('starts the search token probe while the permission checks are still running', async () => {- let finishAgentCheck;- mockCheckAgentPermissionsMigration.mockReturnValue(- new Promise((resolve) => {- finishAgentCheck = resolve;- }),- );- mockCheckPromptPermissionsMigration.mockResolvedValue({});- mockWarnOnMissingSearchTokens.mockResolvedValue(undefined);-- const done = checkMigrations();- expect(mockWarnOnMissingSearchTokens).toHaveBeenCalledTimes(1);-- finishAgentCheck({});- await done;- expect(mockCheckPromptPermissionsMigration).toHaveBeenCalledTimes(1);+it('runs the startup checks as the system against the app models', async () => {+ mockCheckStartupMigrations.mockImplementationOnce(async (checks) => {+ await checks.probeSearchTokens();+ await checks.checkAgentPermissions();+ await checks.checkPromptPermissions();});-});--it('labels permission check failures and still awaits the search probe', async () => {- const agentError = new Error('Agent check failed');- const promptError = new Error('Prompt check failed');- mockCheckAgentPermissionsMigration.mockRejectedValueOnce(agentError);- mockCheckPromptPermissionsMigration.mockRejectedValueOnce(promptError);- mockWarnOnMissingSearchTokens.mockResolvedValueOnce(undefined);await expect(checkMigrations()).resolves.toBeUndefined();- expect(logger.error).toHaveBeenCalledWith(- '[checkMigrations] Failed to check agent permissions migration:',- agentError,- );- expect(logger.error).toHaveBeenCalledWith(- '[checkMigrations] Failed to check prompt permissions migration:',- promptError,- );+ expect(mockRunAsSystem).toHaveBeenCalledTimes(1);+ expect(mockWarnOnMissingSearchTokens).toHaveBeenCalledWith(mongoose.connection);+ expect(mockCheckAgentPermissionsMigration).toHaveBeenCalledWith({+ mongoose,+ methods: { findRoleByIdentifier },+ AgentModel: mongoose.models.Agent,+ });+ expect(mockCheckPromptPermissionsMigration).toHaveBeenCalledWith({+ mongoose,+ methods: { findRoleByIdentifier },+ PromptGroupModel: mongoose.models.PromptGroup,+ });});diff --git a/api/server/services/start/migration.js b/api/server/services/start/migration.jsindex 497f08083e..138d0d8623 100644--- a/api/server/services/start/migration.js+++ b/api/server/services/start/migration.js@@ -1,8 +1,7 @@const mongoose = require('mongoose');-const { logger, runAsSystem, warnOnMissingSearchTokens } = require('@librechat/data-schemas');+const { runAsSystem, warnOnMissingSearchTokens } = require('@librechat/data-schemas');const {- logAgentMigrationWarning,- logPromptMigrationWarning,+ checkStartupMigrations,checkAgentPermissionsMigration,checkPromptPermissionsMigration,} = require('@librechat/api');@@ -12,35 +11,22 @@ const { findRoleByIdentifier } = require('~/models');* Check if permissions migrations are needed for shared resources* This runs at the end to ensure all systems are initialized*/-async function checkMigrations() {- /** Started first so it overlaps the permission checks; it logs its own failures. */- const searchTokens = warnOnMissingSearchTokens(mongoose.connection);- try {- const agentMigrationResult = await checkAgentPermissionsMigration({- mongoose,- methods: {- findRoleByIdentifier,- },- AgentModel: mongoose.models.Agent,- });- logAgentMigrationWarning(agentMigrationResult);- } catch (error) {- logger.error('[checkMigrations] Failed to check agent permissions migration:', error);- }- try {- const promptMigrationResult = await checkPromptPermissionsMigration({- mongoose,- methods: {- findRoleByIdentifier,- },- PromptGroupModel: mongoose.models.PromptGroup,- });- logPromptMigrationWarning(promptMigrationResult);- } catch (error) {- logger.error('[checkMigrations] Failed to check prompt permissions migration:', error);- }- await searchTokens;-}+const checkMigrations = () =>+ checkStartupMigrations({+ probeSearchTokens: () => warnOnMissingSearchTokens(mongoose.connection),+ checkAgentPermissions: () =>+ checkAgentPermissionsMigration({+ mongoose,+ methods: { findRoleByIdentifier },+ AgentModel: mongoose.models.Agent,+ }),+ checkPromptPermissions: () =>+ checkPromptPermissionsMigration({+ mongoose,+ methods: { findRoleByIdentifier },+ PromptGroupModel: mongoose.models.PromptGroup,+ }),+ });module.exports = {checkMigrations: () => runAsSystem(checkMigrations),diff --git a/api/strategies/jwtStrategy.js b/api/strategies/jwtStrategy.jsindex 989b6d1b07..35e85408e7 100644--- a/api/strategies/jwtStrategy.js+++ b/api/strategies/jwtStrategy.js@@ -1,12 +1,15 @@const { logger, runAsSystem } = require('@librechat/data-schemas');-const { SystemRoles } = require('librechat-data-provider');+const { CacheKeys, SystemRoles } = require('librechat-data-provider');const { Strategy: JwtStrategy, ExtractJwt } = require('passport-jwt');const {- AGENT_TRIGGER_SCOPE,+ loadJwtUser,isTokenRetired,+ getAuthUserDocCacheMode,+ AGENT_TRIGGER_SCOPE,continueAfterBearerRetirement,} = require('@librechat/api');const { getUserById, updateUser } = require('~/models');+const getLogStores = require('~/cache/getLogStores');const AGENT_TRIGGER_ADMISSION_PATHS = ['/api/agents/chat/agents', '/api/agents/chat/steer/deliver'];@@ -38,13 +41,12 @@ const jwtLogin = () =>done(null, false, { message: 'Agent trigger token is not valid for this endpoint' });return;}- const user = await runAsSystem(() =>- getUserById(- payload?.id,- '-password -__v -totpSecret -backupCodes +agentTriggerDeletionStartedAt',- ),- );- if (user?.agentTriggerDeletionStartedAt != null) {+ const { user, deleting, remember } = await loadJwtUser(payload?.id, {+ getUserById,+ cacheMode: getAuthUserDocCacheMode(),+ getCacheStore: () => getLogStores(CacheKeys.AUTH_USER_DOC),+ });+ if (deleting) {done(null, false, {message: 'Account deletion is in progress',code: 'ACCOUNT_DELETION_IN_PROGRESS',@@ -63,10 +65,12 @@ const jwtLogin = () =>user.id = user._id.toString();/** Absent on the full doc means local user; null skips getUserPrincipals' fallback lookup */user.idOnTheSource ??= null;- if (!user.role) {+ const roleMissing = !user.role;+ if (roleMissing) {user.role = SystemRoles.USER;await runAsSystem(() => updateUser(user.id, { role: user.role }));}+ await remember(roleMissing);done(null, user);},isTokenRetired,diff --git a/api/strategies/jwtStrategy.spec.js b/api/strategies/jwtStrategy.spec.jsindex 0ca5cb6864..638c1b15a9 100644--- a/api/strategies/jwtStrategy.spec.js+++ b/api/strategies/jwtStrategy.spec.js@@ -21,6 +21,8 @@ jest.mock('@librechat/data-schemas', () => ({jest.mock('@librechat/api', () => ({AGENT_TRIGGER_SCOPE: 'agent_trigger',+ loadJwtUser: jest.requireActual('@librechat/api').loadJwtUser,+ getAuthUserDocCacheMode: () => 'off',isTokenRetired: jest.requireActual('@librechat/api').isTokenRetired,continueAfterBearerRetirement: jest.requireActual('@librechat/api').continueAfterBearerRetirement,}));@@ -30,6 +32,8 @@ jest.mock('~/models', () => ({updateUser: jest.fn(),}));+jest.mock('~/cache/getLogStores', () => jest.fn());+const jwtLogin = require('./jwtStrategy');const { getUserById, updateUser } = require('~/models');diff --git a/api/strategies/openIdJwtStrategy.js b/api/strategies/openIdJwtStrategy.jsindex a0e1dcdfb7..2c63028a60 100644--- a/api/strategies/openIdJwtStrategy.js+++ b/api/strategies/openIdJwtStrategy.js@@ -13,7 +13,8 @@ const {normalizeOpenIdIssuer,buildAuthUserDocCacheKey,getAuthUserDocCacheMode,- getCachedAuthUserDoc,+ getCurrentCachedAuthUserDoc,+ isAuthUserAdmissible,getValidOpenIdReuseUserId,invalidateCachedAuthUserDoc,setCachedAuthUserDoc,@@ -180,7 +181,7 @@ const openIdJwtLogin = (openIdConfig) => {authUserCacheMode !== 'off' && authUserCacheKey ? getAuthUserDocCacheStore() : undefined;const cachedUser =authUserCacheMode !== 'off' && authUserCacheStore && authUserCacheKey- ? await getCachedAuthUserDoc(authUserCacheStore, authUserCacheKey)+ ? await getCurrentCachedAuthUserDoc(authUserCacheStore, authUserCacheKey, { findUser }): undefined;const servedCachedUser =@@ -216,7 +217,11 @@ const openIdJwtLogin = (openIdConfig) => {(message) => logger.warn(message),async () => {user.id = user._id.toString();- if (!(await runAsSystem(() => isAgentTriggerPrincipalActive(user.id)))) {+ const admissible = await isAuthUserAdmissible(user.id, {+ fenceChecked: Boolean(servedCachedUser),+ isPrincipalActive: (id) => runAsSystem(() => isAgentTriggerPrincipalActive(id)),+ });+ if (!admissible) {done(null, false, {message: 'Account deletion is in progress',code: 'ACCOUNT_DELETION_IN_PROGRESS',diff --git a/api/strategies/openIdJwtStrategy.spec.js b/api/strategies/openIdJwtStrategy.spec.jsindex 8602e822ac..06db981372 100644--- a/api/strategies/openIdJwtStrategy.spec.js+++ b/api/strategies/openIdJwtStrategy.spec.js@@ -42,7 +42,9 @@ jest.mock('@librechat/api', () => ({normalizeOpenIdIssuer: jest.requireActual('@librechat/api').normalizeOpenIdIssuer,buildAuthUserDocCacheKey: jest.fn(() => 'auth-user-doc-key'),getAuthUserDocCacheMode: jest.fn(() => 'off'),- getCachedAuthUserDoc: jest.fn(),+ getCurrentCachedAuthUserDoc: jest.fn(),+ isAuthUserAdmissible: (...args) =>+ jest.requireActual('@librechat/api').isAuthUserAdmissible(...args),getValidOpenIdReuseUserId: jest.fn(),invalidateCachedAuthUserDoc: jest.fn(),setCachedAuthUserDoc: jest.fn(),@@ -70,7 +72,7 @@ const {buildAuthUserDocCacheKey,findOpenIDUser,getAuthUserDocCacheMode,- getCachedAuthUserDoc,+ getCurrentCachedAuthUserDoc,getValidOpenIdReuseUserId,invalidateCachedAuthUserDoc,setCachedAuthUserDoc,@@ -86,7 +88,7 @@ function resetAuthUserDocCacheMocks() {mockGetLogStores.mockReturnValue(mockAuthUserDocCacheStore);buildAuthUserDocCacheKey.mockReturnValue('auth-user-doc-key');getAuthUserDocCacheMode.mockReturnValue('off');- getCachedAuthUserDoc.mockResolvedValue(undefined);+ getCurrentCachedAuthUserDoc.mockResolvedValue(undefined);getValidOpenIdReuseUserId.mockReturnValue(null);invalidateCachedAuthUserDoc.mockResolvedValue(undefined);setCachedAuthUserDoc.mockResolvedValue(undefined);@@ -601,7 +603,7 @@ describe('openIdJwtStrategy – auth user document cache', () => {expect(findOpenIDUser).toHaveBeenCalled();expect(mockGetLogStores).not.toHaveBeenCalled();- expect(getCachedAuthUserDoc).not.toHaveBeenCalled();+ expect(getCurrentCachedAuthUserDoc).not.toHaveBeenCalled();expect(setCachedAuthUserDoc).not.toHaveBeenCalled();});@@ -615,7 +617,7 @@ describe('openIdJwtStrategy – auth user document cache', () => {tenantId: 'tenant-a',};getAuthUserDocCacheMode.mockReturnValue('on');- getCachedAuthUserDoc.mockResolvedValue(cachedUser);+ getCurrentCachedAuthUserDoc.mockResolvedValue(cachedUser);const { user } = await invokeVerify(req, payload);@@ -635,15 +637,45 @@ describe('openIdJwtStrategy – auth user document cache', () => {expect(invalidateCachedAuthUserDoc).not.toHaveBeenCalled();});- it('rejects a cached OpenID user while account deletion is fenced', async () => {+ it('checks the cached document against the stored user and reads it fully when stale', async () => {+ getAuthUserDocCacheMode.mockReturnValue('on');+ getCurrentCachedAuthUserDoc.mockResolvedValue(undefined);+ findOpenIDUser.mockResolvedValue({ user: { ...baseUser }, error: null, migration: false });++ const { user } = await invokeVerify(req, payload);++ expect(getCurrentCachedAuthUserDoc).toHaveBeenCalledWith(+ mockAuthUserDocCacheStore,+ 'auth-user-doc-key',+ { findUser },+ );+ expect(findOpenIDUser).toHaveBeenCalled();+ expect(user).toMatchObject({ id: 'user-abc' });+ });++ it('serves a cache hit without a second deletion fence read', async () => {mockGetTenantId.mockReturnValue('tenant-a');getAuthUserDocCacheMode.mockReturnValue('on');- getCachedAuthUserDoc.mockResolvedValue({+ getCurrentCachedAuthUserDoc.mockResolvedValue({_id: 'cached-user',role: SystemRoles.USER,provider: 'openid',tenantId: 'tenant-a',});++ const { user } = await invokeVerify(req, payload);++ expect(user).toMatchObject({ id: 'cached-user' });+ expect(findOpenIDUser).not.toHaveBeenCalled();+ expect(isAgentTriggerPrincipalActive).not.toHaveBeenCalled();+ });++ it('rejects an OpenID user read from the database while account deletion is fenced', async () => {+ mockGetTenantId.mockReturnValue('tenant-a');+ getAuthUserDocCacheMode.mockReturnValue('on');+ /** A fenced user fails the freshness check, so the hit falls back to the database. */+ getCurrentCachedAuthUserDoc.mockResolvedValue(undefined);+ findOpenIDUser.mockResolvedValue({ user: { ...baseUser }, error: null, migration: false });isAgentTriggerPrincipalActive.mockResolvedValue(false);const result = await invokeVerify(req, payload);@@ -655,15 +687,14 @@ describe('openIdJwtStrategy – auth user document cache', () => {code: 'ACCOUNT_DELETION_IN_PROGRESS',},});- expect(findOpenIDUser).not.toHaveBeenCalled();expect(mockRunAsSystem).toHaveBeenCalledWith(expect.any(Function));- expect(isAgentTriggerPrincipalActive).toHaveBeenCalledWith('cached-user');+ expect(isAgentTriggerPrincipalActive).toHaveBeenCalledWith('user-abc');expect(setCachedAuthUserDoc).not.toHaveBeenCalled();});it('populates the cache after a miss with the fresh user document', async () => {getAuthUserDocCacheMode.mockReturnValue('on');- getCachedAuthUserDoc.mockResolvedValue(undefined);+ getCurrentCachedAuthUserDoc.mockResolvedValue(undefined);let lookupAt;findOpenIDUser.mockImplementation(async () => {lookupAt = Date.now();@@ -687,7 +718,7 @@ describe('openIdJwtStrategy – auth user document cache', () => {it('rejects a cached user document from another tenant', async () => {mockGetTenantId.mockReturnValue('tenant-b');getAuthUserDocCacheMode.mockReturnValue('on');- getCachedAuthUserDoc.mockResolvedValue({+ getCurrentCachedAuthUserDoc.mockResolvedValue({_id: 'tenant-a-user',role: SystemRoles.ADMIN,provider: 'openid',@@ -721,7 +752,7 @@ describe('openIdJwtStrategy – auth user document cache', () => {it('uses the signed OpenID user id as cache scope before tenant context is available', async () => {getAuthUserDocCacheMode.mockReturnValue('on');getValidOpenIdReuseUserId.mockReturnValue('tenant-a-user');- getCachedAuthUserDoc.mockResolvedValue({+ getCurrentCachedAuthUserDoc.mockResolvedValue({_id: 'tenant-a-user',role: SystemRoles.USER,provider: 'openid',@@ -754,7 +785,7 @@ describe('openIdJwtStrategy – auth user document cache', () => {it('does not cache a lookup result outside the active tenant scope', async () => {mockGetTenantId.mockReturnValue('tenant-b');getAuthUserDocCacheMode.mockReturnValue('on');- getCachedAuthUserDoc.mockResolvedValue(undefined);+ getCurrentCachedAuthUserDoc.mockResolvedValue(undefined);findOpenIDUser.mockResolvedValue({user: { ...baseUser, tenantId: 'tenant-a' },error: null,@@ -883,7 +914,7 @@ describe('openIdJwtStrategy: retired token cutoffs', () => {it('dates the bearer against a cached stamp that came back serialized', async () => {getAuthUserDocCacheMode.mockReturnValue('on');- getCachedAuthUserDoc.mockResolvedValue({+ getCurrentCachedAuthUserDoc.mockResolvedValue({_id: 'cached-user',role: SystemRoles.USER,provider: 'openid',diff --git a/e2e/specs/mock/scenarios/auth-path-reads.spec.ts b/e2e/specs/mock/scenarios/auth-path-reads.spec.tsnew file mode 100644index 0000000000..112136dfdf--- /dev/null+++ b/e2e/specs/mock/scenarios/auth-path-reads.spec.ts@@ -0,0 +1,215 @@+import { ObjectId } from 'mongodb';+import { randomUUID } from 'node:crypto';+import { expect, test } from '@playwright/test';+import type { APIRequestContext } from '@playwright/test';+import { getE2EUser } from '../../../setup/user';+import { withMongo, deleteUserByEmail } from '../db';++const PASSWORD = 'Auth-Path-Reads-1!';++type Account = { email: string; id: string; headers: Record<string, string> };++async function signUp(request: APIRequestContext, label: string): Promise<Account> {+ const email = `${label}-${randomUUID().slice(0, 8)}@example.com`;+ const register = await request.post('/api/auth/register', {+ data: { email, name: label, password: PASSWORD, confirm_password: PASSWORD },+ });+ expect(register.ok()).toBeTruthy();+ const login = await request.post('/api/auth/login', { data: { email, password: PASSWORD } });+ expect(login.ok()).toBeTruthy();+ const { token, user } = (await login.json()) as { token: string; user: { _id: string } };+ return { email, id: user._id, headers: { Authorization: `Bearer ${token}` } };+}++/** An agent authored by `author` with `fileId` attached to its file search resources. */+async function seedAgentWithFile(author: string, fileId: string): Promise<ObjectId> {+ const _id = new ObjectId();+ await withMongo((db) =>+ db.collection('agents').insertOne({+ _id,+ id: `agent_${randomUUID().replace(/-/g, '').slice(0, 21)}`,+ name: 'File access agent',+ provider: 'Mock Provider A',+ model: 'mock-model-a',+ author: new ObjectId(author),+ tools: [],+ tool_resources: { file_search: { file_ids: [fileId] } },+ versions: [],+ createdAt: new Date(),+ updatedAt: new Date(),+ }),+ );+ return _id;+}++async function grantAgentView(userId: string, agentId: ObjectId, grantedBy: string) {+ await withMongo((db) =>+ db.collection('aclentries').insertOne({+ principalType: 'user',+ principalId: new ObjectId(userId),+ principalModel: 'User',+ resourceType: 'agent',+ resourceId: agentId,+ permBits: 1,+ grantedBy: new ObjectId(grantedBy),+ grantedAt: new Date(),+ createdAt: new Date(),+ updatedAt: new Date(),+ }),+ );+}++test.describe('auth path reads', () => {+ test('a file attached to an agent is readable through that agent and refused without it @scenario:agent-attached-file-follows-agent-access', async ({+ playwright,+ baseURL,+ }) => {+ const request = await playwright.request.newContext({ baseURL });+ const emails: string[] = [];+ const fileId = randomUUID();+ const agentIds: ObjectId[] = [];+ try {+ const owner = await signUp(request, 'file-owner');+ const viewer = await signUp(request, 'agent-viewer');+ const author = await signUp(request, 'agent-author');+ const stranger = await signUp(request, 'stranger');+ emails.push(owner.email, viewer.email, author.email, stranger.email);++ await withMongo((db) =>+ db.collection('files').insertOne({+ file_id: fileId,+ user: new ObjectId(owner.id),+ filename: 'shared.txt',+ filepath: `/uploads/${fileId}.txt`,+ type: 'text/plain',+ bytes: 13,+ object: 'file',+ source: 'local',+ text: 'shared secret',+ textFormat: 'text',+ createdAt: new Date(),+ updatedAt: new Date(),+ }),+ );+ /** Two agents carry the file: one shared with the viewer, one authored by the author. */+ const shared = await seedAgentWithFile(owner.id, fileId);+ agentIds.push(shared, await seedAgentWithFile(author.id, fileId));++ const preview = (account: Account) =>+ request.get(`/api/files/${fileId}/preview`, { headers: account.headers });++ expect((await preview(viewer)).status()).toBe(403);+ await grantAgentView(viewer.id, shared, owner.id);++ const viaShare = await preview(viewer);+ expect(viaShare.status()).toBe(200);+ expect(await viaShare.json()).toMatchObject({ file_id: fileId, status: 'ready' });+ expect((await preview(author)).status()).toBe(200);+ expect((await preview(stranger)).status()).toBe(403);+ expect((await preview(owner)).status()).toBe(200);+ } finally {+ await withMongo(async (db) => {+ await db.collection('files').deleteMany({ file_id: fileId });+ await db.collection('agents').deleteMany({ _id: { $in: agentIds } });+ await db.collection('aclentries').deleteMany({ resourceId: { $in: agentIds } });+ });+ for (const email of emails) {+ await deleteUserByEmail(email);+ }+ await request.dispose();+ }+ });++ test('a bearer token authenticates its user on every request of a burst @scenario:jwt-bearer-burst-serves-current-user', async ({+ playwright,+ baseURL,+ }) => {+ const request = await playwright.request.newContext({ baseURL });+ let email = '';+ try {+ const account = await signUp(request, 'jwt-burst');+ email = account.email;+ const responses = await Promise.all(+ Array.from({ length: 5 }, () => request.get('/api/user', { headers: account.headers })),+ );+ for (const response of responses) {+ expect(response.status()).toBe(200);+ expect(await response.json()).toMatchObject({ id: account.id, email });+ }+ } finally {+ if (email) {+ await deleteUserByEmail(email);+ }+ await request.dispose();+ }+ });++ for (const [path, tag] of [+ ['/api/agents/v1/chat/completions', '@scenario:remote-chat-completion-answers-with-skills-on'],+ ['/api/agents/v1/responses', '@scenario:remote-response-answers-with-skills-on'],+ ] as const) {+ test(`a remote agent call to ${path} answers while skills are enabled ${tag}`, async ({+ playwright,+ baseURL,+ }) => {+ const request = await playwright.request.newContext({ baseURL });+ let headers: Record<string, string> = {};+ let agentId = '';+ let keyId = '';+ try {+ const { email, password } = getE2EUser();+ const login = await request.post('/api/auth/login', { data: { email, password } });+ expect(login.ok()).toBeTruthy();+ headers = { Authorization: `Bearer ${((await login.json()) as { token: string }).token}` };+ const agent = await request.post('/api/agents', {+ headers,+ data: {+ name: `Remote skills ${randomUUID().slice(0, 8)}`,+ provider: 'Mock Provider A',+ model: 'mock-model-a',+ model_parameters: {},+ tools: [],+ },+ });+ expect(agent.status()).toBe(201);+ agentId = ((await agent.json()) as { id: string }).id;+ const created = await request.post('/api/api-keys', {+ headers,+ data: { name: 'remote skills' },+ });+ expect(created.status()).toBe(201);+ const apiKey = (await created.json()) as { id: string; key: string };+ keyId = apiKey.id;++ const isResponses = path.endsWith('/responses');+ const response = await request.post(path, {+ headers: { Authorization: `Bearer ${apiKey.key}` },+ data: isResponses+ ? { model: agentId, input: 'Say hello', stream: false }+ : { model: agentId, messages: [{ role: 'user', content: 'Say hello' }], stream: false },+ timeout: 60_000,+ });+ expect(response.status(), await response.text()).toBe(200);+ const body = (await response.json()) as {+ choices?: Array<{ message?: { content?: string } }>;+ output?: unknown[];+ status?: string;+ };+ if (isResponses) {+ expect(body.status).toBe('completed');+ expect(body.output?.length).toBeGreaterThan(0);+ } else {+ expect(body.choices?.[0]?.message?.content).toBeTruthy();+ }+ } finally {+ if (keyId) {+ await request.delete(`/api/api-keys/${keyId}`, { headers, failOnStatusCode: false });+ }+ if (agentId) {+ await request.delete(`/api/agents/${agentId}`, { headers, failOnStatusCode: false });+ }+ await request.dispose();+ }+ });+ }+});diff --git a/packages/api/src/app/index.ts b/packages/api/src/app/index.tsindex b4f2fee381..dc5ace62c5 100644--- a/packages/api/src/app/index.ts+++ b/packages/api/src/app/index.ts@@ -20,3 +20,4 @@ export * from './agents';export { resolveBuildInfo } from './build';export type { BuildInfo } from './build';export { buildPreLoginInterface, withSafePolicyLinks } from './interface';+export * from './migrations';diff --git a/packages/api/src/app/migrations.spec.ts b/packages/api/src/app/migrations.spec.tsnew file mode 100644index 0000000000..f24f1acb1c--- /dev/null+++ b/packages/api/src/app/migrations.spec.ts@@ -0,0 +1,59 @@+import { logger } from '@librechat/data-schemas';+import { checkStartupMigrations } from './migrations';++jest.mock('@librechat/data-schemas', () => ({+ ...jest.requireActual('@librechat/data-schemas'),+ logger: { error: jest.fn(), warn: jest.fn(), info: jest.fn(), debug: jest.fn() },+}));+jest.mock('~/agents/migration', () => ({ logAgentMigrationWarning: jest.fn() }));+jest.mock('~/prompts/migration', () => ({ logPromptMigrationWarning: jest.fn() }));++function makeChecks() {+ return {+ probeSearchTokens: jest.fn(async () => undefined),+ checkAgentPermissions: jest.fn(),+ checkPromptPermissions: jest.fn(),+ };+}++describe('checkStartupMigrations', () => {+ beforeEach(() => jest.clearAllMocks());++ it('starts every check before any of them finishes', async () => {+ const checks = makeChecks();+ let finishAgentCheck: (value: unknown) => void = () => undefined;+ checks.checkAgentPermissions.mockReturnValue(+ new Promise((resolve) => {+ finishAgentCheck = resolve;+ }),+ );+ checks.checkPromptPermissions.mockResolvedValue({});++ const done = checkStartupMigrations(checks);+ expect(checks.probeSearchTokens).toHaveBeenCalledTimes(1);+ expect(checks.checkPromptPermissions).toHaveBeenCalledTimes(1);++ finishAgentCheck({});+ await expect(done).resolves.toBeUndefined();+ });++ it('labels permission check failures without failing startup', async () => {+ const checks = makeChecks();+ const agentError = new Error('Agent check failed');+ const promptError = new Error('Prompt check failed');+ checks.checkAgentPermissions.mockRejectedValueOnce(agentError);+ checks.checkPromptPermissions.mockRejectedValueOnce(promptError);++ await expect(checkStartupMigrations(checks)).resolves.toBeUndefined();++ expect(checks.probeSearchTokens).toHaveBeenCalledTimes(1);+ expect(logger.error).toHaveBeenCalledWith(+ '[checkMigrations] Failed to check agent permissions migration:',+ agentError,+ );+ expect(logger.error).toHaveBeenCalledWith(+ '[checkMigrations] Failed to check prompt permissions migration:',+ promptError,+ );+ });+});diff --git a/packages/api/src/app/migrations.ts b/packages/api/src/app/migrations.tsnew file mode 100644index 0000000000..087c744d61--- /dev/null+++ b/packages/api/src/app/migrations.ts@@ -0,0 +1,35 @@+import { logger } from '@librechat/data-schemas';+import type { PromptMigrationCheckResult } from '~/prompts/migration';+import type { MigrationCheckResult } from '~/agents/migration';+import { logPromptMigrationWarning } from '~/prompts/migration';+import { logAgentMigrationWarning } from '~/agents/migration';++export interface StartupMigrationChecks {+ /** Warns about documents missing search tokens; logs its own failures. */+ probeSearchTokens: () => Promise<void>;+ checkAgentPermissions: () => Promise<MigrationCheckResult>;+ checkPromptPermissions: () => Promise<PromptMigrationCheckResult>;+}++/**+ * Startup dry-run checks: missing search tokens and the agent and prompt permission+ * migrations. The three are independent reads, so they run together; each logs its own+ * failure and none stops the others or startup.+ */+export async function checkStartupMigrations(checks: StartupMigrationChecks): Promise<void> {+ await Promise.all([+ checks.probeSearchTokens(),+ checks+ .checkAgentPermissions()+ .then(logAgentMigrationWarning)+ .catch((error: unknown) => {+ logger.error('[checkMigrations] Failed to check agent permissions migration:', error);+ }),+ checks+ .checkPromptPermissions()+ .then(logPromptMigrationWarning)+ .catch((error: unknown) => {+ logger.error('[checkMigrations] Failed to check prompt permissions migration:', error);+ }),+ ]);+}diff --git a/packages/api/src/auth/index.ts b/packages/api/src/auth/index.tsindex b5cdf47a62..6e26840bd3 100644--- a/packages/api/src/auth/index.ts+++ b/packages/api/src/auth/index.ts@@ -19,6 +19,7 @@ export * from './invite';export * from './codeapi';export * from './openidRoleSync';export * from './userDocCache';+export * from './jwt';export * from './email';export * from './emailChangeStore';export * from './passwordReset';diff --git a/packages/api/src/auth/jwt.integration.spec.ts b/packages/api/src/auth/jwt.integration.spec.tsnew file mode 100644index 0000000000..7cd191af4e--- /dev/null+++ b/packages/api/src/auth/jwt.integration.spec.ts@@ -0,0 +1,135 @@+import mongoose from 'mongoose';+import { MongoMemoryServer } from 'mongodb-memory-server';+import { createMethods, createModels } from '@librechat/data-schemas';+import type { IUser } from '@librechat/data-schemas';+import { AUTH_USER_FRESHNESS_PROJECTION } from './userDocCache';+import { JWT_USER_PROJECTION, loadJwtUser } from './jwt';++/**+ * Cache admission for local JWT bearers against the real user schema and methods: the hidden+ * deletion fence, projections, and the `updatedAt` stamp mongoose writes on every update.+ */++let mongoServer: MongoMemoryServer;+let methods: ReturnType<typeof createMethods>;++/** Round-trips values through JSON, as the Redis-backed store does. */+function makeStore() {+ const values = new Map<string, string>();+ return {+ get: async <T = unknown>(key: string) => {+ const value = values.get(key);+ return (value === undefined ? undefined : JSON.parse(value)) as T | undefined;+ },+ set: async (key: string, value: unknown) => {+ values.set(key, JSON.stringify(value));+ return true;+ },+ delete: async (key: string) => values.delete(key),+ };+}++async function createUser(): Promise<string> {+ const doc = await mongoose.models.User.create({+ email: `jwt-${new mongoose.Types.ObjectId().toString()}@example.com`,+ provider: 'local',+ role: 'USER',+ });+ return doc._id.toString();+}++function makeDeps() {+ const getUserById = jest.fn((userId: string, fields: string) =>+ methods.getUserById(userId, fields),+ );+ return {+ getUserById,+ deps: { cacheMode: 'on' as const, getUserById },+ };+}++let store = makeStore();++const projections = (spy: jest.Mock) => spy.mock.calls.map(([, fields]) => fields);++beforeAll(async () => {+ mongoServer = await MongoMemoryServer.create();+ await mongoose.connect(mongoServer.getUri());+ createModels(mongoose);+ methods = createMethods(mongoose);+});++afterAll(async () => {+ await mongoose.disconnect();+ await mongoServer.stop();+});++beforeEach(() => {+ store = makeStore();+});++function lookup(userId: string, deps: ReturnType<typeof makeDeps>['deps']) {+ /** Read at call time so each test sees its own store. */+ return loadJwtUser(userId, { ...deps, getCacheStore: () => store });+}++describe('loadJwtUser against MongoDB', () => {+ it('serves a burst from the cache after one freshness read per hit', async () => {+ const userId = await createUser();+ const { getUserById, deps } = makeDeps();++ await (await lookup(userId, deps)).remember(false);+ const hit = await lookup(userId, deps);++ expect(hit.user).toMatchObject({ _id: userId, role: 'USER' });+ expect(projections(getUserById)).toEqual([JWT_USER_PROJECTION, AUTH_USER_FRESHNESS_PROJECTION]);+ });++ it('never serves a document cached from a read that raced a credential change', async () => {+ const userId = await createUser();+ const { getUserById, deps } = makeDeps();+ const first = await lookup(userId, deps);++ /** The reset commits (and would evict) before this request writes its cache entry. */+ const changedAt = new Date();+ await methods.updateUser(userId, { credentialsChangedAt: changedAt } as Partial<IUser>);+ await first.remember(false);++ const next = await lookup(userId, deps);+ expect(projections(getUserById)).toEqual([+ JWT_USER_PROJECTION,+ AUTH_USER_FRESHNESS_PROJECTION,+ JWT_USER_PROJECTION,+ ]);+ expect(new Date(next.user?.credentialsChangedAt as Date).getTime()).toBe(changedAt.getTime());+ });++ it('rejects a cached document once a write bypassing updatedAt changes authorization', async () => {+ const userId = await createUser();+ const { deps } = makeDeps();+ await (await lookup(userId, deps)).remember(false);++ /** Same updatedAt, as two writes stamped in one millisecond would leave it. */+ await mongoose.models.User.collection.updateOne(+ { _id: new mongoose.Types.ObjectId(userId) },+ { $set: { role: 'ADMIN' } },+ );++ const next = await lookup(userId, deps);+ expect(next.user).toMatchObject({ role: 'ADMIN' });+ });++ it('falls back to the database read once the hidden deletion fence is set', async () => {+ const userId = await createUser();+ const { deps } = makeDeps();+ await (await lookup(userId, deps)).remember(false);++ await mongoose.models.User.updateOne(+ { _id: userId },+ { $set: { agentTriggerDeletionStartedAt: new Date() } },+ );++ const fenced = await lookup(userId, deps);+ expect(fenced.deleting).toBe(true);+ });+});diff --git a/packages/api/src/auth/jwt.spec.ts b/packages/api/src/auth/jwt.spec.tsnew file mode 100644index 0000000000..ec6ba4bcd1--- /dev/null+++ b/packages/api/src/auth/jwt.spec.ts@@ -0,0 +1,159 @@+import type { IUser } from '@librechat/data-schemas';+import type { AuthUserDocCacheMode } from './userDocCache';+import {+ AUTH_USER_DOC_CACHE_TTL_MS,+ AUTH_USER_FRESHNESS_PROJECTION,+ buildAuthUserDocReverseIndexKey,+} from './userDocCache';+import { JWT_USER_PROJECTION, loadJwtUser } from './jwt';++const UPDATED_AT = new Date('2026-10-20T00:00:00.000Z');++function makeStore() {+ const values = new Map<string, unknown>();+ return {+ values,+ /** Round-trips through JSON, as Redis does, so dates come back as strings. */+ get: async <T = unknown>(key: string) => {+ const value = values.get(key);+ return (value === undefined ? undefined : JSON.parse(JSON.stringify(value))) as T;+ },+ set: jest.fn(async (key: string, value: unknown) => {+ values.set(key, value);+ return true;+ }),+ delete: jest.fn(async (key: string) => values.delete(key)),+ };+}++function makeUser(overrides: Partial<IUser> = {}): IUser {+ return {+ _id: 'user-1',+ role: 'USER',+ email: '[email protected]',+ updatedAt: UPDATED_AT,+ ...overrides,+ } as unknown as IUser;+}++/** `stored` is the database: each read sees whatever it holds at that moment. */+function makeDeps(initial: IUser | null, cacheMode: AuthUserDocCacheMode = 'on') {+ const store = makeStore();+ const db = { stored: initial };+ return {+ store,+ db,+ deps: {+ cacheMode,+ getUserById: jest.fn(async (): Promise<IUser | null> => db.stored),+ getCacheStore: () => store,+ },+ };+}++const fullReads = (getUserById: jest.Mock) =>+ getUserById.mock.calls.filter(([, projection]) => projection === JWT_USER_PROJECTION).length;++describe('loadJwtUser', () => {+ it('reads the user every request while the cache is off', async () => {+ const { deps, store } = makeDeps(makeUser(), 'off');++ const first = await loadJwtUser('user-1', deps);+ await first.remember(false);+ await loadJwtUser('user-1', deps);++ expect(deps.getUserById).toHaveBeenCalledTimes(2);+ expect(deps.getUserById).toHaveBeenCalledWith('user-1', JWT_USER_PROJECTION);+ expect(store.set).not.toHaveBeenCalled();+ });++ it('serves a request burst from the cache after a small freshness read', async () => {+ const { deps, store } = makeDeps(makeUser());++ const first = await loadJwtUser('user-1', deps);+ await first.remember(false);+ const second = await loadJwtUser('user-1', deps);++ expect(fullReads(deps.getUserById)).toBe(1);+ expect(deps.getUserById).toHaveBeenLastCalledWith('user-1', AUTH_USER_FRESHNESS_PROJECTION);+ expect(second.user).toMatchObject({ _id: 'user-1', role: 'USER' });+ expect(second.deleting).toBe(false);+ /** The reverse index lets every user mutation evict this entry. */+ expect(store.values.get(buildAuthUserDocReverseIndexKey('user-1'))).toHaveLength(1);+ });++ it('never serves a document cached from a read that raced a user mutation', async () => {+ const { deps, db } = makeDeps(makeUser());+ const lookup = await loadJwtUser('user-1', deps);++ /** A credential change commits and runs its eviction before this cache write lands. */+ db.stored = makeUser({+ credentialsChangedAt: new Date('2026-10-26T00:00:00.000Z'),+ updatedAt: new Date('2026-10-26T00:00:00.000Z'),+ } as Partial<IUser>);+ await lookup.remember(false);++ const next = await loadJwtUser('user-1', deps);+ expect(fullReads(deps.getUserById)).toBe(2);+ expect(next.user).toMatchObject({ credentialsChangedAt: db.stored.credentialsChangedAt });+ });++ it('falls back to the database when the cached user is fenced or gone', async () => {+ const { deps, db } = makeDeps(makeUser());+ await (await loadJwtUser('user-1', deps)).remember(false);++ db.stored = makeUser({ agentTriggerDeletionStartedAt: new Date('2026-10-01T00:00:00.000Z') });+ const fenced = await loadJwtUser('user-1', deps);+ expect(fenced.deleting).toBe(true);++ db.stored = null;+ const removed = await loadJwtUser('user-1', deps);+ expect(removed.user).toBeNull();+ expect(removed.deleting).toBe(false);+ });++ it('never caches a fenced user', async () => {+ const { deps, store } = makeDeps(+ makeUser({ agentTriggerDeletionStartedAt: new Date('2026-10-01T00:00:00.000Z') }),+ );++ const lookup = await loadJwtUser('user-1', deps);+ await lookup.remember(false);++ expect(lookup.deleting).toBe(true);+ expect(store.set).not.toHaveBeenCalled();+ });++ it('does not cache a document whose lookup outlived the cache window', async () => {+ const { deps, store } = makeDeps(makeUser());+ const start = Date.now();+ const now = jest.spyOn(Date, 'now').mockReturnValue(start);+ /** The read finishes after a mutation could already have evicted the key. */+ deps.getUserById.mockImplementationOnce(async () => {+ now.mockReturnValue(start + AUTH_USER_DOC_CACHE_TTL_MS + 1);+ return makeUser();+ });++ try {+ await (await loadJwtUser('user-1', deps)).remember(false);+ } finally {+ now.mockRestore();+ }++ expect(store.set).not.toHaveBeenCalled();+ });++ it('evicts instead of caching when the caller wrote to the user', async () => {+ const { deps, store } = makeDeps(makeUser({ role: undefined }));++ await (await loadJwtUser('user-1', deps)).remember(true);+ await loadJwtUser('user-1', deps);++ /** Eviction writes its fence marker; the user document itself is never cached. */+ const documentWrites = store.set.mock.calls.filter(+ ([key]) => !String(key).startsWith('auth-user-doc-evicted:'),+ );+ expect(documentWrites).toEqual([]);+ expect(fullReads(deps.getUserById)).toBe(2);+ });+});diff --git a/packages/api/src/auth/jwt.ts b/packages/api/src/auth/jwt.tsnew file mode 100644index 0000000000..de563dd0bb--- /dev/null+++ b/packages/api/src/auth/jwt.ts@@ -0,0 +1,86 @@+import { runAsSystem } from '@librechat/data-schemas';+import type { IUser } from '@librechat/data-schemas';+import type { AuthUserDocCacheMode, AuthUserDocCacheStore, CachedAuthUser } from './userDocCache';+import {+ timeAuthUserLookup,+ setCachedAuthUserDoc,+ getCurrentCachedAuthUserDoc,+ buildAuthUserDocCacheKey,+ invalidateCachedAuthUserDoc,+} from './userDocCache';++/** Fields the JWT bearer path reads; the deletion fence is opt-in on the schema. */+export const JWT_USER_PROJECTION =+ '-password -__v -totpSecret -backupCodes +agentTriggerDeletionStartedAt';++export interface JwtUserLookupDeps {+ /** Resolved by the caller, e.g. from `getAuthUserDocCacheMode()`. */+ cacheMode: AuthUserDocCacheMode;+ getUserById: (userId: string, fieldsToSelect: string) => Promise<IUser | null>;+ getCacheStore: () => AuthUserDocCacheStore;+}++export interface JwtUserLookup {+ user: IUser | CachedAuthUser | null;+ /** True when the account deletion fence is set. */+ deleting: boolean;+ /**+ * Called once the request is accepted: evicts the cached document when the caller wrote to+ * the user, otherwise caches a document that was read from the database.+ */+ remember: (userChanged: boolean) => Promise<void>;+}++const noop = async (): Promise<void> => undefined;++/**+ * Loads the user for a local JWT bearer, serving request bursts from the auth user document+ * cache when the caller's cache mode is on. A cache hit still makes one small read of the+ * stored `updatedAt` and deletion fence, replacing the full document read; when either+ * differs from the cached document, the full read runs as without the cache, so missing and+ * fenced users are told apart exactly as before.+ */+export async function loadJwtUser(userId: string, deps: JwtUserLookupDeps): Promise<JwtUserLookup> {+ const cacheKey =+ deps.cacheMode === 'on'+ ? buildAuthUserDocCacheKey({ strategy: 'jwt', subject: userId })+ : undefined;+ const store = cacheKey ? deps.getCacheStore() : undefined;++ if (store && cacheKey) {+ const cached = await getCurrentCachedAuthUserDoc(store, cacheKey, {+ findUser: ({ _id }, fields) => runAsSystem(() => deps.getUserById(_id, fields)),+ });+ if (cached) {+ return {+ user: cached,+ deleting: false,+ remember: async (userChanged) => {+ if (userChanged) {+ await invalidateCachedAuthUserDoc(store, { userId, cacheKey });+ }+ },+ };+ }+ }++ /** Stamped before the read so a lookup that overlaps an eviction is never cached past it. */+ const { result: user, lookupStartedAt } = await timeAuthUserLookup(() =>+ runAsSystem(() => deps.getUserById(userId, JWT_USER_PROJECTION)),+ );+ const deleting = user?.agentTriggerDeletionStartedAt != null;+ if (!user || deleting || !store || !cacheKey) {+ return { user, deleting, remember: noop };+ }+ return {+ user,+ deleting,+ remember: async (userChanged) => {+ if (userChanged) {+ await invalidateCachedAuthUserDoc(store, { userId, cacheKey });+ return;+ }+ await setCachedAuthUserDoc(store, cacheKey, user, lookupStartedAt);+ },+ };+}diff --git a/packages/api/src/auth/userDocCache.spec.ts b/packages/api/src/auth/userDocCache.spec.tsindex 011f07b4a6..36ca6c36ed 100644--- a/packages/api/src/auth/userDocCache.spec.ts+++ b/packages/api/src/auth/userDocCache.spec.ts@@ -7,6 +7,9 @@ import {buildAuthUserDocReverseIndexKey,getAuthUserDocCacheMode,getCachedAuthUserDoc,+ getCurrentCachedAuthUserDoc,+ isAuthUserAdmissible,+ AUTH_USER_FRESHNESS_PROJECTION,invalidateCachedAuthUserDoc,setCachedAuthUserDoc,timeAuthUserLookup,@@ -499,4 +502,85 @@ describe('auth user document cache helpers', () => {{ error: 'redis unavailable' },);});++ it('serves a cached document only while the stored updatedAt and fence still match', async () => {+ const store = makeStore();+ const updatedAt = '2026-10-20T00:00:00.000Z';+ store.values.set('key', {+ version: 2,+ cachedAt: Date.now(),+ expiresAt: Date.now() + 60_000,+ user: { _id: 'user-1', id: 'user-1', updatedAt },+ });+ const readStored = jest.fn();++ readStored.mockResolvedValueOnce({ _id: 'user-1', updatedAt: new Date(updatedAt) });+ await expect(+ getCurrentCachedAuthUserDoc(store, 'key', { findUser: readStored }),+ ).resolves.toMatchObject({+ _id: 'user-1',+ });+ expect(readStored).toHaveBeenCalledWith({ _id: 'user-1' }, AUTH_USER_FRESHNESS_PROJECTION);++ /** A mutation after the cached read moved updatedAt. */+ readStored.mockResolvedValueOnce({ _id: 'user-1', updatedAt: new Date('2026-10-27') });+ await expect(+ getCurrentCachedAuthUserDoc(store, 'key', { findUser: readStored }),+ ).resolves.toBeUndefined();++ readStored.mockResolvedValueOnce({+ _id: 'user-1',+ updatedAt: new Date(updatedAt),+ agentTriggerDeletionStartedAt: new Date(),+ });+ await expect(+ getCurrentCachedAuthUserDoc(store, 'key', { findUser: readStored }),+ ).resolves.toBeUndefined();++ readStored.mockResolvedValueOnce(null);+ await expect(+ getCurrentCachedAuthUserDoc(store, 'key', { findUser: readStored }),+ ).resolves.toBeUndefined();++ /** A password reset stamped in the same millisecond as the write before it. */+ readStored.mockResolvedValueOnce({+ _id: 'user-1',+ updatedAt: new Date(updatedAt),+ credentialsChangedAt: new Date(updatedAt),+ });+ await expect(+ getCurrentCachedAuthUserDoc(store, 'key', { findUser: readStored }),+ ).resolves.toBeUndefined();++ readStored.mockResolvedValueOnce({+ _id: 'user-1',+ updatedAt: new Date(updatedAt),+ role: 'ADMIN',+ });+ await expect(+ getCurrentCachedAuthUserDoc(store, 'key', { findUser: readStored }),+ ).resolves.toBeUndefined();+ });++ it('skips the freshness read on a cache miss', async () => {+ const readStored = jest.fn();+ await expect(+ getCurrentCachedAuthUserDoc(makeStore(), 'missing', { findUser: readStored }),+ ).resolves.toBeUndefined();+ expect(readStored).not.toHaveBeenCalled();+ });++ it('reads the deletion fence only for users the cache did not vouch for', async () => {+ const isPrincipalActive = jest.fn(async () => false);++ await expect(+ isAuthUserAdmissible('user-1', { fenceChecked: true, isPrincipalActive }),+ ).resolves.toBe(true);+ expect(isPrincipalActive).not.toHaveBeenCalled();++ await expect(+ isAuthUserAdmissible('user-1', { fenceChecked: false, isPrincipalActive }),+ ).resolves.toBe(false);+ expect(isPrincipalActive).toHaveBeenCalledWith('user-1');+ });});diff --git a/packages/api/src/auth/userDocCache.ts b/packages/api/src/auth/userDocCache.tsindex 87b1ee5c0d..4e2869c895 100644--- a/packages/api/src/auth/userDocCache.ts+++ b/packages/api/src/auth/userDocCache.ts@@ -37,7 +37,7 @@ interface CachedAuthUserDoc {user: CachedAuthUser;}-type CachedAuthUser = Omit<Partial<IUser>, '_id'> & {+export type CachedAuthUser = Omit<Partial<IUser>, '_id'> & {_id?: string;id?: string;};@@ -179,6 +179,97 @@ export async function getCachedAuthUserDoc(}}+/** Date fields that retire tokens or record authorization changes. */+const FRESHNESS_DATE_FIELDS = ['updatedAt', 'credentialsChangedAt', 'twoFactorEnrolledAt'] as const;+/** Scalar fields `req.user` authorization reads. */+const FRESHNESS_VALUE_FIELDS = ['role', 'tenantId', 'twoFactorEnabled'] as const;++/** What a cache hit reads to prove the cached document is still the stored one. */+export const AUTH_USER_FRESHNESS_PROJECTION: string = [+ '_id',+ ...FRESHNESS_DATE_FIELDS,+ ...FRESHNESS_VALUE_FIELDS,+ '+agentTriggerDeletionStartedAt',+].join(' ');++type FreshnessFields = Pick<+ IUser,+ | 'agentTriggerDeletionStartedAt'+ | (typeof FRESHNESS_DATE_FIELDS)[number]+ | (typeof FRESHNESS_VALUE_FIELDS)[number]+>;++function toTime(value: unknown): number | undefined {+ if (value == null) {+ return undefined;+ }+ const time = new Date(value as string | number | Date).getTime();+ return Number.isNaN(time) ? undefined : time;+}++/**+ * A cached document is current only while the stored user has no deletion fence and the same+ * `updatedAt` and authorization fields. Every user mutation bumps `updatedAt`, so a document+ * cached from a read that raced a mutation (even one written after that mutation's eviction)+ * is not served on the next hit; the token retirement stamps, role, tenant and two-factor+ * state are compared as well, so a mutation stamped in the same millisecond as the write+ * before it still cannot leave stale authorization in the cache.+ */+export function isCachedAuthUserDocCurrent(+ cached: CachedAuthUser,+ stored: Partial<FreshnessFields> | null | undefined,+): boolean {+ if (!stored || stored.agentTriggerDeletionStartedAt != null) {+ return false;+ }+ return (+ FRESHNESS_DATE_FIELDS.every((field) => toTime(cached[field]) === toTime(stored[field])) &&+ FRESHNESS_VALUE_FIELDS.every((field) => (cached[field] ?? null) === (stored[field] ?? null))+ );+}++export interface CurrentAuthUserDocDeps {+ /** Selects one user by id; called with `AUTH_USER_FRESHNESS_PROJECTION`. */+ findUser: (criteria: { _id: string }, fieldsToSelect: string) => Promise<IUser | null>;+}++/**+ * Reads a cached auth user document and returns it only when it is still current, checked by+ * one small read of the stored user. Anything else, including a cached document without an+ * id, is a miss. A returned document has passed the deletion fence check.+ */+export async function getCurrentCachedAuthUserDoc(+ store: AuthUserDocCacheStore,+ cacheKey: string,+ deps: CurrentAuthUserDocDeps,+): Promise<CachedAuthUser | undefined> {+ const cached = await getCachedAuthUserDoc(store, cacheKey);+ const userId = cached ? getUserId(cached) : undefined;+ if (!cached || !userId) {+ return undefined;+ }+ const stored = await deps.findUser({ _id: userId }, AUTH_USER_FRESHNESS_PROJECTION);+ return isCachedAuthUserDocCurrent(cached, stored) ? cached : undefined;+}++/**+ * Whether an authenticated user may proceed past the account deletion fence. A document served+ * by `getCurrentCachedAuthUserDoc` already read the fence, so only a database-loaded user costs+ * the separate fence read.+ */+export async function isAuthUserAdmissible(+ userId: string,+ {+ fenceChecked,+ isPrincipalActive,+ }: {+ fenceChecked: boolean;+ isPrincipalActive: (userId: string) => Promise<boolean>;+ },+): Promise<boolean> {+ return fenceChecked || isPrincipalActive(userId);+}+/*** Runs the database lookup whose result a cache write may store, and stamps when it began:* `setCachedAuthUserDoc` anchors the document's lifetime to that moment.diff --git a/packages/api/src/files/access.spec.ts b/packages/api/src/files/access.spec.tsnew file mode 100644index 0000000000..0c6562fd1d--- /dev/null+++ b/packages/api/src/files/access.spec.ts@@ -0,0 +1,59 @@+import { PermissionBits, ResourceType } from 'librechat-data-provider';+import { hasAgentBasedFileAccess } from './access';++const params = { userId: 'user-1', role: 'USER', fileId: 'file-1', fileOwner: 'owner-1' };++describe('hasAgentBasedFileAccess', () => {+ it('reads permissions for every shared agent in one batch', async () => {+ const getResourcePermissionsMap = jest.fn(+ async () => new Map([['agent-b', PermissionBits.VIEW]]),+ );+ const deps = {+ getAgents: jest.fn(async () => [+ { _id: 'agent-a', id: 'a', author: 'someone' },+ { _id: 'agent-b', id: 'b', author: 'someone-else' },+ { _id: 'agent-c', id: 'c', author: null },+ ]),+ getResourcePermissionsMap,+ };++ await expect(hasAgentBasedFileAccess(params, deps)).resolves.toBe(true);+ expect(getResourcePermissionsMap).toHaveBeenCalledTimes(1);+ expect(getResourcePermissionsMap).toHaveBeenCalledWith({+ userId: 'user-1',+ role: 'USER',+ resourceType: ResourceType.AGENT,+ resourceIds: ['agent-a', 'agent-b'],+ });+ });++ it('grants authors without a permission read', async () => {+ const getResourcePermissionsMap = jest.fn(async () => new Map<string, number>());+ const deps = {+ getAgents: jest.fn(async () => [{ _id: 'agent-a', id: 'a', author: 'user-1' }]),+ getResourcePermissionsMap,+ };++ await expect(hasAgentBasedFileAccess(params, deps)).resolves.toBe(true);+ expect(getResourcePermissionsMap).not.toHaveBeenCalled();+ });++ it('denies when no shared agent grants VIEW or the permission read fails', async () => {+ const getAgents = jest.fn(async () => [{ _id: 'agent-a', id: 'a', author: 'someone' }]);++ await expect(+ hasAgentBasedFileAccess(params, {+ getAgents,+ getResourcePermissionsMap: async () => new Map([['agent-a', 0]]),+ }),+ ).resolves.toBe(false);+ await expect(+ hasAgentBasedFileAccess(params, {+ getAgents,+ getResourcePermissionsMap: async () => {+ throw new Error('acl down');+ },+ }),+ ).resolves.toBe(false);+ });+});diff --git a/packages/api/src/files/access.ts b/packages/api/src/files/access.tsnew file mode 100644index 0000000000..7cc4e23055--- /dev/null+++ b/packages/api/src/files/access.ts@@ -0,0 +1,106 @@+import { logger } from '@librechat/data-schemas';+import { PermissionBits, ResourceType, hasPermissions } from 'librechat-data-provider';++type Stringable = string | { toString(): string };++export interface FileAccessAgent {+ _id?: Stringable;+ id?: string;+ author?: Stringable | null;+}++export interface AgentFileAccessDeps {+ getAgents: (filter: Record<string, unknown>) => Promise<FileAccessAgent[] | null | undefined>;+ getResourcePermissionsMap: (params: {+ userId: string;+ role?: string;+ resourceType: ResourceType;+ resourceIds: Stringable[];+ }) => Promise<Map<string, number>>;+}++export interface AgentFileAccessParams {+ userId: string;+ role?: string;+ fileId: string;+ fileOwner?: Stringable | null;+}++/**+ * Whether a user reaches a file through an agent it is attached to: as the agent's author, or+ * with VIEW on the agent. Every attached agent's permissions come from one batched ACL read+ * rather than a principal lookup and ACL read per agent. Fails closed.+ */+export async function hasAgentBasedFileAccess(+ { userId, role, fileId, fileOwner }: AgentFileAccessParams,+ deps: AgentFileAccessDeps,+): Promise<boolean> {+ try {+ if (!fileOwner?.toString()) {+ return false;+ }++ const agentsWithFile = await deps.getAgents({+ $or: [+ { 'tool_resources.execute_code.file_ids': fileId },+ { 'tool_resources.file_search.file_ids': fileId },+ { 'tool_resources.image_edit.file_ids': fileId },+ { 'tool_resources.context.file_ids': fileId },+ { 'tool_resources.ocr.file_ids': fileId },+ ],+ });+ if (!agentsWithFile || agentsWithFile.length === 0) {+ return false;+ }++ const userIdStr = userId.toString();+ const sharedAgents: Array<{ agent: FileAccessAgent; resourceId: Stringable }> = [];+ for (const agent of agentsWithFile) {+ const agentAuthorId = agent.author?.toString();+ if (!agentAuthorId) {+ continue;+ }+ if (agentAuthorId === userIdStr) {+ logger.debug(`[fileAccess] User is author of agent ${agent.id}`);+ return true;+ }+ const resourceId = agent._id || agent.id;+ if (resourceId) {+ sharedAgents.push({ agent, resourceId });+ }+ }+ if (sharedAgents.length === 0) {+ return false;+ }++ let permissions: Map<string, number>;+ try {+ permissions = await deps.getResourcePermissionsMap({+ userId,+ role,+ resourceType: ResourceType.AGENT,+ resourceIds: sharedAgents.map(({ resourceId }) => resourceId),+ });+ } catch (permissionError) {+ logger.warn(+ '[fileAccess] Permission check failed for attached agents:',+ permissionError instanceof Error ? permissionError.message : String(permissionError),+ );+ return false;+ }++ const viewable = sharedAgents.find(({ resourceId }) =>+ hasPermissions(permissions.get(resourceId.toString()) ?? 0, PermissionBits.VIEW),+ );+ if (viewable) {+ logger.debug(+ `[fileAccess] User ${userId} has VIEW permissions on agent ${viewable.agent.id}`,+ );+ return true;+ }+ return false;+ } catch (error) {+ logger.error('[fileAccess] Error checking agent-based access:', error);+ return false;+ }+}diff --git a/packages/api/src/files/index.ts b/packages/api/src/files/index.tsindex f778b4bfa7..9afd289620 100644--- a/packages/api/src/files/index.ts+++ b/packages/api/src/files/index.ts@@ -35,3 +35,4 @@ export * from './usage';export * from './validation';export * from './text';export * from './list';+export * from './access';diff --git a/packages/api/src/mcp/oauth/pending.spec.ts b/packages/api/src/mcp/oauth/pending.spec.tsnew file mode 100644index 0000000000..373eac1729--- /dev/null+++ b/packages/api/src/mcp/oauth/pending.spec.ts@@ -0,0 +1,38 @@+import { getReplayablePendingMCPOAuthStarts } from './pending';++describe('getReplayablePendingMCPOAuthStarts', () => {+ it('reads every server at once and keeps request order for pending starts only', async () => {+ const createdAt = Date.now();+ const resolvers: Array<() => void> = [];+ const getFlowState = jest.fn(+ (flowId: string) =>+ new Promise((resolve) => {+ resolvers.push(() =>+ resolve(+ flowId.includes('idle')+ ? null+ : {+ status: 'PENDING',+ createdAt,+ metadata: { authorizationUrl: `https://auth.example.com/${flowId}` },+ },+ ),+ );+ }),+ );++ const result = getReplayablePendingMCPOAuthStarts({+ flowManager: { getFlowState } as never,+ userId: 'user-1',+ serverNames: ['zeta', 'idle', 'skipped', 'alpha'],+ skip: (serverName) => serverName === 'skipped',+ });+ await Promise.resolve();+ expect(getFlowState).toHaveBeenCalledTimes(3);+ resolvers.reverse().forEach((resolve) => resolve());++ const pending = await result;+ expect([...pending.keys()]).toEqual(['zeta', 'alpha']);+ expect(pending.get('zeta')?.authURL).toContain('zeta');+ });+});diff --git a/packages/api/src/mcp/oauth/pending.ts b/packages/api/src/mcp/oauth/pending.tsindex 4e84d5d4e8..d41bca3085 100644--- a/packages/api/src/mcp/oauth/pending.ts+++ b/packages/api/src/mcp/oauth/pending.ts@@ -69,6 +69,35 @@ export async function getReplayablePendingMCPOAuthStart({}}+/**+ * Reads the pending OAuth flows of several servers at once, skipping any `skip` rejects.+ * The result keeps the order of `serverNames`, and holds only servers with a replayable start.+ */+export async function getReplayablePendingMCPOAuthStarts({+ flowManager,+ userId,+ serverNames,+ skip,+}: Omit<ReplayablePendingMCPOAuthStartOptions, 'serverName'> & {+ serverNames: Iterable<string>;+ skip?: (serverName: string) => boolean;+}): Promise<Map<string, PendingOAuthStart>> {+ const names = Array.from(serverNames).filter((serverName) => !skip?.(serverName));+ const starts = await Promise.all(+ names.map((serverName) =>+ getReplayablePendingMCPOAuthStart({ flowManager, userId, serverName }),+ ),+ );+ const pending = new Map<string, PendingOAuthStart>();+ names.forEach((serverName, index) => {+ const start = starts[index];+ if (start) {+ pending.set(serverName, start);+ }+ });+ return pending;+}+type OAuthEndHandler = () => Promise<void>;export class OAuthLifecycleRelay {diff --git a/packages/api/src/skills/access.spec.ts b/packages/api/src/skills/access.spec.tsnew file mode 100644index 0000000000..1f36dd6420--- /dev/null+++ b/packages/api/src/skills/access.spec.ts@@ -0,0 +1,58 @@+import { PermissionBits, ResourceType } from 'librechat-data-provider';+import { loadSkillAccess } from './access';++function makeDeps() {+ return {+ findAccessibleResources: jest.fn(+ async ({ requiredPermissions }: { requiredPermissions: number }) =>+ requiredPermissions === PermissionBits.EDIT ? ['edit-1'] : ['view-1'],+ ),+ withDeploymentSkillIds: jest.fn((ids: string[]) => [...ids, 'deployment-1']),+ canCreateSkill: jest.fn(async () => true),+ };+}++describe('loadSkillAccess', () => {+ it('reads nothing while the skills capability is off', async () => {+ const deps = makeDeps();+ const access = await loadSkillAccess({ enabled: false, userId: 'user-1', role: 'USER' }, deps);++ expect(access).toEqual({+ accessibleSkillIds: [],+ editableSkillIds: [],+ skillCreateAllowed: false,+ });+ expect(deps.findAccessibleResources).not.toHaveBeenCalled();+ expect(deps.canCreateSkill).not.toHaveBeenCalled();+ });++ it('starts the view, edit and create reads together', async () => {+ const deps = makeDeps();+ let release: () => void = () => undefined;+ const gate = new Promise<void>((resolve) => {+ release = resolve;+ });+ deps.findAccessibleResources.mockImplementationOnce(async () => {+ await gate;+ return ['view-1'];+ });++ const pending = loadSkillAccess({ enabled: true, userId: 'user-1', role: 'USER' }, deps);+ await Promise.resolve();+ expect(deps.findAccessibleResources).toHaveBeenCalledTimes(2);+ expect(deps.canCreateSkill).toHaveBeenCalledTimes(1);+ release();++ expect(await pending).toEqual({+ accessibleSkillIds: ['view-1', 'deployment-1'],+ editableSkillIds: ['edit-1'],+ skillCreateAllowed: true,+ });+ expect(deps.findAccessibleResources).toHaveBeenCalledWith({+ userId: 'user-1',+ role: 'USER',+ resourceType: ResourceType.SKILL,+ requiredPermissions: PermissionBits.VIEW,+ });+ });+});diff --git a/packages/api/src/skills/access.ts b/packages/api/src/skills/access.tsnew file mode 100644index 0000000000..701b1fe6d9--- /dev/null+++ b/packages/api/src/skills/access.ts@@ -0,0 +1,60 @@+import { PermissionBits, ResourceType } from 'librechat-data-provider';++export interface SkillAccessParams {+ /** Whether the skills capability is enabled for the agent endpoint. */+ enabled: boolean;+ userId: string;+ role?: string | null;+}++export interface SkillAccessDeps<TId> {+ findAccessibleResources: (params: {+ userId: string;+ role?: string | null;+ resourceType: ResourceType;+ requiredPermissions: number;+ }) => Promise<TId[]>;+ /** Adds the deployment skills every user can read to the VIEW set. */+ withDeploymentSkillIds: (ids: TId[]) => TId[];+ canCreateSkill: () => Promise<boolean>;+}++export interface SkillAccess<TId> {+ accessibleSkillIds: TId[];+ editableSkillIds: TId[];+ skillCreateAllowed: boolean;+}++/**+ * Resolves which skills a user can read and edit, and whether they may create one, for an+ * agent run. The three reads are independent, so they run together; with the capability off+ * nothing is read.+ */+export async function loadSkillAccess<TId>(+ { enabled, userId, role }: SkillAccessParams,+ deps: SkillAccessDeps<TId>,+): Promise<SkillAccess<TId>> {+ if (!enabled) {+ return { accessibleSkillIds: [], editableSkillIds: [], skillCreateAllowed: false };+ }+ const [viewable, editableSkillIds, skillCreateAllowed] = await Promise.all([+ deps.findAccessibleResources({+ userId,+ role,+ resourceType: ResourceType.SKILL,+ requiredPermissions: PermissionBits.VIEW,+ }),+ deps.findAccessibleResources({+ userId,+ role,+ resourceType: ResourceType.SKILL,+ requiredPermissions: PermissionBits.EDIT,+ }),+ deps.canCreateSkill(),+ ]);+ return {+ accessibleSkillIds: deps.withDeploymentSkillIds(viewable),+ editableSkillIds,+ skillCreateAllowed,+ };+}diff --git a/packages/api/src/skills/index.ts b/packages/api/src/skills/index.tsindex 55ed0fce03..8ad652d21e 100644--- a/packages/api/src/skills/index.ts+++ b/packages/api/src/skills/index.ts@@ -6,6 +6,7 @@ export * from './protection';export * from './limits';export * from './parse';export * from './skillStates';+export * from './access';export * from './deployment';export * from './sync';export * from './management';diff --git a/packages/api/src/user/erasure.spec.ts b/packages/api/src/user/erasure.spec.tsindex c78300d55c..999d0d80d7 100644--- a/packages/api/src/user/erasure.spec.ts+++ b/packages/api/src/user/erasure.spec.ts@@ -470,6 +470,28 @@ describe('eraseUserData', () => {expect(await count('AclEntry', { principalId: userId })).toBeGreaterThan(0);});+ it('surfaces a failed leaf delete and stops before the steps after it', async () => {+ const userId = new mongoose.Types.ObjectId();+ await seedUser(userId);+ const { deps } = createDeps();+ const presetsError = new Error('presets down');+ const failingDeps: UserErasureDeps = {+ ...deps,+ deletePresets: jest.fn().mockRejectedValue(presetsError),+ deleteAllUserMemories: jest.fn().mockRejectedValue(new Error('memories down')),+ deleteSharedLinks: jest.fn(async () => undefined),+ };+ const deleteToolCalls = jest.spyOn(failingDeps, 'deleteToolCalls');++ await expect(eraseUserData({ userId: userId.toString() }, failingDeps)).rejects.toBe(+ presetsError,+ );++ expect(deleteToolCalls).toHaveBeenCalledTimes(1);+ expect(failingDeps.deleteSharedLinks).not.toHaveBeenCalled();+ expect(await count('MCPServer', { author: userId })).toBe(2);+ });+it('removes stored files while the user keys their provider clients need still exist', async () => {const userId = new mongoose.Types.ObjectId();await seedUser(userId);diff --git a/packages/api/src/user/erasure.ts b/packages/api/src/user/erasure.tsindex e6efc581fe..2bc83165a8 100644--- a/packages/api/src/user/erasure.ts+++ b/packages/api/src/user/erasure.ts@@ -232,6 +232,19 @@ export async function deleteUserMCPServers(}}+/**+ * Waits for independent deletes to settle, then rethrows the first failure in declaration+ * order, so a failed step aborts the erasure with the same error as when they ran one by one.+ */+async function settleInOrder(steps: Array<Promise<unknown> | undefined>): Promise<void> {+ const results = await Promise.allSettled(steps);+ for (const result of results) {+ if (result.status === 'rejected') {+ throw result.reason;+ }+ }+}+/*** The user-owned data cascade shared by account self-deletion and the operator CLI.*@@ -285,21 +298,22 @@ export async function eraseUserData(await deps.deleteRefreshTokenBridges({ userId });}await deps.deletePasskeysByUser(userId);- if (!keepTransactions) {- await deps.deleteTransactions({ user: userId });- }await deps.deleteUserKey({ userId, all: true });- await deps.deleteBalances({ user: userObjectId });- await deps.deletePresets(userId);- await deps.deleteAllUserPluginAuths(userId);+ /** Leaf collections nothing later in the erasure reads, so they are removed together. */+ await settleInOrder([+ keepTransactions ? undefined : deps.deleteTransactions({ user: userId }),+ deps.deleteBalances({ user: userObjectId }),+ deps.deletePresets(userId),+ deps.deleteAllUserPluginAuths(userId),+ deps.deleteToolCalls(userId),+ deps.deleteConversationTags({ user: userId }),+ deps.deleteUserToolFavorites(userId),+ deps.deleteAllUserMemories(userId),+ ]);await deps.deleteSharedLinks(userId);- await deps.deleteToolCalls(userId);await deps.deleteUserAgents(userId);await deps.deleteAllAgentApiKeys(userObjectId);await deps.deleteAssistants({ user: userId });- await deps.deleteConversationTags({ user: userId });- await deps.deleteUserToolFavorites(userId);- await deps.deleteAllUserMemories(userId);await deps.deleteUserPrompts(userId);await deps.deleteUserSkills(userId);await deleteUserMCPServers(userId, deps, tenantId);diff --git a/packages/api/src/utils/key.test.ts b/packages/api/src/utils/key.test.tsindex 08d5ed453c..0f550f08e8 100644--- a/packages/api/src/utils/key.test.ts+++ b/packages/api/src/utils/key.test.ts@@ -1,10 +1,12 @@import path from 'path';import axios from 'axios';+import { stat } from 'fs/promises';import { ErrorTypes } from 'librechat-data-provider';-import { checkUserKeyExpiry, loadServiceKey } from './key';+import { checkUserKeyExpiry, isServiceKeyAvailable, loadServiceKey } from './key';import { readFileAsString } from './files';jest.mock('fs');+jest.mock('fs/promises', () => ({ stat: jest.fn() }));jest.mock('axios');jest.mock('@librechat/data-schemas', () => ({logger: {@@ -190,6 +192,65 @@ describe('loadServiceKey', () => {});});+describe('isServiceKeyAvailable', () => {+ const statMock = stat as jest.Mock;+ const validKey = { content: JSON.stringify({ project_id: 'p' }), bytes: 16 };++ beforeEach(() => {+ jest.clearAllMocks();+ statMock.mockResolvedValue({ ino: 7, ctimeMs: 1, mtimeMs: 1, size: 16 });+ });++ it('reads an unchanged key file once it has loaded, and retries one that failed', async () => {+ const keyPath = '/secrets/remembered.json';+ (readFileAsString as jest.Mock)+ .mockRejectedValueOnce(new Error('ENOENT'))+ .mockResolvedValueOnce(validKey);++ await expect(isServiceKeyAvailable(keyPath)).resolves.toBe(false);+ await expect(isServiceKeyAvailable(keyPath)).resolves.toBe(true);+ await expect(isServiceKeyAvailable(keyPath)).resolves.toBe(true);++ expect(readFileAsString).toHaveBeenCalledTimes(2);+ });++ it('stops advertising a key file that was replaced with invalid JSON or removed', async () => {+ const keyPath = '/secrets/rotated.json';+ (readFileAsString as jest.Mock)+ .mockResolvedValueOnce(validKey)+ .mockResolvedValueOnce({ content: '{not json', bytes: 9 });++ await expect(isServiceKeyAvailable(keyPath)).resolves.toBe(true);++ statMock.mockResolvedValue({ ino: 7, ctimeMs: 2, mtimeMs: 2, size: 9 });+ await expect(isServiceKeyAvailable(keyPath)).resolves.toBe(false);++ statMock.mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }));+ (readFileAsString as jest.Mock).mockRejectedValueOnce(new Error('ENOENT'));+ await expect(isServiceKeyAvailable(keyPath)).resolves.toBe(false);+ });++ it('rechecks a key file whose permissions changed without a content change', async () => {+ const keyPath = '/secrets/chmodded.json';+ (readFileAsString as jest.Mock)+ .mockResolvedValueOnce(validKey)+ .mockRejectedValueOnce(Object.assign(new Error('EACCES'), { code: 'EACCES' }));++ await expect(isServiceKeyAvailable(keyPath)).resolves.toBe(true);+ statMock.mockResolvedValue({ ino: 7, ctimeMs: 3, mtimeMs: 1, size: 16 });+ await expect(isServiceKeyAvailable(keyPath)).resolves.toBe(false);+ });++ it('fetches a URL key source on every call', async () => {+ (axios.get as jest.Mock).mockResolvedValue({ data: { project_id: 'p' } });++ await expect(isServiceKeyAvailable('https://keys.example.com/sa.json')).resolves.toBe(true);+ await expect(isServiceKeyAvailable('https://keys.example.com/sa.json')).resolves.toBe(true);++ expect(axios.get).toHaveBeenCalledTimes(2);+ });+});+describe('checkUserKeyExpiry', () => {it('accepts a key that has not expired', () => {expect(() =>diff --git a/packages/api/src/utils/key.ts b/packages/api/src/utils/key.tsindex a0cae609bb..7d780c85f9 100644--- a/packages/api/src/utils/key.ts+++ b/packages/api/src/utils/key.ts@@ -1,5 +1,6 @@import path from 'path';import axios from 'axios';+import { stat } from 'fs/promises';import { logger } from '@librechat/data-schemas';import { ErrorTypes } from 'librechat-data-provider';import { SERVICE_REQUEST_TIMEOUT_MS } from './timeouts';@@ -142,3 +143,44 @@ export function checkUserKeyExpiry(expiresAt: string, endpoint: string): void {throw new Error(errorMessage);}}++/** Key sources that loaded, by the signature of the file they loaded from. */+const availableServiceKeys = new Map<string, string>();++/**+ * The file's identity, change and modification times and size (a chmod or replacement moves+ * the change time), or `inline` when `keyPath` names no readable file+ * (stringified or base64 JSON), so a replaced or removed key file is noticed without a read.+ */+async function getKeySourceSignature(keyPath: string): Promise<string> {+ try {+ const absolutePath = path.isAbsolute(keyPath) ? keyPath : path.resolve(keyPath);+ const stats = await stat(absolutePath);+ return `${stats.ino}:${stats.ctimeMs}:${stats.mtimeMs}:${stats.size}`;+ } catch {+ return 'inline';+ }+}++/**+ * Whether a Google service key loads from `keyPath`, for endpoint availability checks that run+ * on every endpoints config read. A file or inline source that loaded is remembered while that+ * signature is unchanged, so those reads stop re-reading and+ * re-parsing the key; a changed, removed or failing source is loaded again. URL sources are+ * fetched on every call, since nothing local says whether they changed.+ */+export async function isServiceKeyAvailable(keyPath: string): Promise<boolean> {+ if (/^https?:\/\//.test(keyPath)) {+ return (await loadServiceKey(keyPath)) != null;+ }+ const signature = await getKeySourceSignature(keyPath);+ if (availableServiceKeys.get(keyPath) === signature) {+ return true;+ }+ if ((await loadServiceKey(keyPath)) == null) {+ availableServiceKeys.delete(keyPath);+ return false;+ }+ availableServiceKeys.set(keyPath, signature);+ return true;+}