/**
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 {
  endsWith,
  negate,
  overEvery,
  overSome,
  startsWith
} = require('lodash/fp');

const constants = require('../../constants');

const { PROTOCOLS } = constants;
const FTP = `${PROTOCOLS.FTP.toLowerCase()}:`;
const HTTP = `${PROTOCOLS.HTTP.toLowerCase()}:`;
const HTTPS = `${PROTOCOLS.HTTPS.toLowerCase()}:`;
const DTD_EXTENSION = '.dtd';
const FILE_START = 'file:';
const GOPHER_START = 'gopher:';
const JAR_START = 'jar:';
const DOT = '.';
const FORWARD_SLASH = '/';
const UP_DIR_LINUX = '../';
const UP_DIR_WIN = '..\\';
const ENTITY_TYPES = { SYSTEM: 'SYSTEM', PUBLIC: 'PUBLIC' };

const EXTERNAL_RX = /<!ENTITY\s+[a-zA-Z0-f]+\s+(?:SYSTEM|PUBLIC)\s+['"](.*?)['"]\s*>/g;
// <!ENTITY name SYSTEM "URI">
const SYSTEM_ID_REGEX = /<!ENTITY\s+([a-zA-Z0-9]+)\s+SYSTEM\s+['"](.*?)['"]\s*>/;
// <!ENTITY name PUBLIC "public_ID" "URI">
const PUBLIC_ID_REGEX = /<!ENTITY\s+([a-zA-Z0-9]+)\s+PUBLIC\s+['"](.*?)['"]\s+['"](.*?)['"]\s*>/;
// We only use this against lowercase strings; removed A-Z for speed
const FILE_PATTERN_WINDOWS = /^[\\\\]*[a-z]{1,3}:.*/;

// Helper Functions
const isHttp = overSome([startsWith(HTTP), startsWith(HTTPS)]);
const isNotDTD = negate(endsWith(DTD_EXTENSION));
const isExternal = overSome([
  overEvery([isHttp, isNotDTD]),
  startsWith(FTP),
  startsWith(FILE_START),
  startsWith(JAR_START),
  startsWith(GOPHER_START),
  startsWith(FORWARD_SLASH),
  startsWith(DOT),
  startsWith(UP_DIR_LINUX),
  startsWith(UP_DIR_WIN),
  (id) => FILE_PATTERN_WINDOWS.test(id)
]);

function* Iterator(xml) {
  let match;

  while ((match = EXTERNAL_RX.exec(xml))) {
    const meta = {
      finish: match.index + match[0].length,
      start: match.index,
      xml
    };
    const entity = Entity.create(match[0], meta);

    if (entity.external) {
      yield entity;
    } else {
      continue;
    }
  }

  return null;
}

class Finder {
  /**
   * @param {String} xml
   */
  constructor(xml = '') {
    this._parsed = false;
    this.xml = xml;
    this.entities = [];
    this.prolog = null;
    this.parse();
  }

  /**
   * Parses the XML for external entity declarations and adds
   * the instances found to the provided collection.
   */
  parse() {
    let lastIdx = 0;

    if (this._parsed) {
      return this;
    }

    for (const entity of Iterator(this.xml)) {
      this.entities.push(entity);
      lastIdx = entity.finish;
    }

    if (lastIdx) {
      this.prolog = this.xml.substr(0, lastIdx);
    }

    this._parsed = true;

    return this;
  }

  static create(xml) {
    return Reflect.construct(Finder, [xml]);
  }
}

class Entity {
  constructor(declaration = '', meta = {}) {
    this.declaration = declaration;
    this.finish = meta.finish;
    this.start = meta.start;
    this.external = false;
    this.type = null;
    this.name = null;
    this.publicId = null; // type = PUBLIC
    this.uri = null;
    this.parse(declaration);
  }

  parse(declaration) {
    let match;

    match = SYSTEM_ID_REGEX.exec(declaration);

    if (match) {
      this.name = match[1];
      this.type = ENTITY_TYPES.SYSTEM;
      this.uri = match[2];
      this.external = Entity.isExternal(this.uri);
      return;
    }

    match = PUBLIC_ID_REGEX.exec(declaration);
    if (match) {
      this.name = match[1];
      this.publicId = match[2];
      this.type = ENTITY_TYPES.PUBLIC;
      this.uri = match[3];
      this.external = Entity.isExternal(this.uri);
      return;
    }
  }

  static isExternal(entityId) {
    if (!entityId) {
      return false;
    }

    return isExternal(entityId.toLowerCase());
  }

  static create(declaration, meta) {
    return Reflect.construct(Entity, [declaration, meta]);
  }
}

module.exports = Finder;
// Export mainly for testing purposes:
module.exports.Finder = Finder;
module.exports.Iterator = Iterator;
module.exports.Entity = Entity;
module.exports.ENTITY_TYPES = ENTITY_TYPES;
