/**
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 {
  AsyncStorage,
  KEYS: { REQUEST }
} = require('../../../core/async-storage');
const {
  constants: { EVENTS },
  utils: {
    createSessionEvent,
    createSessionContext,
    secureFlagMissing,
    httpOnly
  }
} = require('../../../core/hapi');
const { emitSessionEvent } = require('../../../hooks/frameworks/common');
const patcher = require('../../../hooks/patcher');
const { PATCH_TYPES } = require('../../../constants');

class HapiResponseScanning {
  constructor() {
    this.instrumentSessionMethods();
  }

  instrumentSessionMethods() {
    const self = this;
    agentEmitter.on(EVENTS.HAPI_PRE_HANDLER, ({ server, h }) => {
      patcher.patch(server.constructor.prototype, 'state', {
        alwaysRun: true,
        name: 'hapi.server.state',
        patchType: PATCH_TYPES.ASSESS_SINK,
        pre(data) {
          const [, , options] = data.args;
          self.registerSessionHandler({
            moduleName: 'server',
            module: server,
            options
          });
        }
      });

      patcher.patch(h.constructor.prototype, 'state', {
        alwaysRun: true,
        name: 'hapi.state',
        patchType: PATCH_TYPES.ASSESS_SINK,
        pre(data) {
          const [, , options] = data.args;
          self.registerSessionHandler({
            moduleName: 'h',
            module: h,
            options
          });
        }
      });
    });
  }

  /**
   * registers an event when hapi response is `finished`
   * for response scanning assess rules
   */
  registerSessionHandler({ moduleName, module, options }) {
    agentEmitter.on(EVENTS.HAPI_FINISHED, () => {
      if (secureFlagMissing(options)) {
        this.handleSessionEvent({
          moduleName,
          module,
          ruleId: 'secure-flag-missing',
          options
        });
      }

      if (httpOnly(options)) {
        this.handleSessionEvent({
          moduleName,
          module,
          ruleId: 'httponly',
          options
        });
      }
    });
  }

  /**
   * Emit session events so they can
   * be checked and then reported to TeamServer.
   * @param {Object} params
   * @param {string} params.moduleName - name of the module (h|server)
   * @param {Object} params.module     - the module (h|server)
   * @param {string} params.ruleId     - the ruleid - 'httponly' | 'secure-flag-missing'
   * @param {Object} params.options    - the options passed to *.state
   */
  handleSessionEvent({ moduleName, module, ruleId, options }) {
    const { [REQUEST]: hapiRequest } = AsyncStorage.getContext();
    const ctxt = createSessionContext(module, [options], hapiRequest, 'P1', {
      constructorOpt: agentEmitter.emit
    });
    const events = {};
    events[ruleId] = createSessionEvent(
      moduleName,
      'state',
      ctxt,
      'P1',
      options
    );

    emitSessionEvent(events);
  }
}

module.exports = HapiResponseScanning;
