/**
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 = {
  BEHAVIOR: 'behavior',
  URL: 'url'
};

const behaviorUrlSearch = Builder()
  .JS()
  .literally(TERMS.BEHAVIOR)
  .blockOrInlineComments()
  .literally(':')
  .blockOrInlineComments()
  .literally(TERMS.URL)
  .build();

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

/**
 * Search for a location being set.
 *   behavior:url
 *
 * @returns {CustomSearcher}
 */
class BehaviorUrlSearcher extends CustomSearcher {
  constructor() {
    super({
      description: 'Searches for a location being set.',
      id: 'CS-BEH-1',
      name: 'BehaviorUrlSearcher'
    });
  }

  getImpact(userInput, options) {
    options = options || {};

    const value = (options.stringLower =
      options.stringLower || userInput.value.toLowerCase());

    const behaviorIndex = value.indexOf(TERMS.BEHAVIOR);
    const urlIndex =
      behaviorIndex < 0 ? value.indexOf(TERMS.URL, behaviorIndex + 9) : null;

    /* Quick bail if the 2 keywords aren't there, in order. */
    return urlIndex < 0
      ? SCORES.NONE
      : (function() {
          /* Otherwise, we can do some more heavy lifting.    */
          const patternIndex = value.search(behaviorUrlSearch);

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

          return functionCallSearch.test(value.substring(urlIndex))
            ? SCORES.HIGH
            : SCORES.MEDIUM;
        })();
  }
}

module.exports = new BehaviorUrlSearcher();
