/**
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 { INPUT_TYPES, PATCH_TYPES } = require('../../constants');
const { emitSourceEvent } = require('../../hooks/frameworks/common');
const agentEmitter = require('../../agent-emitter');
const {
  constants: { EVENTS }
} = require('../../core/koa');
const isContrastError = require('../../util/is-contrast-error');
const blockRequest = require('../../util/block-request');
const patcher = require('../../hooks/patcher');

class KoaProtectSources {
  constructor() {
    this.id = 'koa';
    this.registerSourceHandlers();
  }

  registerSourceHandlers() {
    agentEmitter.on(
      EVENTS.REQ_START,
      this.registerRequestStartHandler.bind(this)
    );

    agentEmitter.on(EVENTS.CTX_PARAMS, this.registerParamsHandler.bind(this));

    agentEmitter.on(
      EVENTS.CTX_REQUEST_BODY,
      this.registerBodyHandler.bind(this)
    );

    agentEmitter.on(
      EVENTS.MULTI_PART,
      this.registerMultiPartHandler.bind(this)
    );
    agentEmitter.on(EVENTS.COOKIE, this.registerCookieHandler.bind(this));
    agentEmitter.on(EVENTS.CTX, this.registerOnErrorHandler.bind(this));
  }

  /**
   * Handles emitting `protect.source` for query
   *
   * @param {Koa.Context} ctx koa request ctx
   */
  registerRequestStartHandler(ctx) {
    emitSourceEvent(
      ctx.request,
      ctx.req,
      ctx.res,
      'query',
      INPUT_TYPES.QUERYSTRING,
      this.id
    );
  }

  /**
   * Handles when ctx.params is parsed by emitting `protect.source`
   *
   * @param {Koa.Context} ctx koa request ctx
   */
  registerParamsHandler(ctx) {
    emitSourceEvent(
      ctx,
      ctx.req,
      ctx.res,
      'params',
      INPUT_TYPES.URL_PARAMETER,
      this.id
    );
  }

  /**
   * Handles when ctx.request.body is set by emitting `protect.source`
   *
   * @param {Koa.Context.Request} ctx koa request ctx
   */
  registerBodyHandler({ ctx }) {
    emitSourceEvent(
      ctx.request,
      ctx.req,
      ctx.res,
      'body',
      INPUT_TYPES.BODY,
      this.id
    );
  }

  /**
   * Handles when `koa-multer` middleware is run and properly parses
   * a multipart form and puts the body on the `req`
   *
   * @param {Object} params
   * @param {IncomingMessage} params.req
   * @param {ServerResponse} param.res
   */
  registerMultiPartHandler({ req, res }) {
    emitSourceEvent(req.request, req, res, 'body', INPUT_TYPES.BODY, this.id);
  }

  /**
   * Handles when `koa-cookie` middleware is run and properly parses
   * a cookies that are put on ctx
   *
   * @param {Koa.Context.Request} ctx koa request ctx
   */
  registerCookieHandler(ctx) {
    emitSourceEvent(
      ctx,
      ctx.req,
      ctx.res,
      'cookie',
      INPUT_TYPES.COOKIE_VALUE,
      this.id
    );
  }

  /**
   * patches `ctx.onerror` to properly block protect request
   * when applicable
   *
   * @param {Koa.Context} ctx koa request ctx
   */
  registerOnErrorHandler(ctx) {
    patcher.patch(ctx, 'onerror', {
      name: 'koa.ctx.onerror',
      patchType: PATCH_TYPES.FRAMEWORK,
      alwaysRun: true,
      pre(data) {
        const [err] = data.args;
        if (isContrastError(err)) {
          blockRequest(this.res);
          data.result = patcher.preempt(null);
        }
      }
    });
  }
}

module.exports = KoaProtectSources;
