/**
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 common = module.exports;

/**
 * Checks if a charCode is within ASCII alpha range
 * @param {String} charCode charCodeAt value
 * @return {Boolean} if charCodeacter is alpha
 */
common.isASCIILetter = (charCode) =>
  (charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123);

/**
 * Checks if charCode is within ASCII number range
 *
 * @param {String} charCode charCodeAt value
 * @return {Boolean} if charCodeacter is numberic
 */
common.isASCIINumber = (charCode) => charCode > 47 && charCode < 58;

/**
 * Checks if character is one of the allowable special chars
 *
 * @param {Array} allowableSpecialChars list of allowable special chars
 * @param {String} value character to compare
 * @return {Boolean} if character is an allowable special char
 */
common.isAllowableSpecialChar = (isAllowableSpecialChars, value) =>
  isAllowableSpecialChars.indexOf(value) >= 0;

/**
 * Checks if character code is alpha or numeric
 *
 * @param {Int} charCode code representing character
 * @return {Boolean} if charCode is alphanumeric
 */
common.isASCIIAlphaNumeric = (charCode) =>
  common.isASCIILetter(charCode) || common.isASCIINumber(charCode);

/**
 * Checks if it is a valid host value
 *
 * @param {String} value value of a header that is contains a host
 * @return {Boolean} if value is alphanumeric and contains `.` `:` or `-`
 */
common.safeHost = (value) => {
  for (let i = 0; i < value.length; i++) {
    const char = value[i];
    const charCode = value.charCodeAt(i);
    const isAlphaNumeric = common.isASCIIAlphaNumeric(charCode);
    const allowableSpecial = common.isAllowableSpecialChar(
      ['.', ':', '-'],
      char
    );
    if (!isAlphaNumeric && !allowableSpecial) {
      return false;
    }
  }

  return true;
};
