/**
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 _ = require('lodash');
const { Signature, CallContext } = require('../assess/models');
const { emitSessionEvent } = require('../hooks/frameworks/common');
const patcher = require('../hooks/patcher');
const { PATCH_TYPES } = require('../constants');
const requireHook = require('../hooks/require');
const logger = require('../core/logger')('contrast:hooks:express');
const SessionEvent = require('../assess/response-scanning/cookies/events');
const { signatures } = require('../assess/policy/signatures.json');
const agentEmitter = require('../agent-emitter');
const constants = require('../constants');
const Helpers = require('../core/express/utils');

const { SINK_TYPES } = constants;
const { EVENTS } = Helpers;

function hook() {
  requireHook.resolve({ name: 'express-session' }, function(session) {
    const signature = signatures['express-session'];
    logger.info('hooking express-session middleware constructor');
    // Return the hooked function as the export.
    const hooked = patcher.patch(session, {
      name: 'express.hookedSessionConstructor',
      patchType: PATCH_TYPES.FRAMEWORK,
      alwaysRun: true,
      post(data) {
        const options = data.args[0];

        const sig = new Signature(signature);
        // obfuscate the cookie secret
        if (_.get(data.args, '[0].secret')) {
          _.set(data.args, '[0].secret', '[HIDDEN]');
        }

        const ctxt = CallContext.create(data);
        // event of when the session was initialized that will be reused for all
        // session findings
        const sessionEvent = new SessionEvent({
          context: ctxt,
          signature: sig,
          source: 'P0',
          options,
          framework: 'express'
        });

        data.result = patcher.patch(data.result, {
          name: 'express.hookedSessionMiddleware',
          patchType: PATCH_TYPES.FRAMEWORK,
          alwaysRun: true,
          pre(data) {
            const [, res] = data.args;
            patcher.patch(res, 'setHeader', {
              name: 'express.hookedSessionSetHeader',
              patchType: PATCH_TYPES.SINK,
              alwaysRun: true,
              post(data) {
                try {
                  if (
                    data.args[0] &&
                    data.args[0].toLowerCase() === 'set-cookie'
                  ) {
                    emitSessionEvent({ any: sessionEvent });
                  }
                } catch (err) {
                  logger.info(`Unable to patch res.setHeader. ${err}`);
                }
              }
            });
          },
          post(data) {
            const [, res] = data.args;
            patcher.patch(res, 'end', {
              patchType: PATCH_TYPES.SINK,
              name: 'http.ServerResponse.end - express-session',
              pre(data) {
                agentEmitter.emit(
                  EVENTS.REQUEST_SEND,
                  data.args[0],
                  SINK_TYPES.RESPONSE_BODY
                );
              }
            });
          }
        });
      }
    });

    return hooked;
  });
}

module.exports = hook;
