/**
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 patcher = require('../../hooks/patcher');
const { PATCH_TYPES } = require('../../constants');
const moduleHook = require('../../hooks/require');
const { CallContext, Signature } = require('../models');
const {
  RULES: { REFLECTED_XSS }
} = require('../../constants');

const signature = new Signature({
  moduleName: 'http.ClientResponse',
  methodName: 'write',
  isModule: true
});
const moduleName = 'dustjs-linkedin';

class Handler {
  constructor({ report, isVulnerable, requiredTags, xss: { disallowedTags } }) {
    this._isVulnerable = isVulnerable;
    this.report = report;
    this.requiredTags = requiredTags;
    this.disallowedTags = disallowedTags;
  }

  isVulnerable(input) {
    const { requiredTags, disallowedTags } = this;
    const ret = this._isVulnerable({
      input,
      ruleId: REFLECTED_XSS,
      disallowedTags,
      requiredTags
    });
    return ret;
  }

  handle() {
    moduleHook.resolve({ name: moduleName }, (dust) =>
      this.handleRequire(dust)
    );
  }

  getType(obj) {
    return obj && obj.constructor && obj.constructor.name;
  }

  isResponseType(typeName) {
    return typeName === 'ServerResponse';
  }

  patchDust(dust) {
    const self = this;
    patcher.patch(dust, 'stream', {
      name: moduleName,
      patchType: PATCH_TYPES.ASSESS_SINK,
      alwaysRun: true,
      post(data) {
        self.patchStream(data.result);
      }
    });
  }

  /**
   * Patch the pipe method and check wether the stream is targeting a
   * response instance. If so, add the instance to the set of streams
   * we should follow.
   */
  patchStream(streamInstance) {
    const self = this;
    patcher.patch(streamInstance, 'pipe', {
      name: 'dust.Stream.prototype',
      patchType: PATCH_TYPES.ASSESS_SINK,
      alwaysRun: true,
      pre({ args: [maybeRes] }) {
        self.patchStreamTarget(maybeRes);
      }
    });
  }

  patchStreamTarget(target) {
    const self = this;
    const typeName = self.getType(target);

    if (self.isResponseType(typeName)) {
      patcher.patch(target, 'write', {
        name: 'dust.pipeTarget',
        patchType: PATCH_TYPES.ASSESS_SINK,
        alwaysRun: true,
        post({ args: [str], hooked }) {
          if (self.isVulnerable(str)) {
            self.report({
              ruleId: REFLECTED_XSS,
              signature,
              input: str,
              ctxt: CallContext.create({
                obj: typeName,
                args: [str],
                result: str,
                stackOpts: {
                  constructorOpt: hooked
                }
              })
            });
          }
        }
      });
    }
  }

  handleRequire(dust) {
    this.patchDust(dust);
    return dust;
  }
}

module.exports = ({ common }) => new Handler(common);
module.exports.Handler = Handler;
