/**
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.
*/
/**
 * @module lib/assess/sinks/hapi16-xss
 * XXX: This might not be the only thing we need to hook
 * to be entirely accurate. If it's possible to add data to the
 * response body through hapi after reply(), then we will also need
 * to hook the hapi.Response prototype method which allows this.
 */
'use strict';

const _ = require('lodash');
const { Signature, CallContext } = require('../models');
const policy = require('../policy');

const ruleId = 'reflected-xss';
const signature = new Signature({
  moduleName: 'hapi',
  methodName: 'reply',
  isModule: true
});

module.exports = ({
  common: {
    isVulnerable,
    report,
    requiredTags,
    xss: { disallowedTags }
  }
}) => ({
  handle() {
    require('../../hooks/hapi-16-reply').hook(function(reply) {
      const { response } = reply;
      reply.response = function(result) {
        // reply.response is bound to the instance of reply,
        // so we need to provide 'reply' as the call context.
        const ret = response.apply(reply, [result]);
        const enabled =
          _.get(policy, 'rules.reflected-xss.enabled') &&
          _.get(policy, 'rules.reflected-xss_hapi16.enabled');

        if (
          enabled &&
          isVulnerable({ input: result, disallowedTags, requiredTags, ruleId })
        ) {
          const ctxt = CallContext.create({
            obj: reply,
            args: [result],
            result: ret,
            stackOpts: {
              constructorOpt: reply.response
            }
          });
          report({ ruleId, signature, input: result, ctxt });
        }

        return ret;
      };

      return reply;
    });
  }
});
