/**
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 parseUrl = require('parseurl');
const requireHook = require('../../hooks/require');
const patcher = require('../../hooks/patcher');
const tracker = require('../../tracker');
const { PATCH_TYPES } = require('../../constants');
const TagRange = require('../models/tag-range');
const tagRangeUtil = require('../models/tag-range/util');
const { CallContext, Signature, PropagationEvent } = require('../models');
const { AsyncStorage, KEYS } = require('../../core/async-storage');
const agent = require('../../agent');

module.exports.handle = handle;
module.exports.patchServerStatic = patchServeStatic;
module.exports.patchSendModule = patchSendModule;

/**
 * Called to install require hook.
 */
function handle() {
  if (agent.config.assess.enable_sanitizer_serve_static) {
    requireHook.resolve(
      { name: 'serve-static' },
      (serveStatic) =>
        patchServeStatic(serveStatic));
    requireHook.resolve(
      { name: 'send' },
      (sendModule) =>
        patchSendModule(sendModule));
  }
}

/**
 * Patch the function to apply html-encoded tag to tracked return values.
 * @param {object} serveStaticExport The exported value of the serve-static module
 */
function patchServeStatic(serveStaticExport) {
  return patcher.patch(serveStaticExport, {
    name: 'serve-static',
    patchType: PATCH_TYPES.ASSESS_PROPAGATOR,
    alwaysRun: true,
    post(data) {
      const resultFn = data.result;
      data.result = patcher.patch(resultFn, {
        name: 'serve-static',
        patchType: PATCH_TYPES.ASSESS_PROPAGATOR,
        alwaysRun: true,
        pre(data) {
          const req = data.args[0];
          const path = parseUrl(req).pathname;

          AsyncStorage.set(KEYS.SERVE_STATIC_PATH, path);
        }
      });
    }
  });
}

function patchSendModule(sendModuleExport) {
  return patcher.patch(sendModuleExport, {
    name: 'send',
    patchType: PATCH_TYPES.ASSESS_PROPAGATOR,
    alwaysRun: true,
    pre(data) {
      const [req, path] = data.args;
      const serveStaticPath = AsyncStorage.get(KEYS.SERVE_STATIC_PATH);
      const reqPath = parseUrl(req).pathname;

      if (path !== serveStaticPath || path !== reqPath) return;

      const trackData = tracker.getData(path);
      if (trackData) {
        trackData.tagRanges = tagRangeUtil.add(
          trackData.tagRanges,
          new TagRange(0, path.length - 1, 'safe-path')
        );

        const event = new PropagationEvent({
          context: CallContext.create(data),
          parents: [trackData.event],
          signature: new Signature(
            'serve-static'
          ),
          source: 'P',
          target: 'R',
          tags: 'safe-path',
          tagRanges: trackData.tagRanges
        });
        trackData.event = event;
      }
    }
  });
}

