@openforis/arena-core 2.21.1 → 2.21.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,7 +10,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  import { SystemError, SystemErrorKeys } from '../../../error';
11
11
  import { ExpressionNodeEvaluator, ExpressionNodeType, } from '../../node';
12
12
  import { getGlobalObjectProperty } from '../global';
13
- import { hasNestedQuantifiers, REG_EXP_INPUT_MAX_LENGTH } from '../regExpSafety';
13
+ import { isUnsafeRegExpSource, REG_EXP_INPUT_MAX_LENGTH } from '../regExpSafety';
14
14
  // String functions converting a string argument into a regular expression (replace, replaceAll and split don't)
15
15
  const stringFunctionsWithRegExpArgument = new Set(['match', 'matchAll', 'search']);
16
16
  // e.g. text.match('(a+)+$'): the string pattern is checked like a regular expression literal
@@ -22,7 +22,7 @@ const isRegExpStringPatternCall = (callee, args) => {
22
22
  typeof args[0] === 'string');
23
23
  };
24
24
  const checkRegExpStringPattern = (pattern) => {
25
- if (hasNestedQuantifiers(pattern)) {
25
+ if (isUnsafeRegExpSource(pattern)) {
26
26
  throw new SystemError(SystemErrorKeys.expression.unsafeRegularExpression, { pattern });
27
27
  }
28
28
  };
@@ -1 +1 @@
1
- {"version":3,"file":"call.js","sourceRoot":"","sources":["../../../../../src/expression/javascript/node/call.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAA;AAG7D,OAAO,EAEL,uBAAuB,EACvB,kBAAkB,GAInB,MAAM,YAAY,CAAA;AACnB,OAAO,EAAE,uBAAuB,EAAE,MAAM,WAAW,CAAA;AACnD,OAAO,EAAE,oBAAoB,EAAE,wBAAwB,EAAE,MAAM,iBAAiB,CAAA;AAEhF,gHAAgH;AAChH,MAAM,iCAAiC,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,UAAU,EAAE,QAAQ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QAAQ,EAAE,OAAO,EAAE,CAAC,CAAA;YAE9G,qBAAqB;YACrB,MAAM,WAAW,mCAAQ,IAAI,CAAC,OAAO,KAAE,cAAc,EAAE,mBAAmB,GAAE,CAAA;YAC5E,MAAM,IAAI,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC,CAAC,CAAA;YAEpG,uEAAuE;YACvE,wEAAwE;YACxE,sCAAsC;YACtC,OAAO,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAAA;QACxC,CAAC;KAAA;CACF","sourcesContent":["import { SystemError, SystemErrorKeys } from '../../../error'\nimport { ExpressionContext } from '../../context'\nimport { ExpressionFunction } from '../../function'\nimport {\n CallExpression,\n ExpressionNodeEvaluator,\n ExpressionNodeType,\n IdentifierExpression,\n LiteralExpression,\n MemberExpression,\n} from '../../node'\nimport { getGlobalObjectProperty } from '../global'\nimport { hasNestedQuantifiers, REG_EXP_INPUT_MAX_LENGTH } from '../regExpSafety'\n\n// String functions converting a string argument into a regular expression (replace, replaceAll and split don't)\nconst stringFunctionsWithRegExpArgument = new Set(['match', 'matchAll', 'search'])\n\n// e.g. text.match('(a+)+$'): the string pattern is checked like a regular expression literal\nconst isRegExpStringPatternCall = (callee: MemberExpression, args: any[]): boolean => {\n const { computed, property } = callee\n return (\n !computed &&\n property.type === ExpressionNodeType.Identifier &&\n stringFunctionsWithRegExpArgument.has((property as IdentifierExpression).name) &&\n typeof args[0] === 'string'\n )\n}\n\nconst checkRegExpStringPattern = (pattern: string): void => {\n if (hasNestedQuantifiers(pattern)) {\n throw new SystemError(SystemErrorKeys.expression.unsafeRegularExpression, { pattern })\n }\n}\n\n// e.g. /.../.test(text) or text.match(/.../): the time taken by a regular expression grows with the input length\nconst checkRegExpInputLength = (fnObject: any, args: any[], regExpStringPattern: boolean): void => {\n const values = [fnObject, ...args]\n if (!regExpStringPattern && !values.some((value) => value instanceof RegExp)) return\n const inputTooLong = values.find((value) => typeof value === 'string' && value.length > REG_EXP_INPUT_MAX_LENGTH)\n if (inputTooLong !== undefined) {\n throw new SystemError(SystemErrorKeys.expression.regularExpressionInputTooLong, {\n maxLength: REG_EXP_INPUT_MAX_LENGTH,\n length: inputTooLong.length,\n })\n }\n}\n\nexport class CallEvaluator<C extends ExpressionContext> extends ExpressionNodeEvaluator<C, CallExpression> {\n async evaluate(expressionNode: CallExpression): Promise<any> {\n const { callee } = expressionNode\n\n if (callee.type === ExpressionNodeType.Member) {\n return this.evaluateMember(expressionNode, callee)\n } else if (callee.type === ExpressionNodeType.Identifier) {\n return this.evaluateIdentifier(expressionNode, callee)\n }\n\n // No complex expressions may be put in place of a function body.\n // Only a plain identifier is allowed.\n throw new SystemError(SystemErrorKeys.expression.invalidCalleeType, { type: callee.type })\n }\n\n private async evaluateMember(expressionNode: CallExpression, callee: MemberExpression): Promise<any> {\n const { arguments: exprArgs } = expressionNode\n\n // evaluate the callee object only once: evaluating it again to find the function would take exponential time\n // with chained calls (e.g. text.trim().toUpperCase().toLowerCase())\n const fnObject = await this.evaluator.evaluateNode(callee.object, this.context)\n if (fnObject === null || fnObject === undefined) return null\n\n // find the function (e.g. Math.round or text.toUpperCase) among the properties of the already evaluated object\n const fnObjectLiteral: LiteralExpression = { type: ExpressionNodeType.Literal, value: fnObject, raw: '' }\n const calleeWithObjectEvaluated: MemberExpression = { ...callee, object: fnObjectLiteral }\n const fn = await this.evaluator.evaluateNode(calleeWithObjectEvaluated, this.context)\n if (fn) {\n const argsEvaluated = await Promise.all(exprArgs.map((arg) => this.evaluator.evaluateNode(arg, this.context)))\n const args = argsEvaluated.flat()\n const regExpStringPattern = isRegExpStringPatternCall(callee, args)\n if (regExpStringPattern) {\n checkRegExpStringPattern(args[0])\n }\n checkRegExpInputLength(fnObject, args, regExpStringPattern)\n return fn.call(fnObject, ...args)\n }\n return null\n }\n\n private async evaluateIdentifier(expressionNode: CallExpression, callee: IdentifierExpression): Promise<any> {\n // Arguments is a reserved word in strict mode\n const { arguments: exprArgs } = expressionNode\n const { object: contextObject } = this.context\n\n const { name: fnName } = callee\n\n const functionInfo = this.evaluator.functions[fnName]\n if (functionInfo) {\n // The function is among the custom functions.\n return this.evaluateCustomIdentifier(expressionNode, fnName)\n }\n // identifier is a global object\n const globalFn = getGlobalObjectProperty(fnName, contextObject)\n if (globalFn !== null) {\n // global functions like String, Number, must be invoked passing node value as argument, not the node itself\n const contextArg = { ...this.context, evaluateToNode: false }\n const args = await Promise.all(exprArgs.map((arg) => this.evaluator.evaluateNode(arg, contextArg)))\n return globalFn(...args)\n }\n\n throw new SystemError(SystemErrorKeys.expression.undefinedFunction, { name: fnName })\n }\n\n private async evaluateCustomIdentifier(expressionNode: CallExpression, fnName: string): Promise<any> {\n // Arguments is a reserved word in strict mode\n const { arguments: exprArgs } = expressionNode\n const numArgs = exprArgs.length\n\n const expressionFunction: ExpressionFunction<C> = this.evaluator.functions[fnName]\n\n const { minArity, maxArity, evaluateArgsToNodes, executor } = expressionFunction\n\n if (numArgs < minArity)\n throw new SystemError(SystemErrorKeys.expression.functionHasTooFewArguments, { fnName, minArity, numArgs })\n if (maxArity !== undefined && maxArity >= 0 && numArgs > maxArity)\n throw new SystemError(SystemErrorKeys.expression.functionHasTooManyArguments, { fnName, maxArity, numArgs })\n\n // evaluate arguments\n const argsContext = { ...this.context, evaluateToNode: evaluateArgsToNodes }\n const args = await Promise.all(exprArgs.map((arg) => this.evaluator.evaluateNode(arg, argsContext)))\n\n // Currently there are no side effects from function evaluation so it's\n // safe to call the function even when we're just parsing the expression\n // to find all identifiers being used.\n return executor(this.context)(...args)\n }\n}\n"]}
1
+ {"version":3,"file":"call.js","sourceRoot":"","sources":["../../../../../src/expression/javascript/node/call.ts"],"names":[],"mappings":";;;;;;;;;AAAA,OAAO,EAAE,WAAW,EAAE,e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,GAAG,QAAQ;gBACpB,MAAM,IAAI,WAAW,CAAC,eAAe,CAAC,UAAU,CAAC,0BAA0B,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAA;YAC7G,IAAI,QAAQ,KAAK,SAAS,IAAI,QAAQ,IAAI,CAAC,IAAI,OAAO,GAAG,QAAQ;gBAC/D,MAAM,IAAI,WAAW,CAAC,eAAe,CAAC,UAAU,CAAC,2BAA2B,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAA;YAE9G,qBAAqB;YACrB,MAAM,WAAW,mCAAQ,IAAI,CAAC,OAAO,KAAE,cAAc,EAAE,mBAAmB,GAAE,CAAA;YAC5E,MAAM,IAAI,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC,CAAC,CAAA;YAEpG,uEAAuE;YACvE,wEAAwE;YACxE,sCAAsC;YACtC,OAAO,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAAA;QACxC,CAAC;KAAA;CACF","sourcesContent":["import { SystemError, SystemErrorKeys } from '../../../error'\nimport { ExpressionContext } from '../../context'\nimport { ExpressionFunction } from '../../function'\nimport {\n CallExpression,\n ExpressionNodeEvaluator,\n ExpressionNodeType,\n IdentifierExpression,\n LiteralExpression,\n MemberExpression,\n} from '../../node'\nimport { getGlobalObjectProperty } from '../global'\nimport { isUnsafeRegExpSource, REG_EXP_INPUT_MAX_LENGTH } from '../regExpSafety'\n\n// String functions converting a string argument into a regular expression (replace, replaceAll and split don't)\nconst stringFunctionsWithRegExpArgument = new Set(['match', 'matchAll', 'search'])\n\n// e.g. text.match('(a+)+$'): the string pattern is checked like a regular expression literal\nconst isRegExpStringPatternCall = (callee: MemberExpression, args: any[]): boolean => {\n const { computed, property } = callee\n return (\n !computed &&\n property.type === ExpressionNodeType.Identifier &&\n stringFunctionsWithRegExpArgument.has((property as IdentifierExpression).name) &&\n typeof args[0] === 'string'\n )\n}\n\nconst checkRegExpStringPattern = (pattern: string): void => {\n if (isUnsafeRegExpSource(pattern)) {\n throw new SystemError(SystemErrorKeys.expression.unsafeRegularExpression, { pattern })\n }\n}\n\n// e.g. /.../.test(text) or text.match(/.../): the time taken by a regular expression grows with the input length\nconst checkRegExpInputLength = (fnObject: any, args: any[], regExpStringPattern: boolean): void => {\n const values = [fnObject, ...args]\n if (!regExpStringPattern && !values.some((value) => value instanceof RegExp)) return\n const inputTooLong = values.find((value) => typeof value === 'string' && value.length > REG_EXP_INPUT_MAX_LENGTH)\n if (inputTooLong !== undefined) {\n throw new SystemError(SystemErrorKeys.expression.regularExpressionInputTooLong, {\n maxLength: REG_EXP_INPUT_MAX_LENGTH,\n length: inputTooLong.length,\n })\n }\n}\n\nexport class CallEvaluator<C extends ExpressionContext> extends ExpressionNodeEvaluator<C, CallExpression> {\n async evaluate(expressionNode: CallExpression): Promise<any> {\n const { callee } = expressionNode\n\n if (callee.type === ExpressionNodeType.Member) {\n return this.evaluateMember(expressionNode, callee)\n } else if (callee.type === ExpressionNodeType.Identifier) {\n return this.evaluateIdentifier(expressionNode, callee)\n }\n\n // No complex expressions may be put in place of a function body.\n // Only a plain identifier is allowed.\n throw new SystemError(SystemErrorKeys.expression.invalidCalleeType, { type: callee.type })\n }\n\n private async evaluateMember(expressionNode: CallExpression, callee: MemberExpression): Promise<any> {\n const { arguments: exprArgs } = expressionNode\n\n // evaluate the callee object only once: evaluating it again to find the function would take exponential time\n // with chained calls (e.g. text.trim().toUpperCase().toLowerCase())\n const fnObject = await this.evaluator.evaluateNode(callee.object, this.context)\n if (fnObject === null || fnObject === undefined) return null\n\n // find the function (e.g. Math.round or text.toUpperCase) among the properties of the already evaluated object\n const fnObjectLiteral: LiteralExpression = { type: ExpressionNodeType.Literal, value: fnObject, raw: '' }\n const calleeWithObjectEvaluated: MemberExpression = { ...callee, object: fnObjectLiteral }\n const fn = await this.evaluator.evaluateNode(calleeWithObjectEvaluated, this.context)\n if (fn) {\n const argsEvaluated = await Promise.all(exprArgs.map((arg) => this.evaluator.evaluateNode(arg, this.context)))\n const args = argsEvaluated.flat()\n const regExpStringPattern = isRegExpStringPatternCall(callee, args)\n if (regExpStringPattern) {\n checkRegExpStringPattern(args[0])\n }\n checkRegExpInputLength(fnObject, args, regExpStringPattern)\n return fn.call(fnObject, ...args)\n }\n return null\n }\n\n private async evaluateIdentifier(expressionNode: CallExpression, callee: IdentifierExpression): Promise<any> {\n // Arguments is a reserved word in strict mode\n const { arguments: exprArgs } = expressionNode\n const { object: contextObject } = this.context\n\n const { name: fnName } = callee\n\n const functionInfo = this.evaluator.functions[fnName]\n if (functionInfo) {\n // The function is among the custom functions.\n return this.evaluateCustomIdentifier(expressionNode, fnName)\n }\n // identifier is a global object\n const globalFn = getGlobalObjectProperty(fnName, contextObject)\n if (globalFn !== null) {\n // global functions like String, Number, must be invoked passing node value as argument, not the node itself\n const contextArg = { ...this.context, evaluateToNode: false }\n const args = await Promise.all(exprArgs.map((arg) => this.evaluator.evaluateNode(arg, contextArg)))\n return globalFn(...args)\n }\n\n throw new SystemError(SystemErrorKeys.expression.undefinedFunction, { name: fnName })\n }\n\n private async evaluateCustomIdentifier(expressionNode: CallExpression, fnName: string): Promise<any> {\n // Arguments is a reserved word in strict mode\n const { arguments: exprArgs } = expressionNode\n const numArgs = exprArgs.length\n\n const expressionFunction: ExpressionFunction<C> = this.evaluator.functions[fnName]\n\n const { minArity, maxArity, evaluateArgsToNodes, executor } = expressionFunction\n\n if (numArgs < minArity)\n throw new SystemError(SystemErrorKeys.expression.functionHasTooFewArguments, { fnName, minArity, numArgs })\n if (maxArity !== undefined && maxArity >= 0 && numArgs > maxArity)\n throw new SystemError(SystemErrorKeys.expression.functionHasTooManyArguments, { fnName, maxArity, numArgs })\n\n // evaluate arguments\n const argsContext = { ...this.context, evaluateToNode: evaluateArgsToNodes }\n const args = await Promise.all(exprArgs.map((arg) => this.evaluator.evaluateNode(arg, argsContext)))\n\n // Currently there are no side effects from function evaluation so it's\n // safe to call the function even when we're just parsing the expression\n // to find all identifiers being used.\n return executor(this.context)(...args)\n }\n}\n"]}
@@ -1,10 +1,10 @@
1
1
  import { SystemError, SystemErrorKeys } from '../../../error';
2
2
  import { ExpressionNodeEvaluator } from '../../node';
3
- import { hasNestedQuantifiers } from '../regExpSafety';
3
+ import { isUnsafeRegExpSource } from '../regExpSafety';
4
4
  export class LiteralEvaluator extends ExpressionNodeEvaluator {
5
5
  evaluate(expressionNode) {
6
6
  const { value } = expressionNode;
7
- if (value instanceof RegExp && hasNestedQuantifiers(value.source)) {
7
+ if (value instanceof RegExp && isUnsafeRegExpSource(value.source)) {
8
8
  return Promise.reject(new SystemError(SystemErrorKeys.expression.unsafeRegularExpression, { pattern: value.source }));
9
9
  }
10
10
  return Promise.resolve(value);
@@ -1 +1 @@
1
- {"version":3,"file":"literal.js","sourceRoot":"","sources":["../../../../../src/expression/javascript/node/literal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAA;AAE7D,OAAO,EAAE,uBAAuB,EAAqB,MAAM,YAAY,CAAA;AACvE,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAA;AAEtD,MAAM,OAAO,gBAA8C,SAAQ,uBAA6C;IAC9G,QAAQ,CAAC,cAAiC;QACxC,MAAM,EAAE,KAAK,EAAE,GAAG,cAAc,CAAA;QAChC,IAAI,KAAK,YAAY,MAAM,IAAI,oBAAoB,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC;YAClE,OAAO,OAAO,CAAC,MAAM,CACnB,IAAI,WAAW,CAAC,eAAe,CAAC,UAAU,CAAC,uBAAuB,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAC/F,CAAA;QACH,CAAC;QACD,OAAO,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAA;IAC/B,CAAC;CACF","sourcesContent":["import { SystemError, SystemErrorKeys } from '../../../error'\nimport { ExpressionContext } from '../../context'\nimport { ExpressionNodeEvaluator, LiteralExpression } from '../../node'\nimport { hasNestedQuantifiers } from '../regExpSafety'\n\nexport class LiteralEvaluator<C extends ExpressionContext> extends ExpressionNodeEvaluator<C, LiteralExpression> {\n evaluate(expressionNode: LiteralExpression): Promise<any> {\n const { value } = expressionNode\n if (value instanceof RegExp && hasNestedQuantifiers(value.source)) {\n return Promise.reject(\n new SystemError(SystemErrorKeys.expression.unsafeRegularExpression, { pattern: value.source })\n )\n }\n return Promise.resolve(value)\n }\n}\n"]}
1
+ {"version":3,"file":"literal.js","sourceRoot":"","sources":["../../../../../src/expression/javascript/node/literal.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAA;AAE7D,OAAO,EAAE,uBAAuB,EAAqB,MAAM,YAAY,CAAA;AACvE,OAAO,EAAE,oBAAoB,EAAE,MAAM,iBAAiB,CAAA;AAEtD,MAAM,OAAO,gBAA8C,SAAQ,uBAA6C;IAC9G,QAAQ,CAAC,cAAiC;QACxC,MAAM,EAAE,KAAK,EAAE,GAAG,cAAc,CAAA;QAChC,IAAI,KAAK,YAAY,MAAM,IAAI,oBAAoB,CAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC;YAClE,OAAO,OAAO,CAAC,MAAM,CACnB,IAAI,WAAW,CAAC,eAAe,CAAC,UAAU,CAAC,uBAAuB,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAC/F,CAAA;QACH,CAAC;QACD,OAAO,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAA;IAC/B,CAAC;CACF","sourcesContent":["import { SystemError, SystemErrorKeys } from '../../../error'\nimport { ExpressionContext } from '../../context'\nimport { ExpressionNodeEvaluator, LiteralExpression } from '../../node'\nimport { isUnsafeRegExpSource } from '../regExpSafety'\n\nexport class LiteralEvaluator<C extends ExpressionContext> extends ExpressionNodeEvaluator<C, LiteralExpression> {\n evaluate(expressionNode: LiteralExpression): Promise<any> {\n const { value } = expressionNode\n if (value instanceof RegExp && isUnsafeRegExpSource(value.source)) {\n return Promise.reject(\n new SystemError(SystemErrorKeys.expression.unsafeRegularExpression, { pattern: value.source })\n )\n }\n return Promise.resolve(value)\n }\n}\n"]}
@@ -4,8 +4,12 @@
4
4
  */
5
5
  // maximum length of the strings that regular expressions are applied to in expressions
6
6
  export const REG_EXP_INPUT_MAX_LENGTH = 1000;
7
- // unbounded quantifier at the given position: *, + or {n,} (quantifiers like {n} or {n,m} are bounded)
8
- const unboundedQuantifierRegExp = /^(\*|\+|\{\d+,\})/;
7
+ // repetitions of a group with a higher maximum (e.g. {1,1000}) are as dangerous as unbounded ones
8
+ const GROUP_REPETITIONS_MAX = 3;
9
+ // characters that, right after an atom, quantify it (including "?", which makes it optional)
10
+ const quantifierStartChars = new Set(['*', '+', '?', '{']);
11
+ // characters with a special meaning outside character classes
12
+ const specialChars = new Set(['\\', '[', ']', '(', ')', '|', '.', '^', '$', '*', '+', '?', '{', '}']);
9
13
  const isQuantifierAt = (source, index) => {
10
14
  const char = source[index];
11
15
  if (char === '*' || char === '+')
@@ -13,6 +17,22 @@ const isQuantifierAt = (source, index) => {
13
17
  // {n,m} or {n,} (exact {n} repetitions don't multiply the ways a string can be matched)
14
18
  return char === '{' && /^\{\d+,\d*\}/.test(source.substring(index));
15
19
  };
20
+ /**
21
+ * Returns true if the quantifier at the specified index repeats the preceding atom an unbounded number of times:
22
+ * *, +, {n,} or {n,m} with m greater than GROUP_REPETITIONS_MAX.
23
+ */
24
+ const isUnboundedQuantifierAt = (source, index) => {
25
+ const char = source[index];
26
+ if (char === '*' || char === '+')
27
+ return true;
28
+ const match = /^\{\d+(,(\d*))?\}/.exec(source.substring(index));
29
+ if (!match)
30
+ return false;
31
+ const [, comma, max] = match;
32
+ if (!comma)
33
+ return false; // exact {n}
34
+ return !max || Number(max) > GROUP_REPETITIONS_MAX;
35
+ };
16
36
  const skipEscape = (index) => index + 2;
17
37
  const skipCharacterClass = (source, index) => {
18
38
  let i = index + 1;
@@ -21,35 +41,93 @@ const skipCharacterClass = (source, index) => {
21
41
  }
22
42
  return i + 1;
23
43
  };
24
- // marks the innermost open group (if any) as containing a quantifier
25
- const markInnermostGroupQuantified = (groupsStack) => {
26
- if (groupsStack.length > 0) {
27
- groupsStack[groupsStack.length - 1] = true;
44
+ // skips "(" and the group modifier, if any: (?:, (?=, (?!, (?<=, (?<! or (?<name>
45
+ const skipGroupStart = (source, index) => {
46
+ if (source[index + 1] !== '?')
47
+ return index + 1;
48
+ if (source[index + 2] === '<' && source[index + 3] !== '=' && source[index + 3] !== '!') {
49
+ const nameEnd = source.indexOf('>', index + 3);
50
+ return nameEnd < 0 ? source.length : nameEnd + 1;
28
51
  }
52
+ return source[index + 2] === '<' ? index + 4 : index + 3;
53
+ };
54
+ /**
55
+ * Returns the literal character that the alternative starting at the specified index must start with,
56
+ * or null if it can start with different characters (character class, ".", group, optional atom etc.)
57
+ * or it can be empty.
58
+ */
59
+ const getAlternativeFirstChar = (source, index) => {
60
+ const char = source[index];
61
+ let literal;
62
+ let atomLength;
63
+ if (char === undefined) {
64
+ return null;
65
+ }
66
+ else if (char === '\\') {
67
+ // escaped letters and digits are character classes (\d, \w...), assertions (\b) or back references
68
+ const escapedChar = source[index + 1];
69
+ literal = escapedChar !== undefined && !/[a-zA-Z0-9]/.test(escapedChar) ? escapedChar : null;
70
+ atomLength = 2;
71
+ }
72
+ else {
73
+ literal = specialChars.has(char) ? null : char;
74
+ atomLength = 1;
75
+ }
76
+ if (literal === null || quantifierStartChars.has(source[index + atomLength]))
77
+ return null;
78
+ // case insensitive comparison: the regular expression could use the "i" flag
79
+ return literal.toLowerCase();
80
+ };
81
+ const createGroupState = (source, contentStartIndex) => ({
82
+ quantified: false,
83
+ ambiguous: false,
84
+ alternativesFirstChars: [getAlternativeFirstChar(source, contentStartIndex)],
85
+ });
86
+ /**
87
+ * Alternatives are considered unambiguous only if they all start with different literal characters:
88
+ * then at most one of them can match at any position.
89
+ */
90
+ const hasAmbiguousAlternatives = (group) => {
91
+ const { alternativesFirstChars } = group;
92
+ if (alternativesFirstChars.length < 2)
93
+ return false;
94
+ if (alternativesFirstChars.includes(null))
95
+ return true;
96
+ return new Set(alternativesFirstChars).size < alternativesFirstChars.length;
29
97
  };
30
98
  /**
31
99
  * Closes the group ending at the specified index (position of the ")").
32
- * Returns true if the group contains a quantifier and it's repeated by an unbounded quantifier.
100
+ * Returns true if the group contains a quantifier or ambiguous alternatives and it's repeated
101
+ * by an unbounded quantifier.
33
102
  */
34
103
  const closeGroup = (source, index, groupsStack) => {
35
- var _a;
36
- const groupContainsQuantifier = (_a = groupsStack.pop()) !== null && _a !== void 0 ? _a : false;
37
- if (groupContainsQuantifier && unboundedQuantifierRegExp.test(source.substring(index + 1))) {
104
+ const group = groupsStack.pop();
105
+ if (!group)
106
+ return false;
107
+ const ambiguous = group.ambiguous || hasAmbiguousAlternatives(group);
108
+ if ((group.quantified || ambiguous) && isUnboundedQuantifierAt(source, index + 1)) {
38
109
  return true;
39
110
  }
40
- if (groupContainsQuantifier || isQuantifierAt(source, index + 1)) {
41
- markInnermostGroupQuantified(groupsStack);
111
+ const parent = groupsStack.at(-1);
112
+ if (parent) {
113
+ parent.quantified = parent.quantified || group.quantified || isQuantifierAt(source, index + 1);
114
+ // the parent group could be repeated
115
+ parent.ambiguous = parent.ambiguous || ambiguous;
42
116
  }
43
117
  return false;
44
118
  };
45
119
  /**
46
120
  * Returns true if the specified regular expression source contains a group repeated by an unbounded quantifier
47
- * that contains a quantifier itself (star height > 1), e.g. (a+)+, (\w*)* or (x{1,3})+:
48
- * these patterns can take exponential time on non-matching strings.
49
- * Overlapping alternations like (a|aa)+ are not detected.
121
+ * (*, +, {n,} or {n,m} with a high m) that contains:
122
+ * - a quantifier itself (star height > 1), e.g. (a+)+, (\w*)* or (x{1,3})+
123
+ * - alternatives that can match the same string, e.g. (a|aa)+, (a|.)* or (\d|-)+
124
+ * (alternatives are considered safe only if they start with different literal characters, e.g. (ab|cd)+).
125
+ * These patterns can take exponential time on non-matching strings.
126
+ * Note: patterns taking polynomial time (e.g. a+a+a+$) are not detected; the time they take is limited by
127
+ * the maximum length of the input strings (REG_EXP_INPUT_MAX_LENGTH).
50
128
  */
51
- export const hasNestedQuantifiers = (source) => {
52
- // for each open group: true if it contains a quantifier
129
+ export const isUnsafeRegExpSource = (source) => {
130
+ var _a;
53
131
  const groupsStack = [];
54
132
  let i = 0;
55
133
  while (i < source.length) {
@@ -60,21 +138,28 @@ export const hasNestedQuantifiers = (source) => {
60
138
  case '[':
61
139
  i = skipCharacterClass(source, i);
62
140
  break;
63
- case '(':
64
- groupsStack.push(false);
65
- // a "?" right after "(" introduces a group modifier (e.g. "(?:"), it's not a quantifier
66
- i += source[i + 1] === '?' ? 2 : 1;
141
+ case '(': {
142
+ i = skipGroupStart(source, i);
143
+ groupsStack.push(createGroupState(source, i));
144
+ break;
145
+ }
146
+ case '|': {
147
+ (_a = groupsStack.at(-1)) === null || _a === void 0 ? void 0 : _a.alternativesFirstChars.push(getAlternativeFirstChar(source, i + 1));
148
+ i += 1;
67
149
  break;
150
+ }
68
151
  case ')':
69
152
  if (closeGroup(source, i, groupsStack))
70
153
  return true;
71
154
  i += 1;
72
155
  break;
73
- default:
74
- if (isQuantifierAt(source, i)) {
75
- markInnermostGroupQuantified(groupsStack);
156
+ default: {
157
+ const group = groupsStack.at(-1);
158
+ if (group && isQuantifierAt(source, i)) {
159
+ group.quantified = true;
76
160
  }
77
161
  i += 1;
162
+ }
78
163
  }
79
164
  }
80
165
  return false;
@@ -1 +1 @@
1
- {"version":3,"file":"regExpSafety.js","sourceRoot":"","sources":["../../../../src/expression/javascript/regExpSafety.ts"],"names":[],"mappings":"AAAA;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AK;YACP;gBACE,IAAI,cAAc,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,CAAC;oBAC9B,4BAA4B,CAAC,WAAW,CAAC,CAAA;gBAC3C,CAAC;gBACD,CAAC,IAAI,CAAC,CAAA;QACV,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC,CAAA","sourcesContent":["/**\n * Protection against regular expressions that can take exponential time (ReDoS): JavaScript cannot interrupt a\n * running regular expression, so a single evaluation could freeze the server or the browser.\n */\n\n// maximum length of the strings that regular expressions are applied to in expressions\nexport const REG_EXP_INPUT_MAX_LENGTH = 1000\n\n// unbounded quantifier at the given position: *, + or {n,} (quantifiers like {n} or {n,m} are bounded)\nconst unboundedQuantifierRegExp = /^(\\*|\\+|\\{\\d+,\\})/\n\nconst isQuantifierAt = (source: string, index: number): boolean => {\n const char = source[index]\n if (char === '*' || char === '+') return true\n // {n,m} or {n,} (exact {n} repetitions don't multiply the ways a string can be matched)\n return char === '{' && /^\\{\\d+,\\d*\\}/.test(source.substring(index))\n}\n\nconst skipEscape = (index: number): number => index + 2\n\nconst skipCharacterClass = (source: string, index: number): number => {\n let i = index + 1\n while (i < source.length && source[i] !== ']') {\n i = source[i] === '\\\\' ? skipEscape(i) : i + 1\n }\n return i + 1\n}\n\n// marks the innermost open group (if any) as containing a quantifier\nconst markInnermostGroupQuantified = (groupsStack: boolean[]): void => {\n if (groupsStack.length > 0) {\n groupsStack[groupsStack.length - 1] = true\n }\n}\n\n/**\n * Closes the group ending at the specified index (position of the \")\").\n * Returns true if the group contains a quantifier and it's repeated by an unbounded quantifier.\n */\nconst closeGroup = (source: string, index: number, groupsStack: boolean[]): boolean => {\n const groupContainsQuantifier = groupsStack.pop() ?? false\n if (groupContainsQuantifier && unboundedQuantifierRegExp.test(source.substring(index + 1))) {\n return true\n }\n if (groupContainsQuantifier || isQuantifierAt(source, index + 1)) {\n markInnermostGroupQuantified(groupsStack)\n }\n return false\n}\n\n/**\n * Returns true if the specified regular expression source contains a group repeated by an unbounded quantifier\n * that contains a quantifier itself (star height > 1), e.g. (a+)+, (\\w*)* or (x{1,3})+:\n * these patterns can take exponential time on non-matching strings.\n * Overlapping alternations like (a|aa)+ are not detected.\n */\nexport const hasNestedQuantifiers = (source: string): boolean => {\n // for each open group: true if it contains a quantifier\n const groupsStack: boolean[] = []\n let i = 0\n while (i < source.length) {\n switch (source[i]) {\n case '\\\\':\n i = skipEscape(i)\n break\n case '[':\n i = skipCharacterClass(source, i)\n break\n case '(':\n groupsStack.push(false)\n // a \"?\" right after \"(\" introduces a group modifier (e.g. \"(?:\"), it's not a quantifier\n i += source[i + 1] === '?' ? 2 : 1\n break\n case ')':\n if (closeGroup(source, i, groupsStack)) return true\n i += 1\n break\n default:\n if (isQuantifierAt(source, i)) {\n markInnermostGroupQuantified(groupsStack)\n }\n i += 1\n }\n }\n return false\n}\n"]}
1
+ {"version":3,"file":"regExpSafety.js","sourceRoot":"","sources":["../../../../src/expression/javascript/regExpSafety.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,uFAAuF;AACvF,MAAM,CAAC,MAAM,wBAAwB,GAAG,IAAI,CAAA;AAE5C,kGAAkG;AAClG,MAAM,qBAAqB,GAAG,CAAC,CAAA;AAE/B,6FAA6F;AAC7F,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAA;AAE1D,8DAA8D;AAC9D,MAAM,YAAY,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAA;AAErG,MAAM,cAAc,GAAG,CAAC,MAAc,EAAE,KAAa,EAAW,EAAE;IAChE,MAAM,IAAI,GAAG,MAAM,CAAC,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AC,CAAC,CAAA;gBAC7C,MAAK;YACP,CAAC;YACD,KAAK,GAAG,EAAE,CAAC;gBACT,MAAA,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,0CAAE,sBAAsB,CAAC,IAAI,CAAC,uBAAuB,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;gBACvF,CAAC,IAAI,CAAC,CAAA;gBACN,MAAK;YACP,CAAC;YACD,KAAK,GAAG;gBACN,IAAI,UAAU,CAAC,MAAM,EAAE,CAAC,EAAE,WAAW,CAAC;oBAAE,OAAO,IAAI,CAAA;gBACnD,CAAC,IAAI,CAAC,CAAA;gBACN,MAAK;YACP,SAAS,CAAC;gBACR,MAAM,KAAK,GAAG,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;gBAChC,IAAI,KAAK,IAAI,cAAc,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,CAAC;oBACvC,KAAK,CAAC,UAAU,GAAG,IAAI,CAAA;gBACzB,CAAC;gBACD,CAAC,IAAI,CAAC,CAAA;YACR,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC,CAAA","sourcesContent":["/**\n * Protection against regular expressions that can take exponential time (ReDoS): JavaScript cannot interrupt a\n * running regular expression, so a single evaluation could freeze the server or the browser.\n */\n\n// maximum length of the strings that regular expressions are applied to in expressions\nexport const REG_EXP_INPUT_MAX_LENGTH = 1000\n\n// repetitions of a group with a higher maximum (e.g. {1,1000}) are as dangerous as unbounded ones\nconst GROUP_REPETITIONS_MAX = 3\n\n// characters that, right after an atom, quantify it (including \"?\", which makes it optional)\nconst quantifierStartChars = new Set(['*', '+', '?', '{'])\n\n// characters with a special meaning outside character classes\nconst specialChars = new Set(['\\\\', '[', ']', '(', ')', '|', '.', '^', '$', '*', '+', '?', '{', '}'])\n\nconst isQuantifierAt = (source: string, index: number): boolean => {\n const char = source[index]\n if (char === '*' || char === '+') return true\n // {n,m} or {n,} (exact {n} repetitions don't multiply the ways a string can be matched)\n return char === '{' && /^\\{\\d+,\\d*\\}/.test(source.substring(index))\n}\n\n/**\n * Returns true if the quantifier at the specified index repeats the preceding atom an unbounded number of times:\n * *, +, {n,} or {n,m} with m greater than GROUP_REPETITIONS_MAX.\n */\nconst isUnboundedQuantifierAt = (source: string, index: number): boolean => {\n const char = source[index]\n if (char === '*' || char === '+') return true\n const match = /^\\{\\d+(,(\\d*))?\\}/.exec(source.substring(index))\n if (!match) return false\n const [, comma, max] = match\n if (!comma) return false // exact {n}\n return !max || Number(max) > GROUP_REPETITIONS_MAX\n}\n\nconst skipEscape = (index: number): number => index + 2\n\nconst skipCharacterClass = (source: string, index: number): number => {\n let i = index + 1\n while (i < source.length && source[i] !== ']') {\n i = source[i] === '\\\\' ? skipEscape(i) : i + 1\n }\n return i + 1\n}\n\n// skips \"(\" and the group modifier, if any: (?:, (?=, (?!, (?<=, (?<! or (?<name>\nconst skipGroupStart = (source: string, index: number): number => {\n if (source[index + 1] !== '?') return index + 1\n if (source[index + 2] === '<' && source[index + 3] !== '=' && source[index + 3] !== '!') {\n const nameEnd = source.indexOf('>', index + 3)\n return nameEnd < 0 ? source.length : nameEnd + 1\n }\n return source[index + 2] === '<' ? index + 4 : index + 3\n}\n\n/**\n * Returns the literal character that the alternative starting at the specified index must start with,\n * or null if it can start with different characters (character class, \".\", group, optional atom etc.)\n * or it can be empty.\n */\nconst getAlternativeFirstChar = (source: string, index: number): string | null => {\n const char = source[index]\n let literal: string | null\n let atomLength: number\n if (char === undefined) {\n return null\n } else if (char === '\\\\') {\n // escaped letters and digits are character classes (\\d, \\w...), assertions (\\b) or back references\n const escapedChar = source[index + 1]\n literal = escapedChar !== undefined && !/[a-zA-Z0-9]/.test(escapedChar) ? escapedChar : null\n atomLength = 2\n } else {\n literal = specialChars.has(char) ? null : char\n atomLength = 1\n }\n if (literal === null || quantifierStartChars.has(source[index + atomLength])) return null\n // case insensitive comparison: the regular expression could use the \"i\" flag\n return literal.toLowerCase()\n}\n\ntype GroupState = {\n // the group contains a quantifier\n quantified: boolean\n // the group contains an alternation (or a group with an alternation) whose alternatives can match the same string\n ambiguous: boolean\n // first characters of the alternatives (null if not a single literal character)\n alternativesFirstChars: (string | null)[]\n}\n\nconst createGroupState = (source: string, contentStartIndex: number): GroupState => ({\n quantified: false,\n ambiguous: false,\n alternativesFirstChars: [getAlternativeFirstChar(source, contentStartIndex)],\n})\n\n/**\n * Alternatives are considered unambiguous only if they all start with different literal characters:\n * then at most one of them can match at any position.\n */\nconst hasAmbiguousAlternatives = (group: GroupState): boolean => {\n const { alternativesFirstChars } = group\n if (alternativesFirstChars.length < 2) return false\n if (alternativesFirstChars.includes(null)) return true\n return new Set(alternativesFirstChars).size < alternativesFirstChars.length\n}\n\n/**\n * Closes the group ending at the specified index (position of the \")\").\n * Returns true if the group contains a quantifier or ambiguous alternatives and it's repeated\n * by an unbounded quantifier.\n */\nconst closeGroup = (source: string, index: number, groupsStack: GroupState[]): boolean => {\n const group = groupsStack.pop()\n if (!group) return false\n const ambiguous = group.ambiguous || hasAmbiguousAlternatives(group)\n if ((group.quantified || ambiguous) && isUnboundedQuantifierAt(source, index + 1)) {\n return true\n }\n const parent = groupsStack.at(-1)\n if (parent) {\n parent.quantified = parent.quantified || group.quantified || isQuantifierAt(source, index + 1)\n // the parent group could be repeated\n parent.ambiguous = parent.ambiguous || ambiguous\n }\n return false\n}\n\n/**\n * Returns true if the specified regular expression source contains a group repeated by an unbounded quantifier\n * (*, +, {n,} or {n,m} with a high m) that contains:\n * - a quantifier itself (star height > 1), e.g. (a+)+, (\\w*)* or (x{1,3})+\n * - alternatives that can match the same string, e.g. (a|aa)+, (a|.)* or (\\d|-)+\n * (alternatives are considered safe only if they start with different literal characters, e.g. (ab|cd)+).\n * These patterns can take exponential time on non-matching strings.\n * Note: patterns taking polynomial time (e.g. a+a+a+$) are not detected; the time they take is limited by\n * the maximum length of the input strings (REG_EXP_INPUT_MAX_LENGTH).\n */\nexport const isUnsafeRegExpSource = (source: string): boolean => {\n const groupsStack: GroupState[] = []\n let i = 0\n while (i < source.length) {\n switch (source[i]) {\n case '\\\\':\n i = skipEscape(i)\n break\n case '[':\n i = skipCharacterClass(source, i)\n break\n case '(': {\n i = skipGroupStart(source, i)\n groupsStack.push(createGroupState(source, i))\n break\n }\n case '|': {\n groupsStack.at(-1)?.alternativesFirstChars.push(getAlternativeFirstChar(source, i + 1))\n i += 1\n break\n }\n case ')':\n if (closeGroup(source, i, groupsStack)) return true\n i += 1\n break\n default: {\n const group = groupsStack.at(-1)\n if (group && isQuantifierAt(source, i)) {\n group.quantified = true\n }\n i += 1\n }\n }\n }\n return false\n}\n"]}
@@ -25,7 +25,7 @@ const isRegExpStringPatternCall = (callee, args) => {
25
25
  typeof args[0] === 'string');
26
26
  };
27
27
  const checkRegExpStringPattern = (pattern) => {
28
- if ((0, regExpSafety_1.hasNestedQuantifiers)(pattern)) {
28
+ if ((0, regExpSafety_1.isUnsafeRegExpSource)(pattern)) {
29
29
  throw new error_1.SystemError(error_1.SystemErrorKeys.expression.unsafeRegularExpression, { pattern });
30
30
  }
31
31
  };
@@ -1 +1 @@
1
- {"version":3,"file":"call.js","sourceRoot":"","sources":["../../../../src/expression/javascript/node/call.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,0CAA6D;AAG7D,qCAOmB;AACnB,sCAAmD;AACnD,kDAAgF;AAEhF,gHAAgH;AAChH,MAAM,iCAAiC,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,UAAU,EAAE,QAAQ,CAAC,CAAC,CAAA;AAElF,6FAA6F;AAC7F,MAAM,yBAAyB,GAAG,CAAC,MAAwB,EAAE,IAAW,EAAW,EAAE;IACnF,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,GAAG,MAAM,CAAA;IACrC,OAAO,CACL,CAAC,QAAQ;QACT,QAAQ,CAAC,IAAI,KAAK,yBAAkB,CAAC,UAAU;QAC/C,iCAAiC,CAAC,GAAG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CAAC,SAAS,CAAC,YAAY,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC,CAAC,CAAA;YAEpG,uEAAuE;YACvE,wEAAwE;YACxE,sCAAsC;YACtC,OAAO,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAAA;QACxC,CAAC;KAAA;CACF","sourcesContent":["import { SystemError, SystemErrorKeys } from '../../../error'\nimport { ExpressionContext } from '../../context'\nimport { ExpressionFunction } from '../../function'\nimport {\n CallExpression,\n ExpressionNodeEvaluator,\n ExpressionNodeType,\n IdentifierExpression,\n LiteralExpression,\n MemberExpression,\n} from '../../node'\nimport { getGlobalObjectProperty } from '../global'\nimport { hasNestedQuantifiers, REG_EXP_INPUT_MAX_LENGTH } from '../regExpSafety'\n\n// String functions converting a string argument into a regular expression (replace, replaceAll and split don't)\nconst stringFunctionsWithRegExpArgument = new Set(['match', 'matchAll', 'search'])\n\n// e.g. text.match('(a+)+$'): the string pattern is checked like a regular expression literal\nconst isRegExpStringPatternCall = (callee: MemberExpression, args: any[]): boolean => {\n const { computed, property } = callee\n return (\n !computed &&\n property.type === ExpressionNodeType.Identifier &&\n stringFunctionsWithRegExpArgument.has((property as IdentifierExpression).name) &&\n typeof args[0] === 'string'\n )\n}\n\nconst checkRegExpStringPattern = (pattern: string): void => {\n if (hasNestedQuantifiers(pattern)) {\n throw new SystemError(SystemErrorKeys.expression.unsafeRegularExpression, { pattern })\n }\n}\n\n// e.g. /.../.test(text) or text.match(/.../): the time taken by a regular expression grows with the input length\nconst checkRegExpInputLength = (fnObject: any, args: any[], regExpStringPattern: boolean): void => {\n const values = [fnObject, ...args]\n if (!regExpStringPattern && !values.some((value) => value instanceof RegExp)) return\n const inputTooLong = values.find((value) => typeof value === 'string' && value.length > REG_EXP_INPUT_MAX_LENGTH)\n if (inputTooLong !== undefined) {\n throw new SystemError(SystemErrorKeys.expression.regularExpressionInputTooLong, {\n maxLength: REG_EXP_INPUT_MAX_LENGTH,\n length: inputTooLong.length,\n })\n }\n}\n\nexport class CallEvaluator<C extends ExpressionContext> extends ExpressionNodeEvaluator<C, CallExpression> {\n async evaluate(expressionNode: CallExpression): Promise<any> {\n const { callee } = expressionNode\n\n if (callee.type === ExpressionNodeType.Member) {\n return this.evaluateMember(expressionNode, callee)\n } else if (callee.type === ExpressionNodeType.Identifier) {\n return this.evaluateIdentifier(expressionNode, callee)\n }\n\n // No complex expressions may be put in place of a function body.\n // Only a plain identifier is allowed.\n throw new SystemError(SystemErrorKeys.expression.invalidCalleeType, { type: callee.type })\n }\n\n private async evaluateMember(expressionNode: CallExpression, callee: MemberExpression): Promise<any> {\n const { arguments: exprArgs } = expressionNode\n\n // evaluate the callee object only once: evaluating it again to find the function would take exponential time\n // with chained calls (e.g. text.trim().toUpperCase().toLowerCase())\n const fnObject = await this.evaluator.evaluateNode(callee.object, this.context)\n if (fnObject === null || fnObject === undefined) return null\n\n // find the function (e.g. Math.round or text.toUpperCase) among the properties of the already evaluated object\n const fnObjectLiteral: LiteralExpression = { type: ExpressionNodeType.Literal, value: fnObject, raw: '' }\n const calleeWithObjectEvaluated: MemberExpression = { ...callee, object: fnObjectLiteral }\n const fn = await this.evaluator.evaluateNode(calleeWithObjectEvaluated, this.context)\n if (fn) {\n const argsEvaluated = await Promise.all(exprArgs.map((arg) => this.evaluator.evaluateNode(arg, this.context)))\n const args = argsEvaluated.flat()\n const regExpStringPattern = isRegExpStringPatternCall(callee, args)\n if (regExpStringPattern) {\n checkRegExpStringPattern(args[0])\n }\n checkRegExpInputLength(fnObject, args, regExpStringPattern)\n return fn.call(fnObject, ...args)\n }\n return null\n }\n\n private async evaluateIdentifier(expressionNode: CallExpression, callee: IdentifierExpression): Promise<any> {\n // Arguments is a reserved word in strict mode\n const { arguments: exprArgs } = expressionNode\n const { object: contextObject } = this.context\n\n const { name: fnName } = callee\n\n const functionInfo = this.evaluator.functions[fnName]\n if (functionInfo) {\n // The function is among the custom functions.\n return this.evaluateCustomIdentifier(expressionNode, fnName)\n }\n // identifier is a global object\n const globalFn = getGlobalObjectProperty(fnName, contextObject)\n if (globalFn !== null) {\n // global functions like String, Number, must be invoked passing node value as argument, not the node itself\n const contextArg = { ...this.context, evaluateToNode: false }\n const args = await Promise.all(exprArgs.map((arg) => this.evaluator.evaluateNode(arg, contextArg)))\n return globalFn(...args)\n }\n\n throw new SystemError(SystemErrorKeys.expression.undefinedFunction, { name: fnName })\n }\n\n private async evaluateCustomIdentifier(expressionNode: CallExpression, fnName: string): Promise<any> {\n // Arguments is a reserved word in strict mode\n const { arguments: exprArgs } = expressionNode\n const numArgs = exprArgs.length\n\n const expressionFunction: ExpressionFunction<C> = this.evaluator.functions[fnName]\n\n const { minArity, maxArity, evaluateArgsToNodes, executor } = expressionFunction\n\n if (numArgs < minArity)\n throw new SystemError(SystemErrorKeys.expression.functionHasTooFewArguments, { fnName, minArity, numArgs })\n if (maxArity !== undefined && maxArity >= 0 && numArgs > maxArity)\n throw new SystemError(SystemErrorKeys.expression.functionHasTooManyArguments, { fnName, maxArity, numArgs })\n\n // evaluate arguments\n const argsContext = { ...this.context, evaluateToNode: evaluateArgsToNodes }\n const args = await Promise.all(exprArgs.map((arg) => this.evaluator.evaluateNode(arg, argsContext)))\n\n // Currently there are no side effects from function evaluation so it's\n // safe to call the function even when we're just parsing the expression\n // to find all identifiers being used.\n return executor(this.context)(...args)\n }\n}\n"]}
1
+ {"version":3,"file":"call.js","sourceRoot":"","sources":["../../../../src/expression/javascript/node/call.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,0CAA6D;AAG7D,qCAOmB;AACnB,sCAAmD;AACnD,kDAAgF;AAEhF,gHAAgH;AAChH,MAAM,iCAAiC,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,UAAU,EAAE,QAAQ,CAAC,CAAC,CAAA;AAElF,6FAA6F;AAC7F,MAAM,yBAAyB,GAAG,CAAC,MAAwB,EAAE,IAAW,EAAW,EAAE;IACnF,MAAM,EAAE,QAAQ,EA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AAE,mBAAmB,GAAE,CAAA;YAC5E,MAAM,IAAI,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,YAAY,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC,CAAC,CAAA;YAEpG,uEAAuE;YACvE,wEAAwE;YACxE,sCAAsC;YACtC,OAAO,QAAQ,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,CAAA;QACxC,CAAC;KAAA;CACF","sourcesContent":["import { SystemError, SystemErrorKeys } from '../../../error'\nimport { ExpressionContext } from '../../context'\nimport { ExpressionFunction } from '../../function'\nimport {\n CallExpression,\n ExpressionNodeEvaluator,\n ExpressionNodeType,\n IdentifierExpression,\n LiteralExpression,\n MemberExpression,\n} from '../../node'\nimport { getGlobalObjectProperty } from '../global'\nimport { isUnsafeRegExpSource, REG_EXP_INPUT_MAX_LENGTH } from '../regExpSafety'\n\n// String functions converting a string argument into a regular expression (replace, replaceAll and split don't)\nconst stringFunctionsWithRegExpArgument = new Set(['match', 'matchAll', 'search'])\n\n// e.g. text.match('(a+)+$'): the string pattern is checked like a regular expression literal\nconst isRegExpStringPatternCall = (callee: MemberExpression, args: any[]): boolean => {\n const { computed, property } = callee\n return (\n !computed &&\n property.type === ExpressionNodeType.Identifier &&\n stringFunctionsWithRegExpArgument.has((property as IdentifierExpression).name) &&\n typeof args[0] === 'string'\n )\n}\n\nconst checkRegExpStringPattern = (pattern: string): void => {\n if (isUnsafeRegExpSource(pattern)) {\n throw new SystemError(SystemErrorKeys.expression.unsafeRegularExpression, { pattern })\n }\n}\n\n// e.g. /.../.test(text) or text.match(/.../): the time taken by a regular expression grows with the input length\nconst checkRegExpInputLength = (fnObject: any, args: any[], regExpStringPattern: boolean): void => {\n const values = [fnObject, ...args]\n if (!regExpStringPattern && !values.some((value) => value instanceof RegExp)) return\n const inputTooLong = values.find((value) => typeof value === 'string' && value.length > REG_EXP_INPUT_MAX_LENGTH)\n if (inputTooLong !== undefined) {\n throw new SystemError(SystemErrorKeys.expression.regularExpressionInputTooLong, {\n maxLength: REG_EXP_INPUT_MAX_LENGTH,\n length: inputTooLong.length,\n })\n }\n}\n\nexport class CallEvaluator<C extends ExpressionContext> extends ExpressionNodeEvaluator<C, CallExpression> {\n async evaluate(expressionNode: CallExpression): Promise<any> {\n const { callee } = expressionNode\n\n if (callee.type === ExpressionNodeType.Member) {\n return this.evaluateMember(expressionNode, callee)\n } else if (callee.type === ExpressionNodeType.Identifier) {\n return this.evaluateIdentifier(expressionNode, callee)\n }\n\n // No complex expressions may be put in place of a function body.\n // Only a plain identifier is allowed.\n throw new SystemError(SystemErrorKeys.expression.invalidCalleeType, { type: callee.type })\n }\n\n private async evaluateMember(expressionNode: CallExpression, callee: MemberExpression): Promise<any> {\n const { arguments: exprArgs } = expressionNode\n\n // evaluate the callee object only once: evaluating it again to find the function would take exponential time\n // with chained calls (e.g. text.trim().toUpperCase().toLowerCase())\n const fnObject = await this.evaluator.evaluateNode(callee.object, this.context)\n if (fnObject === null || fnObject === undefined) return null\n\n // find the function (e.g. Math.round or text.toUpperCase) among the properties of the already evaluated object\n const fnObjectLiteral: LiteralExpression = { type: ExpressionNodeType.Literal, value: fnObject, raw: '' }\n const calleeWithObjectEvaluated: MemberExpression = { ...callee, object: fnObjectLiteral }\n const fn = await this.evaluator.evaluateNode(calleeWithObjectEvaluated, this.context)\n if (fn) {\n const argsEvaluated = await Promise.all(exprArgs.map((arg) => this.evaluator.evaluateNode(arg, this.context)))\n const args = argsEvaluated.flat()\n const regExpStringPattern = isRegExpStringPatternCall(callee, args)\n if (regExpStringPattern) {\n checkRegExpStringPattern(args[0])\n }\n checkRegExpInputLength(fnObject, args, regExpStringPattern)\n return fn.call(fnObject, ...args)\n }\n return null\n }\n\n private async evaluateIdentifier(expressionNode: CallExpression, callee: IdentifierExpression): Promise<any> {\n // Arguments is a reserved word in strict mode\n const { arguments: exprArgs } = expressionNode\n const { object: contextObject } = this.context\n\n const { name: fnName } = callee\n\n const functionInfo = this.evaluator.functions[fnName]\n if (functionInfo) {\n // The function is among the custom functions.\n return this.evaluateCustomIdentifier(expressionNode, fnName)\n }\n // identifier is a global object\n const globalFn = getGlobalObjectProperty(fnName, contextObject)\n if (globalFn !== null) {\n // global functions like String, Number, must be invoked passing node value as argument, not the node itself\n const contextArg = { ...this.context, evaluateToNode: false }\n const args = await Promise.all(exprArgs.map((arg) => this.evaluator.evaluateNode(arg, contextArg)))\n return globalFn(...args)\n }\n\n throw new SystemError(SystemErrorKeys.expression.undefinedFunction, { name: fnName })\n }\n\n private async evaluateCustomIdentifier(expressionNode: CallExpression, fnName: string): Promise<any> {\n // Arguments is a reserved word in strict mode\n const { arguments: exprArgs } = expressionNode\n const numArgs = exprArgs.length\n\n const expressionFunction: ExpressionFunction<C> = this.evaluator.functions[fnName]\n\n const { minArity, maxArity, evaluateArgsToNodes, executor } = expressionFunction\n\n if (numArgs < minArity)\n throw new SystemError(SystemErrorKeys.expression.functionHasTooFewArguments, { fnName, minArity, numArgs })\n if (maxArity !== undefined && maxArity >= 0 && numArgs > maxArity)\n throw new SystemError(SystemErrorKeys.expression.functionHasTooManyArguments, { fnName, maxArity, numArgs })\n\n // evaluate arguments\n const argsContext = { ...this.context, evaluateToNode: evaluateArgsToNodes }\n const args = await Promise.all(exprArgs.map((arg) => this.evaluator.evaluateNode(arg, argsContext)))\n\n // Currently there are no side effects from function evaluation so it's\n // safe to call the function even when we're just parsing the expression\n // to find all identifiers being used.\n return executor(this.context)(...args)\n }\n}\n"]}
@@ -7,7 +7,7 @@ const regExpSafety_1 = require("../regExpSafety");
7
7
  class LiteralEvaluator extends node_1.ExpressionNodeEvaluator {
8
8
  evaluate(expressionNode) {
9
9
  const { value } = expressionNode;
10
- if (value instanceof RegExp && (0, regExpSafety_1.hasNestedQuantifiers)(value.source)) {
10
+ if (value instanceof RegExp && (0, regExpSafety_1.isUnsafeRegExpSource)(value.source)) {
11
11
  return Promise.reject(new error_1.SystemError(error_1.SystemErrorKeys.expression.unsafeRegularExpression, { pattern: value.source }));
12
12
  }
13
13
  return Promise.resolve(value);
@@ -1 +1 @@
1
- {"version":3,"file":"literal.js","sourceRoot":"","sources":["../../../../src/expression/javascript/node/literal.ts"],"names":[],"mappings":";;;AAAA,0CAA6D;AAE7D,qCAAuE;AACvE,kDAAsD;AAEtD,sBAA2D,SAAQ,8BAA6C;IAC9G,QAAQ,CAAC,cAAiC;QACxC,MAAM,EAAE,KAAK,EAAE,GAAG,cAAc,CAAA;QAChC,IAAI,KAAK,YAAY,MAAM,IAAI,IAAA,mCAAoB,EAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC;YAClE,OAAO,OAAO,CAAC,MAAM,CACnB,IAAI,mBAAW,CAAC,uBAAe,CAAC,UAAU,CAAC,uBAAuB,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAC/F,CAAA;QACH,CAAC;QACD,OAAO,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAA;IAC/B,CAAC;CACF","sourcesContent":["import { SystemError, SystemErrorKeys } from '../../../error'\nimport { ExpressionContext } from '../../context'\nimport { ExpressionNodeEvaluator, LiteralExpression } from '../../node'\nimport { hasNestedQuantifiers } from '../regExpSafety'\n\nexport class LiteralEvaluator<C extends ExpressionContext> extends ExpressionNodeEvaluator<C, LiteralExpression> {\n evaluate(expressionNode: LiteralExpression): Promise<any> {\n const { value } = expressionNode\n if (value instanceof RegExp && hasNestedQuantifiers(value.source)) {\n return Promise.reject(\n new SystemError(SystemErrorKeys.expression.unsafeRegularExpression, { pattern: value.source })\n )\n }\n return Promise.resolve(value)\n }\n}\n"]}
1
+ {"version":3,"file":"literal.js","sourceRoot":"","sources":["../../../../src/expression/javascript/node/literal.ts"],"names":[],"mappings":";;;AAAA,0CAA6D;AAE7D,qCAAuE;AACvE,kDAAsD;AAEtD,sBAA2D,SAAQ,8BAA6C;IAC9G,QAAQ,CAAC,cAAiC;QACxC,MAAM,EAAE,KAAK,EAAE,GAAG,cAAc,CAAA;QAChC,IAAI,KAAK,YAAY,MAAM,IAAI,IAAA,mCAAoB,EAAC,KAAK,CAAC,MAAM,CAAC,EAAE,CAAC;YAClE,OAAO,OAAO,CAAC,MAAM,CACnB,IAAI,mBAAW,CAAC,uBAAe,CAAC,UAAU,CAAC,uBAAuB,EAAE,EAAE,OAAO,EAAE,KAAK,CAAC,MAAM,EAAE,CAAC,CAC/F,CAAA;QACH,CAAC;QACD,OAAO,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAA;IAC/B,CAAC;CACF","sourcesContent":["import { SystemError, SystemErrorKeys } from '../../../error'\nimport { ExpressionContext } from '../../context'\nimport { ExpressionNodeEvaluator, LiteralExpression } from '../../node'\nimport { isUnsafeRegExpSource } from '../regExpSafety'\n\nexport class LiteralEvaluator<C extends ExpressionContext> extends ExpressionNodeEvaluator<C, LiteralExpression> {\n evaluate(expressionNode: LiteralExpression): Promise<any> {\n const { value } = expressionNode\n if (value instanceof RegExp && isUnsafeRegExpSource(value.source)) {\n return Promise.reject(\n new SystemError(SystemErrorKeys.expression.unsafeRegularExpression, { pattern: value.source })\n )\n }\n return Promise.resolve(value)\n }\n}\n"]}
@@ -5,8 +5,12 @@
5
5
  export declare const REG_EXP_INPUT_MAX_LENGTH = 1000;
6
6
  /**
7
7
  * Returns true if the specified regular expression source contains a group repeated by an unbounded quantifier
8
- * that contains a quantifier itself (star height > 1), e.g. (a+)+, (\w*)* or (x{1,3})+:
9
- * these patterns can take exponential time on non-matching strings.
10
- * Overlapping alternations like (a|aa)+ are not detected.
8
+ * (*, +, {n,} or {n,m} with a high m) that contains:
9
+ * - a quantifier itself (star height > 1), e.g. (a+)+, (\w*)* or (x{1,3})+
10
+ * - alternatives that can match the same string, e.g. (a|aa)+, (a|.)* or (\d|-)+
11
+ * (alternatives are considered safe only if they start with different literal characters, e.g. (ab|cd)+).
12
+ * These patterns can take exponential time on non-matching strings.
13
+ * Note: patterns taking polynomial time (e.g. a+a+a+$) are not detected; the time they take is limited by
14
+ * the maximum length of the input strings (REG_EXP_INPUT_MAX_LENGTH).
11
15
  */
12
- export declare const hasNestedQuantifiers: (source: string) => boolean;
16
+ export declare const isUnsafeRegExpSource: (source: string) => boolean;
@@ -4,11 +4,15 @@
4
4
  * running regular expression, so a single evaluation could freeze the server or the browser.
5
5
  */
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.hasNestedQuantifiers = exports.REG_EXP_INPUT_MAX_LENGTH = void 0;
7
+ exports.isUnsafeRegExpSource = exports.REG_EXP_INPUT_MAX_LENGTH = void 0;
8
8
  // maximum length of the strings that regular expressions are applied to in expressions
9
9
  exports.REG_EXP_INPUT_MAX_LENGTH = 1000;
10
- // unbounded quantifier at the given position: *, + or {n,} (quantifiers like {n} or {n,m} are bounded)
11
- const unboundedQuantifierRegExp = /^(\*|\+|\{\d+,\})/;
10
+ // repetitions of a group with a higher maximum (e.g. {1,1000}) are as dangerous as unbounded ones
11
+ const GROUP_REPETITIONS_MAX = 3;
12
+ // characters that, right after an atom, quantify it (including "?", which makes it optional)
13
+ const quantifierStartChars = new Set(['*', '+', '?', '{']);
14
+ // characters with a special meaning outside character classes
15
+ const specialChars = new Set(['\\', '[', ']', '(', ')', '|', '.', '^', '$', '*', '+', '?', '{', '}']);
12
16
  const isQuantifierAt = (source, index) => {
13
17
  const char = source[index];
14
18
  if (char === '*' || char === '+')
@@ -16,6 +20,22 @@ const isQuantifierAt = (source, index) => {
16
20
  // {n,m} or {n,} (exact {n} repetitions don't multiply the ways a string can be matched)
17
21
  return char === '{' && /^\{\d+,\d*\}/.test(source.substring(index));
18
22
  };
23
+ /**
24
+ * Returns true if the quantifier at the specified index repeats the preceding atom an unbounded number of times:
25
+ * *, +, {n,} or {n,m} with m greater than GROUP_REPETITIONS_MAX.
26
+ */
27
+ const isUnboundedQuantifierAt = (source, index) => {
28
+ const char = source[index];
29
+ if (char === '*' || char === '+')
30
+ return true;
31
+ const match = /^\{\d+(,(\d*))?\}/.exec(source.substring(index));
32
+ if (!match)
33
+ return false;
34
+ const [, comma, max] = match;
35
+ if (!comma)
36
+ return false; // exact {n}
37
+ return !max || Number(max) > GROUP_REPETITIONS_MAX;
38
+ };
19
39
  const skipEscape = (index) => index + 2;
20
40
  const skipCharacterClass = (source, index) => {
21
41
  let i = index + 1;
@@ -24,35 +44,93 @@ const skipCharacterClass = (source, index) => {
24
44
  }
25
45
  return i + 1;
26
46
  };
27
- // marks the innermost open group (if any) as containing a quantifier
28
- const markInnermostGroupQuantified = (groupsStack) => {
29
- if (groupsStack.length > 0) {
30
- groupsStack[groupsStack.length - 1] = true;
47
+ // skips "(" and the group modifier, if any: (?:, (?=, (?!, (?<=, (?<! or (?<name>
48
+ const skipGroupStart = (source, index) => {
49
+ if (source[index + 1] !== '?')
50
+ return index + 1;
51
+ if (source[index + 2] === '<' && source[index + 3] !== '=' && source[index + 3] !== '!') {
52
+ const nameEnd = source.indexOf('>', index + 3);
53
+ return nameEnd < 0 ? source.length : nameEnd + 1;
31
54
  }
55
+ return source[index + 2] === '<' ? index + 4 : index + 3;
56
+ };
57
+ /**
58
+ * Returns the literal character that the alternative starting at the specified index must start with,
59
+ * or null if it can start with different characters (character class, ".", group, optional atom etc.)
60
+ * or it can be empty.
61
+ */
62
+ const getAlternativeFirstChar = (source, index) => {
63
+ const char = source[index];
64
+ let literal;
65
+ let atomLength;
66
+ if (char === undefined) {
67
+ return null;
68
+ }
69
+ else if (char === '\\') {
70
+ // escaped letters and digits are character classes (\d, \w...), assertions (\b) or back references
71
+ const escapedChar = source[index + 1];
72
+ literal = escapedChar !== undefined && !/[a-zA-Z0-9]/.test(escapedChar) ? escapedChar : null;
73
+ atomLength = 2;
74
+ }
75
+ else {
76
+ literal = specialChars.has(char) ? null : char;
77
+ atomLength = 1;
78
+ }
79
+ if (literal === null || quantifierStartChars.has(source[index + atomLength]))
80
+ return null;
81
+ // case insensitive comparison: the regular expression could use the "i" flag
82
+ return literal.toLowerCase();
83
+ };
84
+ const createGroupState = (source, contentStartIndex) => ({
85
+ quantified: false,
86
+ ambiguous: false,
87
+ alternativesFirstChars: [getAlternativeFirstChar(source, contentStartIndex)],
88
+ });
89
+ /**
90
+ * Alternatives are considered unambiguous only if they all start with different literal characters:
91
+ * then at most one of them can match at any position.
92
+ */
93
+ const hasAmbiguousAlternatives = (group) => {
94
+ const { alternativesFirstChars } = group;
95
+ if (alternativesFirstChars.length < 2)
96
+ return false;
97
+ if (alternativesFirstChars.includes(null))
98
+ return true;
99
+ return new Set(alternativesFirstChars).size < alternativesFirstChars.length;
32
100
  };
33
101
  /**
34
102
  * Closes the group ending at the specified index (position of the ")").
35
- * Returns true if the group contains a quantifier and it's repeated by an unbounded quantifier.
103
+ * Returns true if the group contains a quantifier or ambiguous alternatives and it's repeated
104
+ * by an unbounded quantifier.
36
105
  */
37
106
  const closeGroup = (source, index, groupsStack) => {
38
- var _a;
39
- const groupContainsQuantifier = (_a = groupsStack.pop()) !== null && _a !== void 0 ? _a : false;
40
- if (groupContainsQuantifier && unboundedQuantifierRegExp.test(source.substring(index + 1))) {
107
+ const group = groupsStack.pop();
108
+ if (!group)
109
+ return false;
110
+ const ambiguous = group.ambiguous || hasAmbiguousAlternatives(group);
111
+ if ((group.quantified || ambiguous) && isUnboundedQuantifierAt(source, index + 1)) {
41
112
  return true;
42
113
  }
43
- if (groupContainsQuantifier || isQuantifierAt(source, index + 1)) {
44
- markInnermostGroupQuantified(groupsStack);
114
+ const parent = groupsStack.at(-1);
115
+ if (parent) {
116
+ parent.quantified = parent.quantified || group.quantified || isQuantifierAt(source, index + 1);
117
+ // the parent group could be repeated
118
+ parent.ambiguous = parent.ambiguous || ambiguous;
45
119
  }
46
120
  return false;
47
121
  };
48
122
  /**
49
123
  * Returns true if the specified regular expression source contains a group repeated by an unbounded quantifier
50
- * that contains a quantifier itself (star height > 1), e.g. (a+)+, (\w*)* or (x{1,3})+:
51
- * these patterns can take exponential time on non-matching strings.
52
- * Overlapping alternations like (a|aa)+ are not detected.
124
+ * (*, +, {n,} or {n,m} with a high m) that contains:
125
+ * - a quantifier itself (star height > 1), e.g. (a+)+, (\w*)* or (x{1,3})+
126
+ * - alternatives that can match the same string, e.g. (a|aa)+, (a|.)* or (\d|-)+
127
+ * (alternatives are considered safe only if they start with different literal characters, e.g. (ab|cd)+).
128
+ * These patterns can take exponential time on non-matching strings.
129
+ * Note: patterns taking polynomial time (e.g. a+a+a+$) are not detected; the time they take is limited by
130
+ * the maximum length of the input strings (REG_EXP_INPUT_MAX_LENGTH).
53
131
  */
54
- const hasNestedQuantifiers = (source) => {
55
- // for each open group: true if it contains a quantifier
132
+ const isUnsafeRegExpSource = (source) => {
133
+ var _a;
56
134
  const groupsStack = [];
57
135
  let i = 0;
58
136
  while (i < source.length) {
@@ -63,24 +141,31 @@ const hasNestedQuantifiers = (source) => {
63
141
  case '[':
64
142
  i = skipCharacterClass(source, i);
65
143
  break;
66
- case '(':
67
- groupsStack.push(false);
68
- // a "?" right after "(" introduces a group modifier (e.g. "(?:"), it's not a quantifier
69
- i += source[i + 1] === '?' ? 2 : 1;
144
+ case '(': {
145
+ i = skipGroupStart(source, i);
146
+ groupsStack.push(createGroupState(source, i));
147
+ break;
148
+ }
149
+ case '|': {
150
+ (_a = groupsStack.at(-1)) === null || _a === void 0 ? void 0 : _a.alternativesFirstChars.push(getAlternativeFirstChar(source, i + 1));
151
+ i += 1;
70
152
  break;
153
+ }
71
154
  case ')':
72
155
  if (closeGroup(source, i, groupsStack))
73
156
  return true;
74
157
  i += 1;
75
158
  break;
76
- default:
77
- if (isQuantifierAt(source, i)) {
78
- markInnermostGroupQuantified(groupsStack);
159
+ default: {
160
+ const group = groupsStack.at(-1);
161
+ if (group && isQuantifierAt(source, i)) {
162
+ group.quantified = true;
79
163
  }
80
164
  i += 1;
165
+ }
81
166
  }
82
167
  }
83
168
  return false;
84
169
  };
85
- exports.hasNestedQuantifiers = hasNestedQuantifiers;
170
+ exports.isUnsafeRegExpSource = isUnsafeRegExpSource;
86
171
  //# sourceMappingURL=regExpSafety.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"regExpSafety.js","sourceRoot":"","sources":["../../../src/expression/javascript/regExpSafety.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,uFAAuF;AAC1E,QAAA,wBAAwB,GAAG,IAAI,CAAA;AAE5C,uGAAuG;AACvG,MAAM,yBAAyB,GAAG,mBAAmB,CAAA;AAErD,MAAM,cAAc,GAAG,CAAC,MAAc,EAAE,KAAa,EAAW,EAAE;IAChE,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,CAAA;IAC1B,IAAI,IAAI,KAAK,GAAG,IAAI,IAAI,KAAK,GAAG;QAAE,OAAO,IAAI,CAAA;IAC7C,wFAAwF;IACxF,OAAO,IAAI,KAAK,GAAG,IAAI,cAAc,CAAC,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAA;AACrE,CAAC,CAAA;AAED,MAAM,UAAU,GAAG,CAAC,KAAa,EAAU,EAAE,CAAC,KAAK,GAAG,CAAC,CAAA;AAEvD,MAAM,kBAAkB,GAAG,CAAC,MAAc,EAAE,KAAa,EAAU,EAAE;IACnE,IAAI,CAAC,GAAG,KAAK,GAAG,CAAC,CAAA;IACjB,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,IAAI,MAAM,CAAC,CAAC,CAAC,KAAK,GAAG,EAAE,CAAC;QAC9C,CAAC,GAAG,MAAM,CAAC,CAAC,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAA;IAChD,CAAC;IACD,OAAO,CAAC,GAAG,CAAC,CAAA;AACd,CAAC,CAAA;AAED,qEAAqE;AACrE,MAAM,4BAA4B,GAAG,CAAC,WAAsB,EAAQ,EAAE;IACpE,IAAI,WAAW,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C,CAAC,CAAC,CAAC,CAAA;gBAClC,MAAK;YACP,KAAK,GAAG;gBACN,IAAI,UAAU,CAAC,MAAM,EAAE,CAAC,EAAE,WAAW,CAAC;oBAAE,OAAO,IAAI,CAAA;gBACnD,CAAC,IAAI,CAAC,CAAA;gBACN,MAAK;YACP;gBACE,IAAI,cAAc,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,CAAC;oBAC9B,4BAA4B,CAAC,WAAW,CAAC,CAAA;gBAC3C,CAAC;gBACD,CAAC,IAAI,CAAC,CAAA;QACV,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC,CAAA;AA7BY,QAAA,oBAAoB,GAApB,oBAAoB,CA6BhC","sourcesContent":["/**\n * Protection against regular expressions that can take exponential time (ReDoS): JavaScript cannot interrupt a\n * running regular expression, so a single evaluation could freeze the server or the browser.\n */\n\n// maximum length of the strings that regular expressions are applied to in expressions\nexport const REG_EXP_INPUT_MAX_LENGTH = 1000\n\n// unbounded quantifier at the given position: *, + or {n,} (quantifiers like {n} or {n,m} are bounded)\nconst unboundedQuantifierRegExp = /^(\\*|\\+|\\{\\d+,\\})/\n\nconst isQuantifierAt = (source: string, index: number): boolean => {\n const char = source[index]\n if (char === '*' || char === '+') return true\n // {n,m} or {n,} (exact {n} repetitions don't multiply the ways a string can be matched)\n return char === '{' && /^\\{\\d+,\\d*\\}/.test(source.substring(index))\n}\n\nconst skipEscape = (index: number): number => index + 2\n\nconst skipCharacterClass = (source: string, index: number): number => {\n let i = index + 1\n while (i < source.length && source[i] !== ']') {\n i = source[i] === '\\\\' ? skipEscape(i) : i + 1\n }\n return i + 1\n}\n\n// marks the innermost open group (if any) as containing a quantifier\nconst markInnermostGroupQuantified = (groupsStack: boolean[]): void => {\n if (groupsStack.length > 0) {\n groupsStack[groupsStack.length - 1] = true\n }\n}\n\n/**\n * Closes the group ending at the specified index (position of the \")\").\n * Returns true if the group contains a quantifier and it's repeated by an unbounded quantifier.\n */\nconst closeGroup = (source: string, index: number, groupsStack: boolean[]): boolean => {\n const groupContainsQuantifier = groupsStack.pop() ?? false\n if (groupContainsQuantifier && unboundedQuantifierRegExp.test(source.substring(index + 1))) {\n return true\n }\n if (groupContainsQuantifier || isQuantifierAt(source, index + 1)) {\n markInnermostGroupQuantified(groupsStack)\n }\n return false\n}\n\n/**\n * Returns true if the specified regular expression source contains a group repeated by an unbounded quantifier\n * that contains a quantifier itself (star height > 1), e.g. (a+)+, (\\w*)* or (x{1,3})+:\n * these patterns can take exponential time on non-matching strings.\n * Overlapping alternations like (a|aa)+ are not detected.\n */\nexport const hasNestedQuantifiers = (source: string): boolean => {\n // for each open group: true if it contains a quantifier\n const groupsStack: boolean[] = []\n let i = 0\n while (i < source.length) {\n switch (source[i]) {\n case '\\\\':\n i = skipEscape(i)\n break\n case '[':\n i = skipCharacterClass(source, i)\n break\n case '(':\n groupsStack.push(false)\n // a \"?\" right after \"(\" introduces a group modifier (e.g. \"(?:\"), it's not a quantifier\n i += source[i + 1] === '?' ? 2 : 1\n break\n case ')':\n if (closeGroup(source, i, groupsStack)) return true\n i += 1\n break\n default:\n if (isQuantifierAt(source, i)) {\n markInnermostGroupQuantified(groupsStack)\n }\n i += 1\n }\n }\n return false\n}\n"]}
1
+ {"version":3,"file":"regExpSafety.js","sourceRoot":"","sources":["../../../src/expression/javascript/regExpSafety.ts"],"names":[],"mappings":";AAAA;;;GAGG;;;AAEH,uFAAuF;AAC1E,QAAA,wBAAwB,GAAG,IAAI,CAAA;AAE5C,kGAAkG;AAClG,MAAM,qBAAqB,GAAG,CAAC,CAAA;AAE/B,6FAA6F;AAC7F,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAA;AAE1D,8DAA8D;AAC9D,MAAM,YAAY,GAAG,IAAI,GAAG,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,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AAC,MAAM,EAAE,CAAC,CAAC,CAAA;gBACjC,MAAK;YACP,KAAK,GAAG,EAAE,CAAC;gBACT,CAAC,GAAG,cAAc,CAAC,MAAM,EAAE,CAAC,CAAC,CAAA;gBAC7B,WAAW,CAAC,IAAI,CAAC,gBAAgB,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,CAAA;gBAC7C,MAAK;YACP,CAAC;YACD,KAAK,GAAG,EAAE,CAAC;gBACT,MAAA,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,0CAAE,sBAAsB,CAAC,IAAI,CAAC,uBAAuB,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;gBACvF,CAAC,IAAI,CAAC,CAAA;gBACN,MAAK;YACP,CAAC;YACD,KAAK,GAAG;gBACN,IAAI,UAAU,CAAC,MAAM,EAAE,CAAC,EAAE,WAAW,CAAC;oBAAE,OAAO,IAAI,CAAA;gBACnD,CAAC,IAAI,CAAC,CAAA;gBACN,MAAK;YACP,SAAS,CAAC;gBACR,MAAM,KAAK,GAAG,WAAW,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAA;gBAChC,IAAI,KAAK,IAAI,cAAc,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,CAAC;oBACvC,KAAK,CAAC,UAAU,GAAG,IAAI,CAAA;gBACzB,CAAC;gBACD,CAAC,IAAI,CAAC,CAAA;YACR,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAA;AACd,CAAC,CAAA;AAnCY,QAAA,oBAAoB,GAApB,oBAAoB,CAmChC","sourcesContent":["/**\n * Protection against regular expressions that can take exponential time (ReDoS): JavaScript cannot interrupt a\n * running regular expression, so a single evaluation could freeze the server or the browser.\n */\n\n// maximum length of the strings that regular expressions are applied to in expressions\nexport const REG_EXP_INPUT_MAX_LENGTH = 1000\n\n// repetitions of a group with a higher maximum (e.g. {1,1000}) are as dangerous as unbounded ones\nconst GROUP_REPETITIONS_MAX = 3\n\n// characters that, right after an atom, quantify it (including \"?\", which makes it optional)\nconst quantifierStartChars = new Set(['*', '+', '?', '{'])\n\n// characters with a special meaning outside character classes\nconst specialChars = new Set(['\\\\', '[', ']', '(', ')', '|', '.', '^', '$', '*', '+', '?', '{', '}'])\n\nconst isQuantifierAt = (source: string, index: number): boolean => {\n const char = source[index]\n if (char === '*' || char === '+') return true\n // {n,m} or {n,} (exact {n} repetitions don't multiply the ways a string can be matched)\n return char === '{' && /^\\{\\d+,\\d*\\}/.test(source.substring(index))\n}\n\n/**\n * Returns true if the quantifier at the specified index repeats the preceding atom an unbounded number of times:\n * *, +, {n,} or {n,m} with m greater than GROUP_REPETITIONS_MAX.\n */\nconst isUnboundedQuantifierAt = (source: string, index: number): boolean => {\n const char = source[index]\n if (char === '*' || char === '+') return true\n const match = /^\\{\\d+(,(\\d*))?\\}/.exec(source.substring(index))\n if (!match) return false\n const [, comma, max] = match\n if (!comma) return false // exact {n}\n return !max || Number(max) > GROUP_REPETITIONS_MAX\n}\n\nconst skipEscape = (index: number): number => index + 2\n\nconst skipCharacterClass = (source: string, index: number): number => {\n let i = index + 1\n while (i < source.length && source[i] !== ']') {\n i = source[i] === '\\\\' ? skipEscape(i) : i + 1\n }\n return i + 1\n}\n\n// skips \"(\" and the group modifier, if any: (?:, (?=, (?!, (?<=, (?<! or (?<name>\nconst skipGroupStart = (source: string, index: number): number => {\n if (source[index + 1] !== '?') return index + 1\n if (source[index + 2] === '<' && source[index + 3] !== '=' && source[index + 3] !== '!') {\n const nameEnd = source.indexOf('>', index + 3)\n return nameEnd < 0 ? source.length : nameEnd + 1\n }\n return source[index + 2] === '<' ? index + 4 : index + 3\n}\n\n/**\n * Returns the literal character that the alternative starting at the specified index must start with,\n * or null if it can start with different characters (character class, \".\", group, optional atom etc.)\n * or it can be empty.\n */\nconst getAlternativeFirstChar = (source: string, index: number): string | null => {\n const char = source[index]\n let literal: string | null\n let atomLength: number\n if (char === undefined) {\n return null\n } else if (char === '\\\\') {\n // escaped letters and digits are character classes (\\d, \\w...), assertions (\\b) or back references\n const escapedChar = source[index + 1]\n literal = escapedChar !== undefined && !/[a-zA-Z0-9]/.test(escapedChar) ? escapedChar : null\n atomLength = 2\n } else {\n literal = specialChars.has(char) ? null : char\n atomLength = 1\n }\n if (literal === null || quantifierStartChars.has(source[index + atomLength])) return null\n // case insensitive comparison: the regular expression could use the \"i\" flag\n return literal.toLowerCase()\n}\n\ntype GroupState = {\n // the group contains a quantifier\n quantified: boolean\n // the group contains an alternation (or a group with an alternation) whose alternatives can match the same string\n ambiguous: boolean\n // first characters of the alternatives (null if not a single literal character)\n alternativesFirstChars: (string | null)[]\n}\n\nconst createGroupState = (source: string, contentStartIndex: number): GroupState => ({\n quantified: false,\n ambiguous: false,\n alternativesFirstChars: [getAlternativeFirstChar(source, contentStartIndex)],\n})\n\n/**\n * Alternatives are considered unambiguous only if they all start with different literal characters:\n * then at most one of them can match at any position.\n */\nconst hasAmbiguousAlternatives = (group: GroupState): boolean => {\n const { alternativesFirstChars } = group\n if (alternativesFirstChars.length < 2) return false\n if (alternativesFirstChars.includes(null)) return true\n return new Set(alternativesFirstChars).size < alternativesFirstChars.length\n}\n\n/**\n * Closes the group ending at the specified index (position of the \")\").\n * Returns true if the group contains a quantifier or ambiguous alternatives and it's repeated\n * by an unbounded quantifier.\n */\nconst closeGroup = (source: string, index: number, groupsStack: GroupState[]): boolean => {\n const group = groupsStack.pop()\n if (!group) return false\n const ambiguous = group.ambiguous || hasAmbiguousAlternatives(group)\n if ((group.quantified || ambiguous) && isUnboundedQuantifierAt(source, index + 1)) {\n return true\n }\n const parent = groupsStack.at(-1)\n if (parent) {\n parent.quantified = parent.quantified || group.quantified || isQuantifierAt(source, index + 1)\n // the parent group could be repeated\n parent.ambiguous = parent.ambiguous || ambiguous\n }\n return false\n}\n\n/**\n * Returns true if the specified regular expression source contains a group repeated by an unbounded quantifier\n * (*, +, {n,} or {n,m} with a high m) that contains:\n * - a quantifier itself (star height > 1), e.g. (a+)+, (\\w*)* or (x{1,3})+\n * - alternatives that can match the same string, e.g. (a|aa)+, (a|.)* or (\\d|-)+\n * (alternatives are considered safe only if they start with different literal characters, e.g. (ab|cd)+).\n * These patterns can take exponential time on non-matching strings.\n * Note: patterns taking polynomial time (e.g. a+a+a+$) are not detected; the time they take is limited by\n * the maximum length of the input strings (REG_EXP_INPUT_MAX_LENGTH).\n */\nexport const isUnsafeRegExpSource = (source: string): boolean => {\n const groupsStack: GroupState[] = []\n let i = 0\n while (i < source.length) {\n switch (source[i]) {\n case '\\\\':\n i = skipEscape(i)\n break\n case '[':\n i = skipCharacterClass(source, i)\n break\n case '(': {\n i = skipGroupStart(source, i)\n groupsStack.push(createGroupState(source, i))\n break\n }\n case '|': {\n groupsStack.at(-1)?.alternativesFirstChars.push(getAlternativeFirstChar(source, i + 1))\n i += 1\n break\n }\n case ')':\n if (closeGroup(source, i, groupsStack)) return true\n i += 1\n break\n default: {\n const group = groupsStack.at(-1)\n if (group && isQuantifierAt(source, i)) {\n group.quantified = true\n }\n i += 1\n }\n }\n }\n return false\n}\n"]}
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "name": "OpenForis",
5
5
  "email": "openforis.arena@gmail.com"
6
6
  },
7
- "version": "2.21.1",
7
+ "version": "2.21.3",
8
8
  "description": "Arena core module",
9
9
  "repository": {
10
10
  "type": "git",