mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-18 14:08:21 +00:00
* perf: Serve JWT Bearer User Lookups From the Auth User Cache * perf: Batch Agent Permission Reads on the File Access Path * perf: Remember a Loaded Google Service Key Across Endpoint Config Reads * perf: Run Independent Startup, Tool, Skill and Erasure Reads Concurrently * fix: Drop JWT User Cache Writes That Race a User Mutation Confirm each cache write with a second read and evict when the user changed, so an in-flight lookup cannot repopulate an entry a credential change just evicted. The cache mode now arrives through the loader dependencies. * refactor: Move Agent Skill Access Reads Into packages/api The chat-completions and Responses controllers call loadSkillAccess instead of orchestrating the three reads in CJS. The preview route spec mocks the batched file access helper the middleware now calls. * test: Cover Agent File Access, JWT Bursts and Remote Skill Reads End to End * fix: Serve a Cached JWT User Only While Its updatedAt Is Current A cache hit now reads the stored updatedAt and deletion fence instead of the fence alone, so a document cached from a read that raced a user mutation is never served, even when the write landed after that mutation's eviction. * refactor: Move Startup Migration Checks Into packages/api * refactor: Inject the Startup Migration Checks Instead of Mongoose Models * fix: Serve Cached OpenID Users Only While Their updatedAt Is Current Moves the freshness check into getCurrentCachedAuthUserDoc and uses it on the OpenID bearer path as well as the local JWT one, so a document cached from a read that raced a credential or role change is never served there either. Fixes berry-13/LibreChat#432 * fix: Compare Authorization Fields on Every Auth Cache Hit updatedAt has millisecond resolution, so the freshness read also compares the token retirement stamps, role, tenant and two-factor state. * fix: Annotate the Auth Freshness Projection for Isolated Declarations * perf: Reuse the OpenID Cache Freshness Read for Deletion Admission A cache hit already proved the deletion fence is clear, so only users read from the database take the separate fence query. * refactor: Keep the OpenID Cache Freshness and Fence Decisions in packages/api * test: Exercise JWT Cache Freshness Against Real User Methods in MongoDB * fix: Stamp the JWT User Lookup So the Cache Write Fence Applies * fix: Reload a Google Service Key File When It Changes or Disappears The availability check remembers a loaded key only while the file's mtime and size are unchanged, and fetches URL sources every time as before. * fix: Recheck a Service Key File After a Permission Change
88 lines
3 KiB
JavaScript
88 lines
3 KiB
JavaScript
const { logger, runAsSystem } = require('@librechat/data-schemas');
|
|
const { CacheKeys, SystemRoles } = require('librechat-data-provider');
|
|
const { Strategy: JwtStrategy, ExtractJwt } = require('passport-jwt');
|
|
const {
|
|
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'];
|
|
|
|
/** A trigger-scoped bearer is deliberately useless outside the two internal
|
|
* admission routes that the execution host calls. */
|
|
function isAgentTriggerAdmissionRequest(req) {
|
|
if (req?.method !== 'POST' || req?.headers?.['x-lc-agent-trigger'] !== '1') {
|
|
return false;
|
|
}
|
|
try {
|
|
const pathname = new URL(req.originalUrl ?? req.url ?? '', 'http://localhost').pathname;
|
|
return AGENT_TRIGGER_ADMISSION_PATHS.some((path) => pathname.endsWith(path));
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// JWT strategy
|
|
const jwtLogin = () =>
|
|
new JwtStrategy(
|
|
{
|
|
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
|
secretOrKey: process.env.JWT_SECRET,
|
|
passReqToCallback: true,
|
|
},
|
|
async (req, payload, done) => {
|
|
try {
|
|
if (payload?.scope === AGENT_TRIGGER_SCOPE && !isAgentTriggerAdmissionRequest(req)) {
|
|
done(null, false, { message: 'Agent trigger token is not valid for this endpoint' });
|
|
return;
|
|
}
|
|
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',
|
|
});
|
|
return;
|
|
}
|
|
if (user) {
|
|
return await continueAfterBearerRetirement(
|
|
user,
|
|
{ issuedAt: payload?.iat, issuedAtMs: payload?.issuedAtMs },
|
|
'jwt',
|
|
payload?.id,
|
|
done,
|
|
(message) => logger.warn(message),
|
|
async () => {
|
|
user.id = user._id.toString();
|
|
/** Absent on the full doc means local user; null skips getUserPrincipals' fallback lookup */
|
|
user.idOnTheSource ??= null;
|
|
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,
|
|
);
|
|
} else {
|
|
logger.warn('[jwtLogin] JwtStrategy => no user found: ' + payload?.id);
|
|
done(null, false);
|
|
}
|
|
} catch (err) {
|
|
done(err, false);
|
|
}
|
|
},
|
|
);
|
|
|
|
module.exports = jwtLogin;
|