/**
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 COLOR_CODE_MAX_LENGTH = '"#ABC123"'.length;

const searchers = {
  colorCode: () => /^["']#[a-f0-9]{3,6}["']/i,
  dash: () => /["']\s*--/,
  hash: () => /["']\s*#/g
};

class SQLCommentSearcher extends CustomSearcher {
  constructor() {
    super({
      description: 'Searches for SQL comments.',
      id: 'CS-HCS-1',
      name: 'SqlCommentSearcher'
    });
  }

  getImpact(userInput) {
    const hasComment =
      hasDashComment(userInput.value) || hasHashComment(userInput.value);

    return hasComment ? SCORES.MEDIUM : SCORES.NONE;
  }
}

// Scoring on dash-comments, "--", are straightforward.
function hasDashComment(string) {
  return searchers.dash().test(string);
}

// Otherwise hash-comments, "#", need more context to make an assertion.
function hasHashComment(string) {
  const colorCodePattern = searchers.colorCode();
  const hashPattern = searchers.hash();
  let match = hashPattern.exec(string);
  let substring;

  while (match) {
    // Get segment of the string to check if its a color code
    substring = string.substr(match.index, COLOR_CODE_MAX_LENGTH);

    // If so, ignore.
    if (colorCodePattern.test(substring)) {
      match = hashPattern.exec(string);
    } else {
      return true;
    }
  }

  return false;
}

module.exports = new SQLCommentSearcher();
