/**
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 logger = require('../../../core/logger')('contrast:rules:protect');
const { INPUT_TYPES, SINK_TYPES } = require('../common');

class ReflectedXssRule extends require('../') {
  constructor(settings) {
    super(settings);
    this.id = 'reflected-xss';
    this.name = 'Cross-Site Scripting';
    this.evidenceContextLength = 400;
    // Common Rule configuration values
    this.applicableInputs = [
      INPUT_TYPES.BODY,
      INPUT_TYPES.PARAMETER_NAME,
      INPUT_TYPES.PARAMETER_VALUE,
      INPUT_TYPES.JSON_VALUE,
      INPUT_TYPES.JSON_ARRAYED_VALUE,
      INPUT_TYPES.MULTIPART_FIELD_NAME,
      INPUT_TYPES.MULTIPART_VALUE,
      INPUT_TYPES.QUERYSTRING,
      INPUT_TYPES.XML_VALUE,
      INPUT_TYPES.URI,
      INPUT_TYPES.URL_PARAMETER
    ];
    this.applicableSinks = [SINK_TYPES.RESPONSE_BODY];

    this.usesLibInputAnalysis = true;
  }
  /**
   * Evaluates a SinkEvent contingent on <code>applicableSinks</code>.
   * @param {Object} params
   * @param {SinkEvent} params.event
   * @param {Set<Sample>} params.applicableSamples all (definite and ww) samples for xss
   */
  evaluateAtSink({ event, applicableSamples }) {
    if (!applicableSamples.size) {
      return;
    }

    const body = event.data.toString();
    for (const sample of applicableSamples) {
      const xssIndex = body.indexOf(sample.input.value);
      if (0 <= xssIndex) {
        this.appendAttackDetails(sample, { body, xssIndex });
        sample.captureAppContext(event);
        logger.warn(`EFFECTIVE - rule: ${this.id}, mode: ${this.mode} `);

        this.blockRequest(sample);
      }
    }
  }

  /**
   * From the information gathered at the sink where the exploit arrived,
   * will build the necessary details DTM for TS to provide user with
   * detailed attack information.
   * @param   {Sample} sample   The sample who's value was found in sink
   * @param   {String} body     The request body containing attack value
   * @param   {Number} xssIndex The index of the attack value in the body
   * @returns {Object}
   */
  buildDetails(sample, findings) {
    const { body, xssIndex } = findings;

    if (!body || xssIndex < 0) {
      return null;
    }

    const chopFront = this.evidenceContextLength < xssIndex;
    const offsetDiff = xssIndex - this.evidenceContextLength;

    const offset = chopFront ? this.evidenceContextLength : xssIndex;
    const sampleStart = chopFront ? offsetDiff : 0;
    const sampleStop = offset + this.evidenceContextLength;

    return {
      input: sample.input.value,
      matches: [
        {
          evidence: body.substr(sampleStart, sampleStop),
          offset
        }
      ]
    };
  }
}

module.exports = ReflectedXssRule;
