mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-17 21:43:06 +00:00
* fix: Mask Email Addresses and Drop Personal Identifiers from Logs * fix: Log User IDs in OpenID Admin Role and LDAP Domain Block Messages * fix: Mask Unicode Email Addresses in Log Redaction * test: Add Log Email Masking Scenarios * fix: Bound the Email Redaction Matcher and Handle Quoted Local Parts * fix: Mask Quoted and Special-Character Email Local Parts * fix: Redact Whole Email Tokens, Top-Level Log Fields and Metadata Keys * fix: Redact Top-Level Metadata Keys and Escaped Quotes in Email Local Parts * fix: Redact Truncated Emails, Address Literals and Request Paths in Logs * fix: Redact the Full Log String Before Truncating * fix: Preserve Colliding and Object Keys When Redacting Log Metadata * fix: Bound Log Redaction to a Window Past the Truncation Limit * fix: Redact the Truncation Window Without a Whitespace Cut * fix: Redact Serialized Quoted Addresses and Keep Key Collisions Linear * fix: Bound Every Log Redaction Path and the URL Credential Pattern * fix: Keep Long-Scheme Credential Redaction and Serialized Escaped Quotes * test: Cover Every Secret Shape Across the Log Truncation Cap * fix: Drop Unfinished Window Tokens, Mask Short TLDs and Redact Direct Error Stacks * fix: Treat Input End as a Token Boundary and Mask Parenthesized Identifiers * fix: Remove the Quoted Local Part Length Cap Without Quadratic Scans * fix: Drop an Unfinished Quoted Address at the Window Edge * fix: Check Quoted Locals Before Accepting a Window Delimiter * fix: Count Only Opening Quotes When Trimming the Window * fix: Track Unmatched Quoted Locals Instead of Counting Closing Quotes * fix: Lift Residual Email Caps, Keep Punctuated Credential URIs Masked and Move OBO Log Id to the API Package * fix: Mask Empty Quoted Locals and Tolerate Read-Only Log Fields * fix: Return a Sanitized Copy When a Log Field Cannot Be Replaced * fix: Treat a Failed Key Removal as a Failed Replacement and Guard Stack Writes * fix: Skip Heavy Error Graphs and Accept Escaped Backslashes in Serialized Locals * fix: Accept Lone Escaped Backslashes in Serialized Locals Without Rescans * fix: Compact Axios Request Info Before Redaction and Skip Heavy Splat Error Graphs * fix: Redact Address Keys on Nested Error Objects * fix: Materialize and Redact Enumerable Getters on Nested Errors * fix: Guard Throwing Top-Level Getters and Skip Heavy Fields Only on Error Records * fix: Skip Serialized Quotes When Trimming an Unfinished Address * fix: Bound Redaction With a Per-Record Node Budget and Accept JSON Control Escapes * fix: Match Credential URIs From the Separator So Scheme Length Is Unbounded * fix: Count Strings Against the Redaction Budget and Guard Nested Getters * fix: Rebuild the Log Record When a Top-Level Accessor Ignores Writes * fix: Rebuild the Log Record When a Stack Accessor Ignores Writes * fix: Guard the Initial Stack Read on Direct Error Logs * fix: Accept Escaped Solidus and Preserve the Outer Budget on Reentrant Logging * fix: Guard the Axios Marker and Error-Like Probes Against Throwing Getters * fix: Guard the Axios Marker on Nested Errors * fix: Replace Skipped Heavy Fields Up Front, Budget Top-Level Fields and Mask Encoded Emails * fix: Mask Encoded Address Keys and Guard Nested Axios Config Compaction * fix: Redact URL Objects in Compact Request Info * fix: Remove Encoded Email Caps and Strip Serializer Hooks From Clones * fix: Strip Serializer Hooks From Error Clones and Top-Level Records * fix: Neutralize Inherited Serializer Hooks on Log Records * fix: Guard the Serializer Hook Probe * fix: Replace Function Values in Log Records * fix: Mask Percent-Encoded Domain Separators in Logged URLs * fix: Bound the Encoded Email Domain at URL Delimiters * fix: Shadow Throwing Serializer Getters on Nested Errors * fix: Rebuild Accessor Messages and Mask Doubly Encoded Addresses * fix: Redact Multiply Encoded Address Keys * feat: Make the Log Redaction Node Budget Configurable * fix: Guard Message and Serializer Property Reads * fix: Contain Proxy Failures and Redact the Compact Request Method
139 lines
5.2 KiB
TypeScript
139 lines
5.2 KiB
TypeScript
import { ErrorTypes } from 'librechat-data-provider';
|
|
import { logger, tenantStorage } from '@librechat/data-schemas';
|
|
import type { NextFunction, Request, Response } from 'express';
|
|
import type { MongoServerError, ValidationError, CustomError } from '~/types';
|
|
import { MCPAuthenticationRefreshError, MCPAuthenticationRejectedError } from '~/mcp/errors';
|
|
import { buildTenantIsolationErrorLogContext } from './auth';
|
|
import { OpenIDReauthRequiredError } from '~/utils/oidc';
|
|
|
|
const handleDuplicateKeyError = (err: MongoServerError, res: Response) => {
|
|
logger.warn('Duplicate key error', {
|
|
mongoCode: err.code,
|
|
fields: err.keyValue ? Object.keys(err.keyValue) : [],
|
|
});
|
|
const field = err.keyValue ? `${JSON.stringify(Object.keys(err.keyValue))}` : 'unknown';
|
|
const code = 409;
|
|
res
|
|
.status(code)
|
|
.send({ messages: `An document with that ${field} already exists.`, fields: field });
|
|
};
|
|
|
|
const handleValidationError = (err: ValidationError, res: Response) => {
|
|
logger.error('Validation error:', err.errors);
|
|
const errorMessages = Object.values(err.errors).map((el) => el.message);
|
|
const fields = `${JSON.stringify(Object.values(err.errors).map((el) => el.path))}`;
|
|
const code = 400;
|
|
const messages =
|
|
errorMessages.length > 1
|
|
? `${JSON.stringify(errorMessages.join(' '))}`
|
|
: `${JSON.stringify(errorMessages)}`;
|
|
|
|
res.status(code).send({ messages, fields });
|
|
};
|
|
|
|
/** Type guard for ValidationError */
|
|
function isValidationError(err: unknown): err is ValidationError {
|
|
return err !== null && typeof err === 'object' && 'name' in err && err.name === 'ValidationError';
|
|
}
|
|
|
|
/** Type guard for MongoServerError (duplicate key) */
|
|
function isMongoServerError(err: unknown): err is MongoServerError {
|
|
return err !== null && typeof err === 'object' && 'code' in err && err.code === 11000;
|
|
}
|
|
|
|
/** Type guard for CustomError with statusCode and body */
|
|
function isCustomError(err: unknown): err is CustomError {
|
|
return err !== null && typeof err === 'object' && 'statusCode' in err && 'body' in err;
|
|
}
|
|
|
|
/**
|
|
* Builds an error that `ErrorController` relays to the client verbatim. `isCustomError` matches only
|
|
* when both `statusCode` and `body` are present, so a plain `Error` falls through to a bare 500 and
|
|
* its message never leaves the server log. Use this wherever the caller needs to see the reason.
|
|
*/
|
|
export const createCustomError = (statusCode: number, message: string): CustomError => {
|
|
const error = new Error(message) as CustomError;
|
|
error.statusCode = statusCode;
|
|
error.body = { message };
|
|
return error;
|
|
};
|
|
|
|
export const ErrorController = (
|
|
err: Error | CustomError,
|
|
req: Request,
|
|
res: Response,
|
|
next: NextFunction,
|
|
): Response | void => {
|
|
try {
|
|
if (!err) {
|
|
return next();
|
|
}
|
|
const error = err as CustomError;
|
|
|
|
if (
|
|
(error.message === ErrorTypes.AUTH_FAILED || error.code === ErrorTypes.AUTH_FAILED) &&
|
|
req.originalUrl &&
|
|
req.originalUrl.includes('/oauth/') &&
|
|
req.originalUrl.includes('/callback')
|
|
) {
|
|
const domain = process.env.DOMAIN_CLIENT || 'http://localhost:3080';
|
|
return res.redirect(`${domain}/login?redirect=false&error=${ErrorTypes.AUTH_FAILED}`);
|
|
}
|
|
|
|
if (isValidationError(error)) {
|
|
return handleValidationError(error, res);
|
|
}
|
|
|
|
if (isMongoServerError(error)) {
|
|
return handleDuplicateKeyError(error, res);
|
|
}
|
|
|
|
if (err instanceof OpenIDReauthRequiredError) {
|
|
logger.warn('OpenID re-authentication required: ' + err.message);
|
|
return res.status(401).send({ error: 'invalid_token', message: err.message });
|
|
}
|
|
|
|
if (err instanceof MCPAuthenticationRejectedError) {
|
|
logger.warn('MCP bearer authentication rejected: ' + err.message);
|
|
/** A remote credential rejection must not trigger the client's app-JWT retry interceptor. */
|
|
return res.status(err.statusCode).send({
|
|
error: 'invalid_token',
|
|
code: err.code,
|
|
message: err.message,
|
|
retryable: err.retryable,
|
|
connectionRefreshed: err.connectionRefreshed,
|
|
});
|
|
}
|
|
|
|
if (err instanceof MCPAuthenticationRefreshError) {
|
|
logger.warn('MCP bearer refresh temporarily unavailable: ' + err.message);
|
|
return res.status(err.statusCode).send({
|
|
code: err.code,
|
|
message: err.message,
|
|
retryable: err.retryable,
|
|
});
|
|
}
|
|
|
|
if (isCustomError(error) && error.statusCode && error.body) {
|
|
return res.status(error.statusCode).send(error.body);
|
|
}
|
|
|
|
const tenantIsolationContext = buildTenantIsolationErrorLogContext(req, err);
|
|
if (tenantIsolationContext) {
|
|
const { requestId, requestMethod, requestPath } = tenantStorage.getStore() ?? {};
|
|
logger.error({
|
|
message: 'Tenant-isolation request failed',
|
|
...tenantIsolationContext,
|
|
...(requestId && { request_id: requestId }),
|
|
...(requestMethod && { request_method: requestMethod }),
|
|
...(requestPath && { request_path: requestPath }),
|
|
});
|
|
} else {
|
|
logger.error('ErrorController => error', err);
|
|
}
|
|
return res.status(500).send('An unknown error occurred.');
|
|
} catch (processingError) {
|
|
logger.error('ErrorController => processing error', processingError);
|
|
return res.status(500).send('Processing error in ErrorController.');
|
|
}
|
|
};
|