/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';

const { CustomSearcher } = require('../../signature');
const common = require('../../../common');
const Builder = require('../../../attack-patterns');

const { SCORES } = common;

const TERMS = {
  COMMON_FUNCTIONS: [
    'alert',
    'confirm',
    'prompt',
    'eval',
    'substring',
    'setTimeout',
    'setInterval'
  ],
  FUNCTION: 'Function',
  CONCAT_OPERATOR: '+'
};

const fnSearch = Builder()
  .JS()
  .literally(TERMS.FUNCTION)
  .blockOrInlineComments()
  .functionCall()
  .blockOrInlineComments()
  .anyOf(
    [
      '\\([\\s\\S]*\\)', // paren. invokation
      '`[\\s\\S]*`' // template literal invocation
    ],
    true
  )
  .build();
//   =>
//   Function(?:\s*)(?:\/\*[\\s\\S]*\*\/)?(?:\s*)(\([\\s\\S]*\))(?:\s*)(?:\/\*[\\s\\S]*\*\/)?(?:\s*)(`[\\s\\S]*`|\([\\s\\S]*\))

const concatSearch = Builder()
  .JS()
  .concatenation()
  .build();

/**
 * Search for a function being called. Functions can be called with:
 *   Function(something)()
 *   Function/*.../(something)()
 *   Function (something)()
 *   Function (something)` `
 * @returns {CustomSearcher}
 */
class ImmediateFunctionSearcher extends CustomSearcher {
  constructor() {
    super({
      description: 'Searches for a function being called.',
      id: 'CS-EXP-3',
      name: 'Immediate function searcher'
    });
  }

  getImpact(userInput) {
    let { value } = userInput;

    const functionIndex = value.indexOf(TERMS.FUNCTION);

    // Quick bail if we don't find "Function" text
    if (functionIndex < 0) {
      return SCORES.NONE;
    }

    // Otherwise we'll do some more heavy lifting
    const patternIndex = value.search(fnSearch, functionIndex);

    if (patternIndex < 0) {
      return SCORES.NONE;
    }

    if (value.indexOf(TERMS.CONCAT_OPERATOR, patternIndex + 8)) {
      value = value.replace(concatSearch, '');
    }

    const foundFnName = TERMS.COMMON_FUNCTIONS.some(function(fnName) {
      return 0 <= value.indexOf(fnName);
    });

    return !foundFnName ? SCORES.MEDIUM : SCORES.HIGH;
  }
}

module.exports = new ImmediateFunctionSearcher();
