/**
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 moduleHook = require('../../hooks/require');
const _ = require('lodash');
const patcher = require('../../hooks/patcher');
const { PATCH_TYPES } = require('../../constants');
const {
  constants: { EVENTS }
} = require('../../core/hapi');
const agentEmitter = require('../../agent-emitter');

class HapiErrorHandler {
  constructor() {
    this.instrumentBoom();
  }

  /**
   * instruments `boom` after `hapi` is required
   */
  instrumentBoom() {
    agentEmitter.on(EVENTS.HAPI_EXPORT, () => {
      // Hapi won't let you pass an error to reply which isn't a
      // Boom AND format the response yourself; you have to pick one.
      // The workaround is to hook boom.boomify
      // (see hapi/response.js:internals.Response.wrap) and change the
      // formatting of the boom it returns.
      moduleHook.resolve(
        { name: 'boom' },
        this.registerErrorHandler.bind(this)
      );
      moduleHook.resolve(
        { name: '@hapi/boom' },
        this.registerErrorHandler.bind(this)
      );
    });
  }

  /**
   * Checks if the error is a contrast error
   * and if we haven't already reformatted it
   * and then changes statusCode to 403 and
   * sets payload to undefined
   */
  registerErrorHandler(boom) {
    patcher.patch(boom, 'boomify', {
      name: 'boom.boomify',
      patchType: PATCH_TYPES.FRAMEWORK,
      alwaysRun: true,
      post(data) {
        let boomified = data.result;
        const statusCode = _.get(boomified, 'output.statusCode');

        // we only want to reformat the error once, boomified gets
        // called a few times during an error handling situation
        if ('contrast' === boomified.type && statusCode !== 403) {
          boomified = _.set(boomified, 'output.statusCode', 403);
          boomified.reformat();
          boomified = _.set(boomified, 'output.payload', undefined);
          data.result = boomified;
        }
      }
    });
  }
}

module.exports = HapiErrorHandler;
