AI-native design editor. Open-source Figma alternative.
fix(tools): evaluate calc expressions without expr-eval (#753)
Danila Poyarkov99925e4c2523
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7ecf21caf..61d4f28a7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,11 @@- Show what to update instead of a blank window when the browser or system WebView is too old, naming the detected macOS, Safari, Chrome, Edge, Firefox, WebKitGTK, or WebView2 version and linking a prefilled bug report, and explain a failed start the same way (#744).- Start on macOS 13 with WebKit older than Safari 17.4, which previously failed with `Promise.withResolvers is not a function` (#744).+- Evaluate the `**` operator in the AI and MCP `calc` tool, which its own description advertised but which the tool rejected. `calc` now accepts exactly the arithmetic it documents — `+ - * / % **`, parentheses and `min max floor ceil round abs sqrt pow` — and no longer evaluates undocumented expressions such as `random()`, factorials, trigonometry, strings, arrays, or property access.++### Security++- Evaluate `calc` expressions through `jsep` and an arithmetic allowlist that never compiles input into JavaScript, replacing the `expr-eval` dependency and its unpatched critical code-execution advisory (GHSA-q9v2-7m5w-4693).## 0.15.1 — 2026-09-18diff --git a/bun.lock b/bun.lockindex 70925c001..cb170bbb0 100644--- a/bun.lock+++ b/bun.lock@@ -198,11 +198,11 @@"destr": "^2.0.5","diff": "^8.0.4","es-toolkit": "^1.51.0",- "expr-eval": "^2.0.2","fflate": "^0.8.3","fontoxpath": "^3.34.0","fzstd": "^0.1.1","js-base64": "^3.9.3",+ "jsep": "^1.4.0","jspdf": "^4.2.1","nanoevents": "^9.1.0","ofetch": "^1.5.1",@@ -2703,8 +2703,6 @@"expect-webdriverio": ["[email protected]", "", { "dependencies": { "@vitest/snapshot": "^4.1.7", "deep-eql": "^5.0.2", "expect": "^30.4.1", "jest-matcher-utils": "^30.4.1" }, "peerDependencies": { "@wdio/globals": "^9.0.0", "@wdio/logger": "^9.0.0", "webdriverio": "^9.0.0" } }, "sha512-jLOTrJoPBC3Wtd83ryHMbRcEajMGtAnn6OWtSnoJoDLt16nHvxVdjcI4Bc0n+1KAOr8DvQtlJ55f0M48kJtEpw=="],- "expr-eval": ["[email protected]", "", {}, "sha512-4EMSHGOPSwAfBiibw3ndnP0AvjDWLsMvGOvWEZ2F96IGk0bIVdjQisOHxReSkE13mHcfbuCiXw+G4y0zv6N8Eg=="],-"express": ["[email protected]", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", "content-disposition": "^1.0.0", "content-type": "^1.0.5", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.7", "qs": "^6.14.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.0.1", "vary": "^1.1.2" } }, "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw=="],"express-rate-limit": ["[email protected]", "", { "dependencies": { "debug": "^4.4.3", "ip-address": "^10.2.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-YH4ru+eOJxQABscKFfRCy9R7x9QFGdezclVMwwgFFndzS2Xnm0uo6B0ABZsLhcpeptGv2qvuJVWlQr9gQZoC3A=="],@@ -3173,6 +3171,8 @@"jscpd-sarif-reporter": ["[email protected]", "", { "dependencies": { "colors": "^1.4.0", "fs-extra": "^11.2.0", "node-sarif-builder": "^4.1.0" } }, "sha512-O8LcM9grAS5yO5x1Q0yegYaYcUX//IEBEyvzGFSYCeo1YzHbMnAI6EK7oTrwD+7Csjvfg9m8B8G7OOxzcSlr9w=="],+ "jsep": ["[email protected]", "", {}, "sha512-B7qPcEVE3NVkmSJbaYxvv4cHkVW7DQsZz13pUMrfS8z8Q/BuShN+gcTXrUlPiGqM2/t/EEaI030bpxMqY8gMlw=="],+"jsesc": ["[email protected]", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="],"json-bigint": ["[email protected]", "", { "dependencies": { "bignumber.js": "^9.0.0" } }, "sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ=="],diff --git a/packages/core/package.json b/packages/core/package.jsonindex 096b4ecc8..6b3490adf 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -194,11 +194,11 @@"destr": "^2.0.5","diff": "^8.0.4","es-toolkit": "^1.51.0",- "expr-eval": "^2.0.2","fflate": "^0.8.3","fontoxpath": "^3.34.0","fzstd": "^0.1.1","js-base64": "^3.9.3",+ "jsep": "^1.4.0","jspdf": "^4.2.1","nanoevents": "^9.1.0","ofetch": "^1.5.1",diff --git a/packages/core/src/tools/calc.ts b/packages/core/src/tools/calc.tsindex 102dad4e5..999c6926f 100644--- a/packages/core/src/tools/calc.ts+++ b/packages/core/src/tools/calc.ts@@ -1,15 +1,13 @@-import ExprEval from 'expr-eval'import * as v from 'valibot'+import { CALC_FUNCTIONS, evaluateExpression } from './calc/expression'import { defineTool } from './schema'-const parser = new ExprEval.Parser()-function evalExpr(expr: string): { expr: string; result: number } | { expr: string; error: string } {try {- const result = parser.evaluate(expr)+ const result = evaluateExpression(expr)if (!Number.isFinite(result)) {return { expr, error: `Produced ${String(result)}` }}@@ -24,7 +22,7 @@ export const calc = defineTool({description:'Arithmetic calculator. ALWAYS use instead of mental math. ' +'Pass one expression or a JSON array of expressions — all evaluated in one call. ' +- 'Supports: + - * / % ** ( ) min max floor ceil round abs sqrt pow. ' ++ `Supports: + - * / % ** ( ) ${CALC_FUNCTIONS.join(' ')}. ` +'Examples: "844 - 56 - 96 - 82", \'["1440 * 8 / 12", "(952 - 16) / 2", "floor(390 * 0.6)"]\'',execution: { kind: 'sync', mutation: 'none' },exposure: { webmcp: false },diff --git a/packages/core/src/tools/calc/expression.ts b/packages/core/src/tools/calc/expression.tsnew file mode 100644index 000000000..341fa7087--- /dev/null+++ b/packages/core/src/tools/calc/expression.ts@@ -0,0 +1,150 @@+import jsep from 'jsep'++/**+ * Arithmetic expression evaluator for the `calc` tool.+ *+ * `jsep` parses; this module walks the resulting syntax tree and evaluates+ * only the arithmetic the tool documents. Expressions arrive from a model, so+ * nothing is compiled into JavaScript and no host object is reachable: every+ * node type, operator and function is matched against an allowlist, and+ * anything else — identifiers, member access, arrays, conditionals, comparison+ * and logical operators — is rejected with a message naming what was used.+ */++const smaller = (left: number, right: number): number => Math.min(left, right)+const larger = (left: number, right: number): number => Math.max(left, right)++/** Functions the tool documents, with their accepted argument counts. */+const FUNCTIONS = {+ // Folded rather than spread: a long argument list overflows the call stack+ // on V8 at roughly 125k arguments, which an expression can reach.+ min: { arity: [1, Number.POSITIVE_INFINITY], apply: (args: number[]) => args.reduce(smaller) },+ max: { arity: [1, Number.POSITIVE_INFINITY], apply: (args: number[]) => args.reduce(larger) },+ floor: { arity: [1, 1], apply: ([value]: number[]) => Math.floor(value) },+ ceil: { arity: [1, 1], apply: ([value]: number[]) => Math.ceil(value) },+ round: { arity: [1, 1], apply: ([value]: number[]) => Math.round(value) },+ abs: { arity: [1, 1], apply: ([value]: number[]) => Math.abs(value) },+ sqrt: { arity: [1, 1], apply: ([value]: number[]) => Math.sqrt(value) },+ pow: { arity: [2, 2], apply: ([base, exponent]: number[]) => base ** exponent }+} as const satisfies Record<+ string,+ { arity: readonly [number, number]; apply: (args: number[]) => number }+>++export type CalcFunction = keyof typeof FUNCTIONS++export const CALC_FUNCTIONS = Object.keys(FUNCTIONS) as CalcFunction[]++const BINARY_OPERATORS = new Map<string, (left: number, right: number) => number>([+ ['+', (left, right) => left + right],+ ['-', (left, right) => left - right],+ ['*', (left, right) => left * right],+ ['/', (left, right) => left / right],+ ['%', (left, right) => left % right],+ ['**', (left, right) => left ** right]+])++const UNARY_OPERATORS = new Map<string, (value: number) => number>([+ ['-', (value) => -value],+ ['+', (value) => value]+])++export const CALC_OPERATORS = [...BINARY_OPERATORS.keys()]++/** Raised for input outside the supported arithmetic; the message reaches the caller. */+export class CalcSyntaxError extends Error {+ constructor(message: string) {+ super(message)+ this.name = 'CalcSyntaxError'+ }+}++/** Human-readable name for a node the evaluator refuses, used in error messages. */+const UNSUPPORTED_NODES: Record<string, string> = {+ Identifier: 'a name',+ MemberExpression: 'property access',+ ArrayExpression: 'an array',+ Compound: 'more than one expression',+ ConditionalExpression: 'a conditional',+ ThisExpression: 'this'+}++function describeNode(node: jsep.Expression): string {+ return UNSUPPORTED_NODES[node.type] ?? `'${node.type}'`+}++function describeArity(minimum: number, maximum: number): string {+ if (minimum === maximum) return `${minimum} argument${minimum === 1 ? '' : 's'}`+ if (maximum === Number.POSITIVE_INFINITY) return `at least ${minimum} argument(s)`+ return `${minimum} to ${maximum} arguments`+}++function callFunction(node: jsep.CallExpression): number {+ const callee = node.callee+ if (callee.type !== 'Identifier') {+ throw new CalcSyntaxError(`Cannot call ${describeNode(callee)}`)+ }+ const name = (callee as jsep.Identifier).name+ // hasOwn, not `in`: inherited names such as `constructor` are not functions.+ if (!Object.hasOwn(FUNCTIONS, name)) {+ throw new CalcSyntaxError(`Unknown function '${name}'; supported: ${CALC_FUNCTIONS.join(', ')}`)+ }+ const args = node.arguments.map(evaluateNode)+ const { arity, apply } = FUNCTIONS[name as CalcFunction]+ const [minimum, maximum] = arity+ if (args.length < minimum || args.length > maximum) {+ throw new CalcSyntaxError(+ `'${name}' takes ${describeArity(minimum, maximum)}, received ${args.length}`+ )+ }+ return apply(args)+}++function evaluateNode(node: jsep.Expression): number {+ switch (node.type) {+ case 'Literal': {+ const { value, raw } = node as jsep.Literal+ if (typeof value !== 'number') {+ throw new CalcSyntaxError(`'${raw}' is not a number`)+ }+ return value+ }+ case 'UnaryExpression': {+ const { operator, argument } = node as jsep.UnaryExpression+ const apply = UNARY_OPERATORS.get(operator)+ if (!apply) throw new CalcSyntaxError(`Unsupported operator '${operator}'`)+ return apply(evaluateNode(argument))+ }+ case 'BinaryExpression': {+ const { operator, left, right } = node as jsep.BinaryExpression+ const apply = BINARY_OPERATORS.get(operator)+ if (!apply) {+ throw new CalcSyntaxError(+ `Unsupported operator '${operator}'; supported: ${CALC_OPERATORS.join(' ')}`+ )+ }+ return apply(evaluateNode(left), evaluateNode(right))+ }+ case 'CallExpression':+ return callFunction(node as jsep.CallExpression)+ default:+ throw new CalcSyntaxError(`Expression uses ${describeNode(node)}, which calc does not accept`)+ }+}++/**+ * Evaluate an arithmetic expression. Throws `CalcSyntaxError` for input the+ * parser rejects or the allowlist refuses; a well-formed expression may still+ * return a non-finite number, which the caller reports rather than this module.+ */+export function evaluateExpression(source: string): number {+ if (source.trim() === '') throw new CalcSyntaxError('Expression is empty')+ let tree: jsep.Expression+ try {+ tree = jsep(source)+ } catch (error) {+ // jsep's own messages already name the offending character and position.+ throw new CalcSyntaxError(error instanceof Error ? error.message : String(error))+ }+ return evaluateNode(tree)+}diff --git a/tests/engine/tools/calc/expression.test.ts b/tests/engine/tools/calc/expression.test.tsnew file mode 100644index 000000000..07eb837f2--- /dev/null+++ b/tests/engine/tools/calc/expression.test.ts@@ -0,0 +1,195 @@+import { describe, expect, test } from 'bun:test'++import {+ CALC_FUNCTIONS,+ CalcSyntaxError,+ evaluateExpression+} from '@open-pencil/core/tools/calc/expression'++describe('calc expression evaluator', () => {+ test.each([+ ['844 - 56 - 96 - 82', 610],+ ['1440 * 8 / 12', 960],+ ['(952 - 16) / 2', 468],+ [' 8 * 4 ', 32],+ ['2 + 2 * 2', 6],+ ['(2 + 2) * 2', 8],+ ['7 / 2', 3.5],+ ['10 % 3', 1],+ ['-10 % 3', -1],+ ['1e3', 1000],+ ['1E3 + 1', 1001],+ ['.5 + 1', 1.5],+ ['1.', 1],+ ['2.5e-2', 0.025]+ ])('evaluates %s', (expression, expected) => {+ expect(evaluateExpression(expression)).toBe(expected)+ })++ test.each([+ ['-5', -5],+ ['+5', 5],+ ['3 - -2', 5],+ ['3 * -2', -6],+ ['-(2 + 3)', -5]+ ])('applies the sign in %s', (expression, expected) => {+ expect(evaluateExpression(expression)).toBe(expected)+ })++ describe('exponentiation', () => {+ test('is right-associative', () => {+ expect(evaluateExpression('2 ** 3 ** 2')).toBe(512)+ })++ // jsep binds a leading sign tighter than `**`, so `-2 ** 2` is `(-2) ** 2`.+ // Pinned because Python and ordinary notation instead read it as `-(2 ** 2)`.+ test('applies a leading sign before the exponent', () => {+ expect(evaluateExpression('-2 ** 2')).toBe(4)+ expect(evaluateExpression('(-2) ** 2')).toBe(4)+ expect(evaluateExpression('-(2 ** 2)')).toBe(-4)+ })++ test('binds tighter than multiplication and accepts a signed exponent', () => {+ expect(evaluateExpression('3 * 2 ** 3')).toBe(24)+ expect(evaluateExpression('2 ** -2')).toBe(0.25)+ })+ })++ describe('functions', () => {+ test.each([+ ['floor(390 * 0.6)', 234],+ ['ceil(1.2)', 2],+ ['round(2.5)', 3],+ ['round(-2.5)', -2],+ ['abs(-4)', 4],+ ['sqrt(16)', 4],+ ['pow(2, 10)', 1024],+ ['min(3, 1, 2)', 1],+ ['max(3, 1, 2)', 3],+ ['min(3)', 3],+ ['max(1 + 1, 3 - 2)', 2],+ ['floor(min(4.7, 9))', 4]+ ])('evaluates %s', (expression, expected) => {+ expect(evaluateExpression(expression)).toBe(expected)+ })++ test('rejects a wrong argument count', () => {+ expect(() => evaluateExpression('round(2.345, 2)')).toThrow(/takes 1 argument, received 2/)+ expect(() => evaluateExpression('pow(2)')).toThrow(/takes 2 arguments, received 1/)+ })++ test.each(['min', 'max'])('folds a long %s argument list without spreading it', (name) => {+ // Spreading overflows the call stack on V8 at roughly 125k arguments.+ const args = Array.from({ length: 200_000 }, (_, index) => index)+ expect(evaluateExpression(`${name}(${args.join(',')})`)).toBe(name === 'min' ? 0 : 199_999)+ })++ test('names the supported functions when one is unknown', () => {+ expect(() => evaluateExpression('sin(0)')).toThrow(/Unknown function 'sin'/)+ for (const name of CALC_FUNCTIONS) {+ expect(() => evaluateExpression('sin(0)')).toThrow(new RegExp(`\\b${name}\\b`))+ }+ })+ })++ describe('results outside the real numbers', () => {+ test.each([+ ['1 / 0', Number.POSITIVE_INFINITY],+ ['-1 / 0', Number.NEGATIVE_INFINITY]+ ])('returns %s as a non-finite number for the caller to report', (expression, expected) => {+ expect(evaluateExpression(expression)).toBe(expected)+ })++ test.each(['0 / 0', 'sqrt(-1)', '0 % 0'])('returns NaN for %s', (expression) => {+ expect(evaluateExpression(expression)).toBeNaN()+ })+ })++ describe('input the evaluator refuses', () => {+ test.each([+ ['', 'Expression is empty'],+ [' ', 'Expression is empty'],+ ['1 +', 'Expected expression after +'],+ ['(1 + 2', 'Unclosed ('],+ ['1 + 2)', 'Unexpected ")"'],+ ['pow(2, 10', 'Expected )'],+ ['5!', 'missing unaryOp argument'],+ ['1_000 + 1', 'Variable names cannot start with a number'],+ ['0x10', 'Variable names cannot start with a number'],+ ['{"a": 1}', 'Unexpected "{"']+ ])("reports the parser's own message for %s", (expression, message) => {+ expect(() => evaluateExpression(expression)).toThrow(CalcSyntaxError)+ expect(() => evaluateExpression(expression)).toThrow(message)+ })++ test.each([+ ['1 2', 'more than one expression'],+ ['1 ; 2', 'more than one expression'],+ ['3 and 4', 'more than one expression'],+ ['floor 1', 'more than one expression'],+ ['x + 1', 'a name'],+ ['PI', 'a name'],+ ['12 + $', 'a name'],+ ['a.b', 'property access'],+ ['[1,2][0]', 'property access'],+ ['1 ? 2 : 3', 'a conditional']+ ])('names the construct it refuses in %s', (expression, description) => {+ expect(() => evaluateExpression(expression)).toThrow(CalcSyntaxError)+ expect(() => evaluateExpression(expression)).toThrow(description)+ })++ test.each([+ ['2 < 3', "Unsupported operator '<'"],+ ['1 == 1', "Unsupported operator '=='"],+ ['1 || 2', "Unsupported operator '||'"],+ ['3 & 4', "Unsupported operator '&'"]+ ])('refuses the non-arithmetic operator in %s', (expression, message) => {+ expect(() => evaluateExpression(expression)).toThrow(message)+ })++ test.each([+ ['"a" + "b"', 'is not a number'],+ ['true', "'true' is not a number"],+ ['null', "'null' is not a number"]+ ])('refuses the non-numeric literal in %s', (expression, message) => {+ expect(() => evaluateExpression(expression)).toThrow(message)+ })++ test.each([+ ['random()', "Unknown function 'random'"],+ ['if(1, 2, 3)', "Unknown function 'if'"],+ ['sin(0)', "Unknown function 'sin'"]+ ])('refuses the undocumented function in %s', (expression, message) => {+ expect(() => evaluateExpression(expression)).toThrow(message)+ })++ test('keeps the character position the parser reports', () => {+ expect(() => evaluateExpression('(1 + 2')).toThrow('character 6')+ })++ test.each([+ 'constructor(1)',+ 'toString(1)',+ 'valueOf(1)',+ 'hasOwnProperty(1)',+ '__defineGetter__(1)'+ ])('refuses %s, an inherited name rather than a function', (expression) => {+ expect(() => evaluateExpression(expression)).toThrow(CalcSyntaxError)+ expect(() => evaluateExpression(expression)).toThrow('Unknown function')+ })+ })++ test.each([+ 'constructor',+ 'globalThis',+ 'this',+ 'process',+ 'Math',+ 'Math.random()',+ 'Function("return 1")()',+ '__proto__',+ 'constructor.constructor("return 1")()'+ ])('evaluates %s without reaching a host object', (expression) => {+ expect(() => evaluateExpression(expression)).toThrow(CalcSyntaxError)+ })+})diff --git a/tests/engine/tools/calc/tool.test.ts b/tests/engine/tools/calc/tool.test.tsnew file mode 100644index 000000000..e3905ae15--- /dev/null+++ b/tests/engine/tools/calc/tool.test.ts@@ -0,0 +1,59 @@+import { describe, expect, test } from 'bun:test'++import { getTool, setupToolTest, type ToolResult } from '#tests/helpers/tools'++function run(expr: string): ToolResult {+ const { figma } = setupToolTest()+ return getTool('calc').execute(figma, { expr }) as ToolResult+}++describe('calc tool', () => {+ test('returns a single result for one expression', () => {+ expect(run('844 - 56 - 96 - 82')).toEqual({ expr: '844 - 56 - 96 - 82', result: 610 })+ })++ test('evaluates a JSON array in one call, preserving order', () => {+ expect(run('["1440 * 8 / 12", "(952 - 16) / 2", "floor(390 * 0.6)"]')).toEqual({+ results: [+ { expr: '1440 * 8 / 12', result: 960 },+ { expr: '(952 - 16) / 2', result: 468 },+ { expr: 'floor(390 * 0.6)', result: 234 }+ ]+ })+ })++ test('treats a single-element array like a bare expression', () => {+ expect(run('["2 + 2"]')).toEqual({ expr: '2 + 2', result: 4 })+ })++ test('reports the documented ** operator', () => {+ expect(run('2 ** 10')).toEqual({ expr: '2 ** 10', result: 1024 })+ })++ test('reports a non-finite result as an error rather than a number', () => {+ expect(run('1 / 0')).toEqual({ expr: '1 / 0', error: 'Produced Infinity' })+ expect(run('0 / 0')).toEqual({ expr: '0 / 0', error: 'Produced NaN' })+ })++ test('reports a rejected expression without failing its siblings', () => {+ const result = run('["2 + 2", "2 +", "3 * 3"]')+ expect(result.results).toEqual([+ { expr: '2 + 2', result: 4 },+ { expr: '2 +', error: 'Expected expression after + at character 3' },+ { expr: '3 * 3', result: 9 }+ ])+ })++ test('evaluates text that only looks like JSON as an expression', () => {+ expect(run('2 + 2')).toEqual({ expr: '2 + 2', result: 4 })+ expect((run('{"a": 1}') as { error: string }).error).toContain('Unexpected "{"')+ })++ test('advertises exactly the functions it supports', () => {+ const { description } = getTool('calc')+ for (const name of ['min', 'max', 'floor', 'ceil', 'round', 'abs', 'sqrt', 'pow']) {+ expect(description).toContain(name)+ }+ expect(description).toContain('**')+ })+})