/**
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 { Signature, CallContext } = require('../../models');
const policy = require('../../policy');
const { get } = require('lodash');
const agentEmitter = require('../../../agent-emitter');
const {
  constants: { EVENTS }
} = require('../../../core/koa');
const stackFactory = require('../../../core/stacktrace').singleton;

class KoaXssSink {
  constructor(agent) {
    this.common = require('../../sinks/common')(agent);
    this.rules = get(policy, 'rules');
    this.moduleName = 'koa';
    this.ruleId = 'reflected-xss';
    this.signature = new Signature({
      moduleName: this.moduleName,
      methodName: 'ctx.body', // only part used for the custom mapping
      isModule: true
    });

    this.registerStackCaptureHandler();
    this.registerResEndHandler();
  }

  /**
   * checks if an assess rule is enabled in policy
   */
  get enabled() {
    return get(this.rules, `${this.ruleId}.enabled`);
  }

  /**
   * Adds a listeners for when `ctx.body` is set and if body is tracked
   * it will create a new stack
   */
  registerStackCaptureHandler() {
    /**
     * @param {Object} params
     * @param {Koa.Context} params.ctx
     * @param {Boolean} params.tracked is body tracked?
     */
    agentEmitter.on(EVENTS.CTX_BODY, ({ ctx, tracked }) => {
      if (tracked) {
        ctx._cs_stack = getStacktrace();
      }

      ctx._cs_stack = null;
    });
  }

  /**
   * Implements a koa `onRoute` hook to wrap the handler
   * if it is a promise
   */
  registerResEndHandler() {
    const {
      report,
      isVulnerable,
      xss: { disallowedTags },
      requiredTags
    } = this.common;
    const { ruleId, signature } = this;

    agentEmitter.on(EVENTS.RES_END, (ctx) => {
      if (!this.enabled) {
        return;
      }

      const { body } = ctx;

      if (
        isVulnerable({
          input: body,
          disallowedTags,
          requiredTags,
          ruleId
        })
      ) {
        // the source should be building a stack when body is set, but if
        // it doesn't, the report will give some garbage code location like
        // process._nextTick()
        const { _cs_stack } = ctx;
        // The CallContext instance will use _cs_stack function if defined,
        // otherwise will generate one based on stackOpts
        const ctxt = CallContext.create({
          obj: ctx.response,
          args: [body],
          result: body,
          stacktrace: _cs_stack,
          stackOpts: {
            constructorOpt: agentEmitter.emit
          }
        });

        if (_cs_stack) {
          ctxt.stack = _cs_stack;
        }

        report({ ruleId, signature, input: body, ctxt });
      }
    });
  }
}

function getStacktrace() {
  return stackFactory.createSnapshot({
    constructorOpt: agentEmitter.emit
  });
}

module.exports = KoaXssSink;
