/**
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 KEYWORDS = [
  'document',
  'location',
  'window',
  'top',
  'this',
  'parent',
  'self',
  'frames'
];

const mapAccessSearch = Builder()
  .JS()
  .anyOf(KEYWORDS)
  .blockOrInlineComments()
  .literally('[')
  .zeroOrMoreOf()
  .anything()
  .literally(']')
  .build();
//    =>
//    (document|location|window|top|this|parent|self|frames)(?:\s*)(?:\/\*[\\s\\S]*\*\/)?(?:\s*)\[[\\s\\S]*\]

const invocationSearch = Builder()
  .JS()
  .functionCall()
  .build();

/**
 * Search for map access of an object, like:
 *   window[/*../ 'na' + 'me']
 *   document["location"]
 *   document /*../  [  "locat" + "ion" + "" ]
 * We heighten the impact from MEDIUM to HIGH if we see a method invocation
 * afterwards, like:
 *   window["alert"]()
 *
 * @returns {CustomSearcher}
 */
class MapAccessSearcher extends CustomSearcher {
  constructor() {
    super({
      description:
        'Search for bracket-style access to an object e.g. obj["prop"].',
      id: 'CS-EVADE-MAPACCESS',
      name: 'Map access searcher'
    });
  }

  getImpact(userInput) {
    let impact;

    KEYWORDS.some(function(keyword) {
      const keywordIndex = userInput.value.indexOf(keyword);
      if (keywordIndex < 0) {
        impact = SCORES.NONE;
        return true;
      }

      const patternIndex = userInput.value.search(
        mapAccessSearch,
        keywordIndex
      );
      if (patternIndex < 0) {
        impact = SCORES.NONE;
        return true;
      }

      impact =
        0 <= userInput.value.search(invocationSearch, patternIndex)
          ? SCORES.HIGH
          : SCORES.MEDIUM;

      return true;
    });

    return impact;
  }
}

module.exports = new MapAccessSearcher();
