/**
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 COMMON_FUNCTIONS = [
  'alert',
  'confirm',
  'prompt',
  'eval',
  'substring',
  'setTimeout',
  'setInterval'
];
const TERMS = { CONCAT_OPERATOR: '+' };

const assignmentSearch = Builder()
  .zeroOrMoreOf()
  .literally('[\\s;]', true)
  .zeroOrMoreOf()
  .anything()
  .literally('=')
  .zeroOrMoreOf()
  .anything()
  .literally(';')
  .build();

const concatSearch = Builder({ flags: 'gm' })
  .JS()
  .concatenation()
  .build();

/**
 * Search for variable assignment.
 * @returns {CustomSearcher}
 */
class VariableAssignmentSearcher extends CustomSearcher {
  constructor() {
    super({
      description: 'Searches for variable assignment.',
      id: 'CS-VARASSIGN-1',
      name: 'VariableAssignmentSearcher'
    });
  }

  getImpact(userInput) {
    let impact;
    let string = userInput.value;
    const patternIndex = string.search(assignmentSearch);

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

    if (0 <= string.indexOf(TERMS.CONCAT_OPERATOR)) {
      string = string.replace(concatSearch, '');
    }

    // If the pattern matches, the score will (at least) be LOW.
    // But if a function name is found, we give score MEDIUM.
    COMMON_FUNCTIONS.some((fnName) => {
      if (string.indexOf(fnName) < 0) {
        return false;
      }
      impact = SCORES.MEDIUM;
      return true;
    });

    return impact || SCORES.LOW;
  }
}

module.exports = new VariableAssignmentSearcher();
