mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-18 14:08:21 +00:00
Some checks are pending
Backend Unit Tests / Build packages (push) Waiting to run
Backend Unit Tests / Codegraph select (push) Waiting to run
Backend Unit Tests / TypeScript type checks (push) Blocked by required conditions
Backend Unit Tests / Circular dependency checks (push) Waiting to run
Backend Unit Tests / Tests: api (shard 1/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 2/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: api (shard 3/3) (push) Blocked by required conditions
Backend Unit Tests / Tests: data-provider (push) Blocked by required conditions
Backend Unit Tests / Tests: data-schemas (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 1/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 2/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 3/4) (push) Blocked by required conditions
Backend Unit Tests / Tests: @librechat/api (shard 4/4) (push) Blocked by required conditions
Codegraph E2E Votes / vote (full suite) (push) Waiting to run
Docker Dev Branch Images Build / publish (push) Waiting to run
Frontend Unit Tests / Client build recovery regression (push) Waiting to run
Frontend Unit Tests / Codegraph select (push) Waiting to run
Frontend Unit Tests / Build packages (push) Waiting to run
Frontend Unit Tests / TypeScript type checks (client) (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/chat (push) Blocked by required conditions
Frontend Unit Tests / Tests: @librechat/client (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 1/2) (push) Blocked by required conditions
Frontend Unit Tests / Tests: Ubuntu (shard 2/2) (push) Blocked by required conditions
Frontend Unit Tests / Vite build verification (push) Blocked by required conditions
* fix: Bound Outbound Calls Made Inside a Request RAG queries for file search and message context, OCR provider calls, action HTTP calls, the moderation check, the stored-image fetch for base64 providers, and Flux result polling had no timeout. A stalled upstream hung the chat turn, the upload or the tool call indefinitely, and Flux kept polling forever on statuses that never become Ready. Each now runs under a budget from a new librechat.yaml timeouts block with finite defaults (getOutboundTimeoutMs in @librechat/api). Action calls also receive the run's abort signal, so stopping a run closes the socket. * test: Cover a Stalled RAG Query in the Mock Harness * fix: Share One Flux Budget Across Submit and Polls, Bound the Vertex Token Exchange * refactor: Poll Flux Results Through pollUntilSettled * refactor: Leave Flux Polling for a Separate Migration * fix: Cap Configured Timeouts at the Node Timer Limit * fix: Bound the Action Token Refresh and the Whole Image Download * fix: Cap Every Outbound Budget by Wall-Clock Time Axios's timeout only fires on an idle socket, so a RAG, OCR, moderation, action or token response that keeps trickling bytes never ended. outboundRequestBudget pairs each timeout with an AbortSignal deadline, and action calls combine it with the run's own signal. * fix: Name the Budget That Ran Out and Give Actions Five Minutes The actions default rises to five minutes, since action endpoints are arbitrary third-party APIs and the old minute could cut off legitimately slow ones after an upgrade. A budget overrun now fails with an error naming the timeouts key and its value, whether it was the idle timeout or the wall-clock deadline, and logAxiosError logs it as a warning so operators know what to raise. A deadline cancellation is no longer read as a user stop, so an action that runs out of time reports a timeout instead of looking like a stopped run. * fix: Hold Outbound Deadlines Weakly So Finished Requests Leave No Timers * fix: Check the Budget Before Reading an Error Message * fix: Report a Wrapped Deadline as a Failure, Not a Stop * fix: Bound the OAuth Code Exchange and Keep the OCR Budget Hint When Protected * chore: Sort Imports in axios.ts After Rebase
134 lines
5 KiB
JavaScript
134 lines
5 KiB
JavaScript
const express = require('express');
|
|
const jwt = require('jsonwebtoken');
|
|
const { logger } = require('@librechat/data-schemas');
|
|
const { CacheKeys } = require('librechat-data-provider');
|
|
const {
|
|
getBasePath,
|
|
getAccessToken,
|
|
setOAuthSession,
|
|
validateOAuthCsrf,
|
|
OAUTH_CSRF_COOKIE,
|
|
setOAuthCsrfCookie,
|
|
validateOAuthSession,
|
|
OAUTH_SESSION_COOKIE,
|
|
} = require('@librechat/api');
|
|
const { findToken, updateToken, createToken } = require('~/models');
|
|
const { requireJwtAuth } = require('~/server/middleware');
|
|
const { getActionFlowStateManager } = require('~/config');
|
|
const { getLogStores } = require('~/cache');
|
|
|
|
const router = express.Router();
|
|
const JWT_SECRET = process.env.JWT_SECRET;
|
|
const OAUTH_CSRF_COOKIE_PATH = '/api/actions';
|
|
|
|
/**
|
|
* Sets a CSRF cookie binding the action OAuth flow to the current browser session.
|
|
* Must be called before the user opens the IdP authorization URL.
|
|
*
|
|
* @route POST /actions/:action_id/oauth/bind
|
|
*/
|
|
router.post('/:action_id/oauth/bind', requireJwtAuth, setOAuthSession, async (req, res) => {
|
|
try {
|
|
const { action_id } = req.params;
|
|
const user = req.user;
|
|
if (!user?.id) {
|
|
return res.status(401).json({ error: 'User not authenticated' });
|
|
}
|
|
const flowId = `${user.id}:${action_id}`;
|
|
setOAuthCsrfCookie(res, flowId, OAUTH_CSRF_COOKIE_PATH);
|
|
res.json({ success: true });
|
|
} catch (error) {
|
|
logger.error('[Action OAuth] Failed to set CSRF binding cookie', error);
|
|
res.status(500).json({ error: 'Failed to bind OAuth flow' });
|
|
}
|
|
});
|
|
|
|
/**
|
|
* Handles the OAuth callback and exchanges the authorization code for tokens.
|
|
*
|
|
* @route GET /actions/:action_id/oauth/callback
|
|
* @param {string} req.params.action_id - The ID of the action.
|
|
* @param {string} req.query.code - The authorization code returned by the provider.
|
|
* @param {string} req.query.state - The state token to verify the authenticity of the request.
|
|
* @returns {void} Sends a success message after updating the action with OAuth tokens.
|
|
*/
|
|
router.get('/:action_id/oauth/callback', async (req, res) => {
|
|
const { action_id } = req.params;
|
|
const { code, state } = req.query;
|
|
const flowsCache = getLogStores(CacheKeys.FLOWS);
|
|
const flowManager = getActionFlowStateManager(flowsCache);
|
|
const basePath = getBasePath();
|
|
let identifier = action_id;
|
|
try {
|
|
let decodedState;
|
|
try {
|
|
decodedState = jwt.verify(state, JWT_SECRET);
|
|
} catch (err) {
|
|
logger.error('Error verifying state parameter:', err);
|
|
await flowManager.failFlow(identifier, 'oauth', 'Invalid or expired state parameter');
|
|
return res.redirect(`${basePath}/oauth/error?error=invalid_state`);
|
|
}
|
|
|
|
if (decodedState.action_id !== action_id) {
|
|
await flowManager.failFlow(identifier, 'oauth', 'Mismatched action ID in state parameter');
|
|
return res.redirect(`${basePath}/oauth/error?error=invalid_state`);
|
|
}
|
|
|
|
if (!decodedState.user) {
|
|
await flowManager.failFlow(identifier, 'oauth', 'Invalid user ID in state parameter');
|
|
return res.redirect(`${basePath}/oauth/error?error=invalid_state`);
|
|
}
|
|
|
|
identifier = `${decodedState.user}:${action_id}`;
|
|
|
|
if (
|
|
!validateOAuthCsrf(req, res, identifier, OAUTH_CSRF_COOKIE_PATH) &&
|
|
!validateOAuthSession(req, decodedState.user)
|
|
) {
|
|
logger.error('[Action OAuth] CSRF validation failed: no valid CSRF or session cookie', {
|
|
identifier,
|
|
hasCsrfCookie: !!req.cookies?.[OAUTH_CSRF_COOKIE],
|
|
hasSessionCookie: !!req.cookies?.[OAUTH_SESSION_COOKIE],
|
|
});
|
|
await flowManager.failFlow(identifier, 'oauth', 'CSRF validation failed');
|
|
return res.redirect(`${basePath}/oauth/error?error=csrf_validation_failed`);
|
|
}
|
|
|
|
const flowState = await flowManager.getFlowState(identifier, 'oauth');
|
|
if (!flowState) {
|
|
throw new Error('OAuth flow not found');
|
|
}
|
|
|
|
const tokenData = await getAccessToken(
|
|
{
|
|
code,
|
|
userId: decodedState.user,
|
|
identifier,
|
|
client_url: flowState.metadata.client_url,
|
|
redirect_uri: flowState.metadata.redirect_uri,
|
|
token_exchange_method: flowState.metadata.token_exchange_method,
|
|
allowedAddresses: flowState.metadata.allowedAddresses,
|
|
timeout: flowState.metadata.timeout,
|
|
/** Encrypted values */
|
|
encrypted_oauth_client_id: flowState.metadata.encrypted_oauth_client_id,
|
|
encrypted_oauth_client_secret: flowState.metadata.encrypted_oauth_client_secret,
|
|
},
|
|
{
|
|
findToken,
|
|
updateToken,
|
|
createToken,
|
|
},
|
|
);
|
|
await flowManager.completeFlow(identifier, 'oauth', tokenData);
|
|
|
|
const serverName = flowState.metadata?.action_name || `Action ${action_id}`;
|
|
const redirectUrl = `${basePath}/oauth/success?serverName=${encodeURIComponent(serverName)}`;
|
|
res.redirect(redirectUrl);
|
|
} catch (error) {
|
|
logger.error('Error in OAuth callback:', error);
|
|
await flowManager.failFlow(identifier, 'oauth', error);
|
|
res.redirect(`${basePath}/oauth/error?error=callback_failed`);
|
|
}
|
|
});
|
|
|
|
module.exports = router;
|