/**
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 = {
  CONCAT_OPERATOR: '+',
  LOCATION: 'location'
};

const locationSearch = Builder()
  .literally(TERMS.LOCATION)
  .JS()
  .blockOrInlineComments()
  .literally('=')
  .zeroOrMoreOf()
  .anything()
  .build();

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

class LocationSetSearcher extends CustomSearcher {
  constructor() {
    super({
      description: 'Searches for a location being set.',
      id: 'CS-LOC-1',
      name: 'Location set searcher'
    });
  }

  getImpact(userInput) {
    const locationIndex = userInput.value.indexOf(TERMS.LOCATION);
    if (locationIndex < 0) {
      return SCORES.NONE;
    }

    const patternIndex = userInput.value.search(locationSearch);
    if (patternIndex < 0) {
      return SCORES.NONE;
    }

    const concatIndex = userInput.value.indexOf(
      TERMS.CONCAT_OPERATOR,
      locationIndex + 8
    );

    return 0 <= concatIndex && concatSearch.test(userInput.value)
      ? SCORES.HIGH
      : SCORES.LOW;
  }
}

module.exports = new LocationSetSearcher();
