/**
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/restify');

class RestifyXssSink {
  constructor(agent) {
    this.common = require('../../sinks/common')(agent);
    this.rules = get(policy, 'rules');
    this.ruleId = 'reflected-xss';
    this.signature = new Signature({
      moduleName: 'restify.Response.prototype',
      methodName: 'send',
      isModule: true
    });
    this.registerXssHandler();
  }

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

  /**
   * Adds a post listener to `Response.prototype.__send` for
   * `reflected-xss` checking
   */
  registerXssHandler() {
    const {
      isVulnerable,
      xss: { disallowedTags },
      requiredTags,
      report
    } = this.common;
    const { signature, ruleId } = this;
    if (!this.enabled) {
      return;
    }

    agentEmitter.on(EVENTS.SEND.POST, (data) => {
      const input = get(data, 'args.0.body', {});
      const vulnerable = isVulnerable({
        input,
        disallowedTags,
        requiredTags,
        ruleId
      });

      if (vulnerable) {
        report({
          signature,
          input,
          ctxt: CallContext.create({
            obj: data.obj,
            args: [input],
            stackOpts: {
              constructorOpt: agentEmitter.emit
            }
          }),
          ruleId
        });
      }
    });
  }
}

module.exports = RestifyXssSink;
