mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-01-22 10:16:13 +01:00
🧮 refactor: Replace Eval with Safe Math Expression Parser (#11098)
* chore: Add mathjs dependency * refactor: Replace eval with mathjs for safer expression evaluation and improve session expiry handling to not environment variables from data-schemas package * test: Add integration tests for math function with environment variable expressions * refactor: Update test description for clarity on expiresIn behavior * refactor: Update test cases to clarify default expiration behavior for token generation * refactor: Improve error handling in math function for clearer evaluation errors
This commit is contained in:
parent
d0863de8d4
commit
6ffb176056
14 changed files with 602 additions and 85 deletions
|
|
@ -1,3 +1,5 @@
|
|||
import { evaluate } from 'mathjs';
|
||||
|
||||
/**
|
||||
* Evaluates a mathematical expression provided as a string and returns the result.
|
||||
*
|
||||
|
|
@ -5,6 +7,8 @@
|
|||
* If the input is not a string or contains invalid characters, an error is thrown.
|
||||
* If the evaluated result is not a number, an error is thrown.
|
||||
*
|
||||
* Uses mathjs for safe expression evaluation instead of eval().
|
||||
*
|
||||
* @param str - The mathematical expression to evaluate, or a number.
|
||||
* @param fallbackValue - The default value to return if the input is not a string or number, or if the evaluated result is not a number.
|
||||
*
|
||||
|
|
@ -32,14 +36,22 @@ export function math(str: string | number | undefined, fallbackValue?: number):
|
|||
throw new Error('Invalid characters in string');
|
||||
}
|
||||
|
||||
const value = eval(str);
|
||||
try {
|
||||
const value = evaluate(str);
|
||||
|
||||
if (typeof value !== 'number') {
|
||||
if (typeof value !== 'number') {
|
||||
if (fallback) {
|
||||
return fallbackValue;
|
||||
}
|
||||
throw new Error(`[math] str did not evaluate to a number but to a ${typeof value}`);
|
||||
}
|
||||
|
||||
return value;
|
||||
} catch (error) {
|
||||
if (fallback) {
|
||||
return fallbackValue;
|
||||
}
|
||||
throw new Error(`[math] str did not evaluate to a number but to a ${typeof value}`);
|
||||
const originalMessage = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(`[math] Error while evaluating mathematical expression: ${originalMessage}`);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue