/**
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 { SCORES } = common;
const TERMS = {
  EQUALS: '=',
  STYLE: 'style',
  URL: 'url'
};

const styleSearcher = RegExp(
  'style\\s*=.*((url(?:\\s*)(?:\\/\\*.*\\*\\/)?(?:\\s*)\\(.*\\))|(background\\-image:\\\\\\d{4}))',
  'i'
);

/**
 * Search for URL invocations via style/url() calls, like:
 *   <div style=content:url(...)>
 * @returns {CustomSearcher}
 */
class StyleUrlInjectionSearcher extends CustomSearcher {
  constructor() {
    super({
      name: 'StyleUrlInjectionSearcher',
      id: 'CS-EVADE-STYLE',
      description: 'Search for URL invocations via style/url() calls.'
    });
  }

  getImpact(userInput, options) {
    options = options || {};
    const stringLower = (options.stringLower =
      options.stringLower || userInput.value.toLowerCase());

    const styleIndex = stringLower.indexOf(TERMS.STYLE);
    if (styleIndex < 0) {
      return SCORES.NONE;
    }

    const urlIndex = stringLower.indexOf(TERMS.URL, styleIndex + 5);
    if (urlIndex < 0 || !styleSearcher.test(userInput.value)) {
      return SCORES.NONE;
    }

    return SCORES.HIGH;
  }
}

module.exports = new StyleUrlInjectionSearcher();
