/**
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';

/**
 * @module lib/rules/protect/nosqli/nosql-scanner/MongoDBScanner
 * Tokenize MongoDB queries and searches for injections.
 */

const scannerLib = require('./index');
const SCAN_STATES = require('./scan-states');

const { BaseScanner } = scannerLib;

module.exports = class JavaScriptScanner extends BaseScanner {
  readAtCursor(state) {
    return state.value() === SCAN_STATES.INSIDE_TEMPLATE ||
      this.isStartOfTemplateString(state)
      ? this.processTemplate(state)
      : super.readAtCursor(state);
  }

  processTemplate(state) {
    const { codeString: query, index: idx } = state;
    const threeBehind = query[idx - 2];
    const twoBehind = query[idx - 1];
    const behind = query[idx];
    const atCursor = query[idx + 1];
    let escaped;

    // We're entering new state
    if (state.value() !== SCAN_STATES.INSIDE_TEMPLATE) {
      return state.is(SCAN_STATES.INSIDE_TEMPLATE);
    }

    escaped = twoBehind !== '\\' && behind === '\\';
    const leaving = !escaped && atCursor === '`';

    escaped = twoBehind === '\\' && threeBehind !== twoBehind;
    const nesting = behind === '$' && atCursor === '{' && !escaped;

    if (nesting) {
      return state
        .flag('INCLUSIVE_CAPTURE', true)
        .enter(SCAN_STATES.EXPECTING_TOKEN);
    }

    return !leaving
      ? state.is(SCAN_STATES.INSIDE_TEMPLATE)
      : state.flag('INCLUSIVE_CAPTURE', true).is(SCAN_STATES.EXPECTING_TOKEN);
  }

  processExpectingToken(state) {
    const { codeString: query, index: idx } = state;
    const twoBehind = query[idx - 1];
    const behind = query[idx];
    const atCursor = query[idx + 1];

    // Check whether we're in template interpolation
    if (state.nestedState() === SCAN_STATES.INSIDE_TEMPLATE) {
      const escape = behind === '\\' && twoBehind !== behind;
      if (atCursor === '}' && !escape) {
        return state.exit();
      }
    }

    return super.processExpectingToken(state);
  }

  processInsideToken(state) {
    const { codeString: query, index: idx } = state;
    const twoBehind = query[idx - 1];
    const behind = query[idx];
    const atCursor = query[idx + 1];

    // Check whether we're in template interpolation
    if (state.nestedState() === SCAN_STATES.INSIDE_TEMPLATE) {
      const escape = behind === '\\' && twoBehind !== behind;
      if (atCursor === '}' && !escape) {
        return state.exit();
      }
    }
    return super.processInsideToken(state);
  }

  isStartOfTemplateString(state) {
    const { codeString: query, index: idx } = state;
    const atCursor = query[idx + 1];
    const currentState = state.value();

    return (
      currentState !== SCAN_STATES.INSIDE_DOUBLEQUOTE &&
      currentState !== SCAN_STATES.INSIDE_SINGLEQUOTE &&
      currentState !== SCAN_STATES.INSIDE_TEMPLATE &&
      atCursor === '`'
    );
  }

  /**
   * Whether the cursor is on dot operator.
   * @param   {ScanState} state   The current scan state of the parser.
   * @returns {Boolean}          Whether the character is an '.' operator
   */
  isDotOperator({ codeString: query, index: idx }) {
    return query && query[idx + 1] === '.';
  }

  /**
   * Overloading because we have additional operators in the language.
   * @param   {ScanState} state   The current scan state of the parser.
   * @returns {Boolean}          Whether the character is an operator
   */
  isOperator(state) {
    return super.isOperator(state) || this.isDotOperator(state);
  }

  /**
   * Whether the analysis at the current state suggests that
   * the next token is the start of a line comment;
   * @param   {ScanState} state   The current scan state of the parser.
   * @returns {Boolean}          Whether next token is line comment start
   */
  isLineCommentStart({ codeString: query, index: idx }) {
    return query && query[idx + 1] === '/' && query[idx + 2] === '/';
  }

  /**
   * Whether a single quote can be an escape character within a single quote.
   * @returns {Boolean} true by default.
   */
  canSingleQuoteEscapeInSingleQuote() {
    return false;
  }

  /**
   * Whether a double quote can be an escape character within a double quote.
   * @returns {Boolean} false by default.
   */
  canDoubleQuoteEscapeInDoubleQuote() {
    return false;
  }
};
