/**
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 tracker = require('../../../tracker');
const moduleHook = require('../../../hooks/require');
const patcher = require('../../../hooks/patcher');
const { PATCH_TYPES } = require('../../../constants');
const TagRange = require('../../models/tag-range');
const tagRangeUtil = require('../../models/tag-range/util');
const { addTagRangesWithOffset, trackResult } = require('../common');
const {
  SCOPE_NAMES: { NO_PROPAGATION }
} = require('../../../core/async-storage/scopes');
const Scopes = require('../../../core/async-storage/scopes');
const ContrastJSON = require('../../../core/rewrite/injections').get('JSON');

/**
 * Applies `origStart` and `origStop` keys to a tagRange so we can keep track of
 * locations before replacing specifiers in a format string.
 * @param {TagRange} target
 * @param {number} start
 * @param {number} stop
 * @return {TagRange}
 */
const tagRangeWithOriginals = (
  target,
  start = target.start,
  stop = target.stop
) => {
  target.origStart = start;
  target.origStop = stop;
  return target;
};

/**
 * Moves an existing format string tag range.
 * @param {Object} resultMeta
 * @param {string} resultMeta.str result string of the util.format call
 * @param {TagRange} tagRange
 * @param {string} arg
 * @return {TagRange}
 */
const moveTagRange = (resultMeta, tagRange, arg) =>
  tagRangeWithOriginals(
    new TagRange(
      tagRange.start + arg.length - 2, // subtract 2 to account for specifier
      Math.min(resultMeta.str.length - 1, tagRange.stop + arg.length - 2), // subtract 2 to account for specifier
      tagRange.tag
    ),
    tagRange.origStart,
    tagRange.origStop
  );

/**
 * Splits an existing format string tag range when it spans across a specifier.
 * @param {Object} resultMeta
 * @param {string} resultMeta.str result string of the util.format call
 * @param {TagRange} tagRange
 * @param {string} arg
 * @param {number} index
 * @return {TagRange[]}
 */
const splitTagRange = (resultMeta, tagRange, arg, index) => {
  const firstPart = tagRangeWithOriginals(
    new TagRange(tagRange.start, index - 1, tagRange.tag)
  );

  if (index + arg.length > resultMeta.str.length - 1) return [firstPart];
  const secondPart = tagRangeWithOriginals(
    new TagRange(
      index + arg.length,
      Math.min(resultMeta.str.length - 1, tagRange.stop + arg.length - 2), // subtract 2 to account for specifier
      tagRange.tag
    )
  );

  return [firstPart, secondPart];
};

/**
 * Adjusts existing tag ranges that were present on the first argument, the format string.
 * @param {Object} resultMeta
 * @param {string} resultMeta.str result string of the util.format call
 * @param {TagRange[]} resultMeta.fmtStrTagRanges
 * @param {string} arg
 * @param {number} index
 */
const adjustTagRanges = (resultMeta, arg, index) => {
  if (!resultMeta.fmtStrTagRanges.length) return;
  const tagRanges = [];
  resultMeta.fmtStrTagRanges.forEach((tagRange) => {
    if (tagRange.origStart >= index) {
      tagRanges.push(moveTagRange(resultMeta, tagRange, arg));
    } else if (tagRange.origStop >= index) {
      tagRanges.push(...splitTagRange(resultMeta, tagRange, arg, index));
    } else {
      tagRanges.push(tagRange);
    }
  });

  resultMeta.fmtStrTagRanges = tagRanges;
};

/**
 * Tries to JSON.stringify an argument, returning '[Circular]' if the argument
 * is an object containing a circular reference. Copied from node.js internals.
 * @see https://github.com/nodejs/node/blob/master/lib/internal/util/inspect.js
 *
 * @param {any} arg
 * @return {string}
 */
const tryStringify = (arg) => {
  let CIRCULAR_ERROR_MESSAGE;
  const firstErrorLine = (error) => error.message.split('\n')[0];

  try {
    return JSON.stringify(arg);
  } catch (err) {
    // Populate the circular error message lazily
    if (!CIRCULAR_ERROR_MESSAGE) {
      try {
        const a = {};
        a.a = a;
        JSON.stringify(a);
      } catch (err) {
        CIRCULAR_ERROR_MESSAGE = firstErrorLine(err);
      }
    }
    if (
      err.name === 'TypeError' &&
      firstErrorLine(err) === CIRCULAR_ERROR_MESSAGE
    ) {
      return '[Circular]';
    }
    throw err;
  }
};

/**
 * Iterate over the format string, accounting for and adjusting tag ranges based
 * on specifiers detected.
 * @param {Object} opts
 * @param {import('util')} opts.util
 * @param {string} opts.fmtStr
 * @param {any[]} opts.args
 * @param {Object} opts.resultMeta
 * @param {number} opts.resultMeta.offset
 */
const checkForSpecifiers = ({ util, fmtStr, args, resultMeta }) => {
  for (let i = 0; i < fmtStr.length; i++, resultMeta.offset++) {
    // %
    if (fmtStr.charCodeAt(i) === 37) {
      const nextChar = fmtStr.charCodeAt(++i);
      const arg = args.shift();
      if (arg) {
        let str;
        switch (nextChar) {
          // s
          case 115: {
            str = util.format('%s', arg);
            addTagRangesWithOffset(resultMeta, str);
            break;
          }
          // j
          case 106: {
            const result = tryStringify(arg);
            // NOTE: we have to apply the same propagation logic from JSON.stringify manually here.
            str =
              result === '[Circular]'
                ? '[Circular]'
                : Scopes.runInAllowAllScope(() =>
                    ContrastJSON.value.stringify(arg)
                  );
            addTagRangesWithOffset(resultMeta, str);
            break;
          }
          // o
          case 111: {
            // NOTE: see above. tracking not yet implemented for util.inspect, but when it is we
            //   will need to apply the same propagation logic used in the util.inspect propagator
            //   here
            str = util.inspect(arg, {
              showHidden: true,
              showProxy: true
            });
            break;
          }
          // O
          case 79: {
            // NOTE: see above. tracking not yet implemented for util.inspect, but when it is we
            //   will need to apply the same propagation logic used in the util.inspect propagator
            //   here
            str = util.inspect(arg);
            break;
          }
          default: {
            str = String(arg);
          }
        }

        addTagRangesWithOffset(resultMeta, str);
        resultMeta.offset += str.length - 1;
        adjustTagRanges(resultMeta, str, i - 1);
      }
    }
  }
};

/**
 * Increments offset and propagates args that were not formatted with specifiers
 * util.format('%s', 'foo', 'additional-arg');
 *
 * @param {Object} params
 * @param {Object} params.resultMeta
 * @param {number} params.resultMeta.offset
 * @param {any[]} params.args
 * @param {util} params.util util module
 */
const propagateAdditionalArgs = ({ resultMeta, args, util }) => {
  args.forEach((arg) => {
    resultMeta.offset++;
    /**
     * NODE-937: simulate what util.format would do to args that are not a string
     * NOTE: tracking not yet implemented for util.inspect, but when it is we
     * will need to apply the same propagation logic used in the util.inspect propagator
     */
    arg = typeof arg === 'string' ? arg : util.inspect(arg);
    addTagRangesWithOffset(resultMeta, arg);
    resultMeta.offset += arg.length;
  });
};

/**
 *
 * @param {Object} data
 * @param {any[]} data.args
 * @param {import('util')} data.obj node util module
 */
const propagate = function propagate(util, data) {
  const {
    args: [fmtStr, ...args]
  } = data;

  if (!fmtStr || !args.length) return;

  const resultMeta = {
    str: data.result,
    method: 'util.format',
    offset: 0,
    tagRanges: [],
    fmtStrTagRanges: [],
    // List of any events that the existing tag ranges came from
    parents: []
  };

  const fmtStrMeta = tracker.getData(fmtStr);
  if (fmtStrMeta) {
    resultMeta.fmtStrTagRanges = fmtStrMeta.tagRanges.map((tagRange) =>
      tagRangeWithOriginals(
        new TagRange(tagRange.start, tagRange.stop, tagRange.tag)
      )
    );
  }

  checkForSpecifiers({ util, fmtStr, args, resultMeta });

  if (resultMeta.fmtStrTagRanges.length) {
    tagRangeUtil.addAllInPlace(
      resultMeta.tagRanges,
      resultMeta.fmtStrTagRanges
    );
    resultMeta.parents.push(fmtStrMeta.event);
  }

  propagateAdditionalArgs({ resultMeta, args, util });

  trackResult(resultMeta, data);
};

/**
 * Entry point to propagator provider
 * This instruments util.format
 */
module.exports.handle = function handle() {
  moduleHook.resolve({ name: 'util' }, (util) => {
    patcher.patch(util, 'format', {
      scope: NO_PROPAGATION,
      name: 'util.format',
      patchType: PATCH_TYPES.ASSESS_PROPAGATOR,
      post: propagate.bind(null, util)
    });
  });
};
