/**
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 agentEmitter = require('../../../agent-emitter');
const logger = require('../../../core/logger')('contrast:rules:http:headers');

let cookieCommon;

module.exports = ({ common }) => {
  if (!cookieCommon) {
    cookieCommon = {
      report(request, ruleId, event, responseHeaders) {
        const cookieValue = responseHeaders['set-cookie'] || '';
        const props = {
          evidence: `set-cookie: ${cookieValue.toString()}`
        };

        common.emitFinding({
          ruleId,
          stack: event.stack,
          request,
          event,
          props
        });
      },
      registerCookieListener({ ruleId, isVulnerable }) {
        // data.events is a hash which maps a ruleId to the event for that ID.
        // if a single event maps to every rule, as in Express, the event will
        // be in events.any
        agentEmitter.on('session', function({
          request,
          events,
          responseHeaders
        }) {
          const event = events[ruleId] || events.any;
          if (!event) return;

          const reportFinding = isVulnerable(event.options, event.framework);

          if (reportFinding) {
            logger.debug('%s: %s', ruleId, request.uri);
            cookieCommon.report(request, ruleId, event, responseHeaders);
          }
        });
      }
    };
  }

  return cookieCommon;
};
