/**
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 agentEmitter = require('../../agent-emitter');
const htmlUtil = require('../../util/html-util');
const htmlCommon = require('./common');

const ruleId = 'autocomplete-missing';

module.exports = ({ common }) => {
  const rule = {};

  rule.check = function(body, bodyLC, responseHeaders) {
    // look for form tag with missing action attribute.
    // ex: <form method="post">..

    if (!htmlCommon.isHtmlContent(responseHeaders)) {
      return;
    }

    const elements = htmlUtil.getElements('form', bodyLC);

    for (let i = 0; i < elements.length; i++) {
      const autocomplete = htmlUtil.getAttribute('autocomplete', elements[i]);
      if (autocomplete !== 'off') {
        return {
          attribute: autocomplete,
          html: elements[i],
          start: 0,
          end: elements[i].length
        };
      }
    }
  };

  rule.handle = function() {
    require('./parseable-response-emitter').hook();
    agentEmitter.on('parseableResponse', function({
      request,
      responseHeaders,
      body,
      bodyLC
    }) {
      const vulnerableElement = rule.check(body, bodyLC, responseHeaders);
      if (vulnerableElement) {
        vulnerableElement.html = _.escape(vulnerableElement.html);
        common.emitFinding({ ruleId, request, props: vulnerableElement });
      }
    });
  };

  return rule;
};
