/**
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 ACCEPT_TYPES = ['image/', 'text/css', 'text/javascript'];
const CONTENT_TYPES = [...ACCEPT_TYPES, 'application/javascript'];
const util = module.exports;

/**
 * Returns true if the request URL appears to point to a static file.
 *
 * @param {String} url
 * @return {Boolean}
 */
util.isStaticFile = (url) => {
  try {
    return /\.(?:js|css|jpeg|jpg|gif|png|ico|woff|svg|pdf|eot|ttf|jar)$/i.test(
      url
    );
  } catch (e) {
    return false;
  }
};

/**
 * Checks both accept headers and content-type headers
 * to see if they match expected
 *
 * @param {Object} headers headers from an IncomingRequest
 * @return {Boolean}
 */
util.isMediaType = (headers = {}) => {
  const { accept } = headers;
  const contentType = headers['content-type'];

  if (!accept || accept === '*/*') {
    return false;
  }

  if (!isContentType(contentType)) {
    return ACCEPT_TYPES.filter((type) => accept.startsWith(type)).length > 0;
  }

  return true;
};

/**
 * Checks content-type header to see if it starts with a list of expected
 * values.  Also checks to see if header contains the string "font"
 *
 * @param {String} contentType value of content-type header
 * @return {Boolean}
 */
const isContentType = (contentType) => {
  if (!contentType) {
    return false;
  }

  return (
    CONTENT_TYPES.filter((type) => contentType.startsWith(type)).length > 0 ||
    /font/.test(contentType)
  );
};
