/**
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 agentEmitter = require('../../agent-emitter');
const {
  constants: { EVENTS }
} = require('../../core/fastify');

class FastifyAssessSources {
  constructor() {
    agentEmitter.on(
      EVENTS.PRE_VALIDATION,
      this.registerPreValidationHandler.bind(this)
    );
  }

  /**
   * Implements a `preValidation` hook to emit all the
   * necesary assess sources
   *
   * @param {Fastify.Request} request incoming request
   */
  registerPreValidationHandler(request) {
    FastifyAssessSources.emitHeaders(request);
    agentEmitter.emit('assess.body', request, 'body');
    agentEmitter.emit('assess.params', request, 'params');
    agentEmitter.emit('assess.query', request, 'query');
    agentEmitter.emit('assess.cookies', request, 'cookies');
    agentEmitter.emit('assess.body', request, 'file');
  }

  /**
   * In fastify >=3 the request model does not have a configurable
   * request.headers property. If this is the case we can't proxy its headers
   * property, just the headers on IncomingMessage instance.
   * @param {Fastify.Request} request
   * @returns {boolean}
   */
  static isRequestHeadersWritable(request) {
    const headersDescriptor = Object.getOwnPropertyDescriptor(
      request.constructor.prototype,
      'headers'
    );

    return !(
      headersDescriptor &&
      headersDescriptor.get &&
      !headersDescriptor.set
    );
  }

  /**
   * Emit headers for native IncomingMessage and fastify's Request if possible.
   * @param {Fastify.Request} request
   */
  static emitHeaders(request) {
    agentEmitter.emit('assess.headers', request.raw, 'headers');
    if (FastifyAssessSources.isRequestHeadersWritable(request)) {
      agentEmitter.emit('assess.headers', request, 'headers');
    }
  }
}

module.exports = FastifyAssessSources;
