/**
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 EventEmitter = require('events');
const emitter = new EventEmitter();
const domain = require('domain');
const errorHandler = require('./protect/errors/handler');
const PROTECT_EVENTS = ['protect.source', 'protect.sink'];
const blockRequest = require('./util/block-request');
const isContrastError = require('./util/is-contrast-error');

class AgentEmitter extends EventEmitter {
  constructor() {
    super();
    this._events = emitter._events;
  }

  /*
   * Protect: runs the emit in a domain so we can
   * properly catch SecurityException and return
   * 403 in a given framework
   *
   * Assess: skip running in domain just call
   * emit, no need to wrap in domain
   */
  emit(name, ...data) {
    // only wrap protect events in domain
    // to properly handle throwing SecurityException
    if (PROTECT_EVENTS.includes(name)) {
      const protectDomain = domain.create();
      errorHandler(this, protectDomain);
      protectDomain.enter();
      super.emit.call(this, name, ...data);
      protectDomain.exit();
    } else {
      super.emit.call(this, name, ...data);
    }
  }

  /**
   * Checks if error is contrast error and blocks request
   *
   * @param {Error} err
   * @param {ServerResponse} res
   * @return {Boolean}
   */
  handleError(err, res) {
    if (isContrastError(err)) {
      blockRequest(res);
      return true;
    }

    return false;
  }

  /**
   * EventEmitter's 'on', with an optional 3rd argument
   * @memberof AgentEmitter
   * @param {string} event    The name of the event
   * @param {Function} fn       The event handler being registered
   * @param {Object} [rule]   The rule we would like to add the event to
   */
  on(eventName, listener, rule) {
    if (rule) {
      rule.events = rule.events || {};
      if (!rule.events[eventName]) {
        rule.events[eventName] = [];
      }
      rule.events[eventName].push(listener);
    }
    return super.on(eventName, listener);
  }
}

module.exports = new AgentEmitter();
module.exports.AgentEmitter = AgentEmitter;
