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

/**
 * InFilter hooks for vm module methods.
 * @module lib/rules/protect/in-filters/vm
 */

const BaseSensor = require('../../hooks/frameworks/base');
const constants = require('../../constants');
const patcher = require('../../hooks/patcher');
const { PATCH_TYPES } = require('../../constants');
const { emitSinkEvent } = require('../../hooks/frameworks/common');

const { SINK_TYPES } = constants;
const ID = 'vm';

class VMSensor extends BaseSensor {
  constructor(agent) {
    super({ id: ID, agent });
  }

  install({ ModuleHook }) {
    ModuleHook.resolve({ name: 'vm' }, (vm) => {
      ['Script', 'createScript', 'runInContext', 'runInThisContext'].forEach(
        (method) => {
          patcher.patch(vm, method, {
            name: 'vm',
            patchType: PATCH_TYPES.PROTECT_SINK,
            alwaysRun: true,
            pre(data) {
              const codeString = data.args[0];
              emitSinkEvent(codeString, SINK_TYPES.CODE_STRING, ID);
            }
          });
        }
      );

      patcher.patch(vm, 'runInNewContext', {
        name: 'vm',
        patchType: PATCH_TYPES.PROTECT_SINK,
        alwaysRun: true,
        pre: (wrapCtx) => {
          const codeString = wrapCtx.args[0];
          const env = wrapCtx.args[1];
          emitSinkEvent(codeString, SINK_TYPES.CODE_STRING, ID);
          emitSinkEvent(env, SINK_TYPES.CODE_ENV, ID);
        }
      });

      patcher.patch(vm, 'createContext', {
        name: 'vm',
        patchType: PATCH_TYPES.PROTECT_SINK,
        alwaysRun: true,
        pre: (wrapCtx) => {
          const env = wrapCtx.args[0];
          emitSinkEvent(env, SINK_TYPES.CODE_ENV, ID);
        }
      });

      patcher.patch(vm.Script.prototype, 'runInNewContext', {
        name: 'vm.Script.prototype',
        patchType: PATCH_TYPES.PROTECT_SINK,
        alwaysRun: true,
        pre: (wrapCtx) => {
          const env = wrapCtx.args[0];
          emitSinkEvent(env, SINK_TYPES.CODE_ENV, ID);
        }
      });
    });

    return this;
  }
}

module.exports = VMSensor;
