LibreChat/packages/api/src/oauth/tokens.ts
Danny Avila 04a4a2aa44
🧵 refactor: Migrate Endpoint Initialization to TypeScript (#10794)
* refactor: move endpoint initialization methods to typescript

* refactor: move agent init to packages/api

- Introduced `initialize.ts` for agent initialization, including file processing and tool loading.
- Updated `resources.ts` to allow optional appConfig parameter.
- Enhanced endpoint configuration handling in various initialization files to support model parameters.
- Added new artifacts and prompts for React component generation.
- Refactored existing code to improve type safety and maintainability.

* refactor: streamline endpoint initialization and enhance type safety

- Updated initialization functions across various endpoints to use a consistent request structure, replacing `unknown` types with `ServerResponse`.
- Simplified request handling by directly extracting keys from the request body.
- Improved type safety by ensuring user IDs are safely accessed with optional chaining.
- Removed unnecessary parameters and streamlined model options handling for better clarity and maintainability.

* refactor: moved ModelService and extractBaseURL to packages/api

- Added comprehensive tests for the models fetching functionality, covering scenarios for OpenAI, Anthropic, Google, and Ollama models.
- Updated existing endpoint index to include the new models module.
- Enhanced utility functions for URL extraction and model data processing.
- Improved type safety and error handling across the models fetching logic.

* refactor: consolidate utility functions and remove unused files

- Merged `deriveBaseURL` and `extractBaseURL` into the `@librechat/api` module for better organization.
- Removed redundant utility files and their associated tests to streamline the codebase.
- Updated imports across various client files to utilize the new consolidated functions.
- Enhanced overall maintainability by reducing the number of utility modules.

* refactor: replace ModelService references with direct imports from @librechat/api and remove ModelService file

* refactor: move encrypt/decrypt methods and key db methods to data-schemas, use `getProviderConfig` from `@librechat/api`

* chore: remove unused 'res' from options in AgentClient

* refactor: file model imports and methods

- Updated imports in various controllers and services to use the unified file model from '~/models' instead of '~/models/File'.
- Consolidated file-related methods into a new file methods module in the data-schemas package.
- Added comprehensive tests for file methods including creation, retrieval, updating, and deletion.
- Enhanced the initializeAgent function to accept dependency injection for file-related methods.
- Improved error handling and logging in file methods.

* refactor: streamline database method references in agent initialization

* refactor: enhance file method tests and update type references to IMongoFile

* refactor: consolidate database method imports in agent client and initialization

* chore: remove redundant import of initializeAgent from @librechat/api

* refactor: move checkUserKeyExpiry utility to @librechat/api and update references across endpoints

* refactor: move updateUserPlugins logic to user.ts and simplify UserController

* refactor: update imports for user key management and remove UserService

* refactor: remove unused Anthropics and Bedrock endpoint files and clean up imports

* refactor: consolidate and update encryption imports across various files to use @librechat/data-schemas

* chore: update file model mock to use unified import from '~/models'

* chore: import order

* refactor: remove migrated to TS agent.js file and its associated logic from the endpoints

* chore: add reusable function to extract imports from source code in unused-packages workflow

* chore: enhance unused-packages workflow to include @librechat/api dependencies and improve dependency extraction

* chore: improve dependency extraction in unused-packages workflow with enhanced error handling and debugging output

* chore: add detailed debugging output to unused-packages workflow for better visibility into unused dependencies and exclusion lists

* chore: refine subpath handling in unused-packages workflow to correctly process scoped and non-scoped package imports

* chore: clean up unused debug output in unused-packages workflow and reorganize type imports in initialize.ts
2025-12-11 16:37:16 -05:00

323 lines
9 KiB
TypeScript

import axios from 'axios';
import { logger, encryptV2, decryptV2 } from '@librechat/data-schemas';
import { TokenExchangeMethodEnum } from 'librechat-data-provider';
import type { TokenMethods } from '@librechat/data-schemas';
import type { AxiosError } from 'axios';
import { logAxiosError } from '~/utils';
export function createHandleOAuthToken({
findToken,
updateToken,
createToken,
}: {
findToken: TokenMethods['findToken'];
updateToken: TokenMethods['updateToken'];
createToken: TokenMethods['createToken'];
}) {
/**
* Handles the OAuth token by creating or updating the token.
* @param fields
* @param fields.userId - The user's ID.
* @param fields.token - The full token to store.
* @param fields.identifier - Unique, alternative identifier for the token.
* @param fields.expiresIn - The number of seconds until the token expires.
* @param fields.metadata - Additional metadata to store with the token.
* @param [fields.type="oauth"] - The type of token. Default is 'oauth'.
*/
return async function handleOAuthToken({
token,
userId,
identifier,
expiresIn,
metadata,
type = 'oauth',
}: {
token: string;
userId: string;
identifier: string;
expiresIn?: number | string | null;
metadata?: Record<string, unknown>;
type?: string;
}) {
const encrypedToken = await encryptV2(token);
let expiresInNumber = 3600;
if (typeof expiresIn === 'number') {
expiresInNumber = expiresIn;
} else if (expiresIn != null) {
expiresInNumber = parseInt(expiresIn, 10) || 3600;
}
const tokenData = {
type,
userId,
metadata,
identifier,
token: encrypedToken,
expiresIn: expiresInNumber,
};
const existingToken = await findToken({ userId, identifier });
if (existingToken) {
return await updateToken({ identifier }, tokenData);
} else {
return await createToken(tokenData);
}
};
}
/**
* Processes the access tokens and stores them in the database.
* @param tokenData
* @param tokenData.access_token
* @param tokenData.expires_in
* @param [tokenData.refresh_token]
* @param [tokenData.refresh_token_expires_in]
* @param metadata
* @param metadata.userId
* @param metadata.identifier
*/
async function processAccessTokens(
tokenData: {
access_token: string;
expires_in: number;
refresh_token?: string;
refresh_token_expires_in?: number;
},
{ userId, identifier }: { userId: string; identifier: string },
{
findToken,
updateToken,
createToken,
}: {
findToken: TokenMethods['findToken'];
updateToken: TokenMethods['updateToken'];
createToken: TokenMethods['createToken'];
},
) {
const { access_token, expires_in = 3600, refresh_token, refresh_token_expires_in } = tokenData;
if (!access_token) {
logger.error('Access token not found: ', tokenData);
throw new Error('Access token not found');
}
const handleOAuthToken = createHandleOAuthToken({
findToken,
updateToken,
createToken,
});
await handleOAuthToken({
identifier,
token: access_token,
expiresIn: expires_in,
userId,
});
if (refresh_token != null) {
logger.debug('Processing refresh token');
await handleOAuthToken({
token: refresh_token,
type: 'oauth_refresh',
userId,
identifier: `${identifier}:refresh`,
expiresIn: refresh_token_expires_in ?? null,
});
}
logger.debug('Access tokens processed');
}
/**
* Refreshes the access token using the refresh token.
* @param fields
* @param fields.userId - The ID of the user.
* @param fields.client_url - The URL of the OAuth provider.
* @param fields.identifier - The identifier for the token.
* @param fields.refresh_token - The refresh token to use.
* @param fields.token_exchange_method - The token exchange method ('default_post' or 'basic_auth_header').
* @param fields.encrypted_oauth_client_id - The client ID for the OAuth provider.
* @param fields.encrypted_oauth_client_secret - The client secret for the OAuth provider.
*/
export async function refreshAccessToken(
{
userId,
client_url,
identifier,
refresh_token,
token_exchange_method,
encrypted_oauth_client_id,
encrypted_oauth_client_secret,
}: {
userId: string;
client_url: string;
identifier: string;
refresh_token: string;
token_exchange_method: TokenExchangeMethodEnum;
encrypted_oauth_client_id: string;
encrypted_oauth_client_secret: string;
},
{
findToken,
updateToken,
createToken,
}: {
findToken: TokenMethods['findToken'];
updateToken: TokenMethods['updateToken'];
createToken: TokenMethods['createToken'];
},
): Promise<{
access_token: string;
expires_in: number;
refresh_token?: string;
refresh_token_expires_in?: number;
}> {
try {
const oauth_client_id = await decryptV2(encrypted_oauth_client_id);
const oauth_client_secret = await decryptV2(encrypted_oauth_client_secret);
const headers: Record<string, string> = {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
};
const params = new URLSearchParams({
grant_type: 'refresh_token',
refresh_token,
});
if (token_exchange_method === TokenExchangeMethodEnum.BasicAuthHeader) {
const basicAuth = Buffer.from(`${oauth_client_id}:${oauth_client_secret}`).toString('base64');
headers['Authorization'] = `Basic ${basicAuth}`;
} else {
params.append('client_id', oauth_client_id);
params.append('client_secret', oauth_client_secret);
}
const response = await axios({
method: 'POST',
url: client_url,
headers,
data: params.toString(),
});
await processAccessTokens(
response.data,
{
userId,
identifier,
},
{
findToken,
updateToken,
createToken,
},
);
logger.debug(`Access token refreshed successfully for ${identifier}`);
return response.data;
} catch (error) {
const message = 'Error refreshing OAuth tokens';
throw new Error(
logAxiosError({
message,
error: error as AxiosError,
}),
);
}
}
/**
* Handles the OAuth callback and exchanges the authorization code for tokens.
* @param {object} fields
* @param {string} fields.code - The authorization code returned by the provider.
* @param {string} fields.userId - The ID of the user.
* @param {string} fields.identifier - The identifier for the token.
* @param {string} fields.client_url - The URL of the OAuth provider.
* @param {string} fields.redirect_uri - The redirect URI for the OAuth provider.
* @param {string} fields.token_exchange_method - The token exchange method ('default_post' or 'basic_auth_header').
* @param {string} fields.encrypted_oauth_client_id - The client ID for the OAuth provider.
* @param {string} fields.encrypted_oauth_client_secret - The client secret for the OAuth provider.
*/
export async function getAccessToken(
{
code,
userId,
identifier,
client_url,
redirect_uri,
token_exchange_method,
encrypted_oauth_client_id,
encrypted_oauth_client_secret,
}: {
code: string;
userId: string;
identifier: string;
client_url: string;
redirect_uri: string;
token_exchange_method: TokenExchangeMethodEnum;
encrypted_oauth_client_id: string;
encrypted_oauth_client_secret: string;
},
{
findToken,
updateToken,
createToken,
}: {
findToken: TokenMethods['findToken'];
updateToken: TokenMethods['updateToken'];
createToken: TokenMethods['createToken'];
},
): Promise<{
access_token: string;
expires_in: number;
refresh_token?: string;
refresh_token_expires_in?: number;
}> {
const oauth_client_id = await decryptV2(encrypted_oauth_client_id);
const oauth_client_secret = await decryptV2(encrypted_oauth_client_secret);
const headers: Record<string, string> = {
'Content-Type': 'application/x-www-form-urlencoded',
Accept: 'application/json',
};
const params = new URLSearchParams({
code,
grant_type: 'authorization_code',
redirect_uri,
});
if (token_exchange_method === TokenExchangeMethodEnum.BasicAuthHeader) {
const basicAuth = Buffer.from(`${oauth_client_id}:${oauth_client_secret}`).toString('base64');
headers['Authorization'] = `Basic ${basicAuth}`;
} else {
params.append('client_id', oauth_client_id);
params.append('client_secret', oauth_client_secret);
}
try {
const response = await axios({
method: 'POST',
url: client_url,
headers,
data: params.toString(),
});
await processAccessTokens(
response.data,
{
userId,
identifier,
},
{
findToken,
updateToken,
createToken,
},
);
logger.debug(`Access tokens successfully created for ${identifier}`);
return response.data;
} catch (error) {
const message = 'Error exchanging OAuth code';
throw new Error(
logAxiosError({
message,
error: error as AxiosError,
}),
);
}
}