All files / src/utils htmlBuilder.js

100% Statements 334/334
100% Branches 59/59
100% Functions 11/11
100% Lines 334/334

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 33513x 13x 13x 13x 13x 13x 13x 13x 13x 14x 14x 14x 14x 14x 13x 13x 13x 13x 13x 13x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 13x 13x 13x 13x 13x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 13x 13x 13x 13x 13x 6x 6x 6x 6x 2x 2x 2x 2x 2x 6x 6x 6x 6x 1x 6x 1x 1x 1x 1x 1x 6x 6x 6x 6x 1x 6x 1x 1x 1x 1x 1x 6x 6x 6x 6x 3x 6x 3x 3x 3x 3x 3x 3x 3x 3x 6x 6x 6x 2x 2x 2x 2x 2x 6x 6x 6x 1x 1x 1x 1x 1x 6x 6x 4x 4x 4x 4x 10x 10x 10x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 6x 13x 13x 13x 13x 13x 3x 3x 3x 3x 1x 1x 1x 1x 1x 3x 3x 3x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 1x 3x 1x 1x 3x 3x 3x 13x 13x 13x 13x 13x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 4x 13x 13x 13x 13x 13x 3x 1x 1x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 3x 13x 13x 13x 13x 13x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 13x 13x 13x 13x 13x 51x 50x 50x 50x 50x 50x 50x 50x 50x 50x 51x 13x 13x 13x 13x 13x 9x 8x 8x 8x 9x 13x 13x 13x 13x 13x 13x 13x 13x 5x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 5x 13x 13x 13x  
/**
 * Constructor de HTML para work items
 * Genera HTML completo para renderizar en PDFs con Puppeteer
 */
 
const createDOMPurify = require("isomorphic-dompurify");
 
class WorkItemHTMLBuilder {
  constructor(workItem, selectedFields, cssStyles) {
    this.workItem = workItem;
    this.selectedFields = selectedFields || [];
    this.cssStyles = cssStyles || "";
    this.fields = workItem.fields || {};
  }
 
  /**
   * Construye el HTML completo para el PDF
   * @returns {string} HTML completo con estilos
   */
  buildFullHTML() {
    return `<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <title>WI #${this.workItem.id} - ${this._escapeHtml(this.fields["System.Title"] || "Sin título")}</title>
  <style>
${this.cssStyles}
  </style>
</head>
<body>
  ${this._buildHeader()}
  ${this._buildMetadataTable()}
  ${this._buildFieldSections()}
  ${this._buildFooter()}
</body>
</html>`;
  }
 
  /**
   * Construye el encabezado del documento
   */
  _buildHeader() {
    const workItemType = this.fields["System.WorkItemType"] || "Work Item";
    const title = this.fields["System.Title"] || "Sin título";
    const state = this.fields["System.State"] || "N/A";
 
    return `
  <div class="workitem-header">
    <div class="workitem-type">${this._escapeHtml(workItemType)} #${this.workItem.id}</div>
    <h1 class="workitem-title">${this._escapeHtml(title)}</h1>
    <div class="workitem-state state-${this._sanitizeClassName(state)}">${this._escapeHtml(state)}</div>
  </div>`;
  }
 
  /**
   * Construye la tabla de metadata básica
   */
  _buildMetadataTable() {
    const metadata = [];
 
    // Proyecto
    if (this.fields["System.TeamProject"]) {
      metadata.push({
        label: "Proyecto",
        value: this.fields["System.TeamProject"],
      });
    }
 
    // Iteración (siempre incluir si seleccionado)
    if (
      this.selectedFields.includes("iteration") &&
      this.fields["System.IterationPath"]
    ) {
      metadata.push({
        label: "Iteración",
        value: this.fields["System.IterationPath"],
      });
    }
 
    // Área (siempre incluir si seleccionado)
    if (
      this.selectedFields.includes("area") &&
      this.fields["System.AreaPath"]
    ) {
      metadata.push({
        label: "Área",
        value: this.fields["System.AreaPath"],
      });
    }
 
    // Asignado a
    if (
      this.selectedFields.includes("assignedTo") &&
      this.fields["System.AssignedTo"]
    ) {
      const assignedTo = this.fields["System.AssignedTo"];
      const displayName =
        assignedTo.displayName || assignedTo.uniqueName || "N/A";
      metadata.push({
        label: "Asignado a",
        value: displayName,
      });
    }
 
    // Estado (siempre incluir si seleccionado)
    if (this.selectedFields.includes("state") && this.fields["System.State"]) {
      metadata.push({
        label: "Estado",
        value: this.fields["System.State"],
      });
    }
 
    // Tags
    if (this.selectedFields.includes("tags") && this.fields["System.Tags"]) {
      metadata.push({
        label: "Etiquetas",
        value: this.fields["System.Tags"],
      });
    }
 
    if (metadata.length === 0) return "";
 
    const rows = metadata
      .map(
        (m) => `
      <tr>
        <td class="metadata-label">${this._escapeHtml(m.label)}</td>
        <td class="metadata-value">${this._escapeHtml(m.value)}</td>
      </tr>`,
      )
      .join("");
 
    return `
  <div class="workitem-metadata">
    <table class="metadata-table">
      <tbody>
${rows}
      </tbody>
    </table>
  </div>`;
  }
 
  /**
   * Construye las secciones de campos seleccionados
   */
  _buildFieldSections() {
    let sections = "";
 
    // Descripción
    if (this.selectedFields.includes("description")) {
      sections += this._buildFieldSection(
        "Descripción",
        this.fields["System.Description"],
      );
    }
 
    // Criterios de Aceptación
    if (this.selectedFields.includes("acceptanceCriteria")) {
      sections += this._buildFieldSection(
        "Criterios de Aceptación",
        this.fields["System.AcceptanceCriteria"] ||
          this.fields["Microsoft.VSTS.Common.AcceptanceCriteria"],
      );
    }
 
    // Tareas hijas
    if (
      this.selectedFields.includes("childItems") &&
      this.workItem.childItems &&
      this.workItem.childItems.length > 0
    ) {
      sections += this._buildChildItemsSection();
    }
 
    return sections;
  }
 
  /**
   * Construye una sección de campo con HTML
   */
  _buildFieldSection(label, htmlContent) {
    if (!htmlContent) return "";
 
    // CRÍTICO: Sanitizar HTML para prevenir XSS
    // No confiar en datos externos incluso si vienen de Azure DevOps
    const sanitizedContent = this._sanitizeHtml(htmlContent);
 
    return `
  <div class="workitem-field">
    <h2 class="workitem-field-label">${this._escapeHtml(label)}</h2>
    <div class="workitem-content">
      ${sanitizedContent}
    </div>
  </div>`;
  }
 
  /**
   * Construye la tabla de tareas hijas
   */
  _buildChildItemsSection() {
    if (!this.workItem.childItems || this.workItem.childItems.length === 0) {
      return "";
    }
 
    const rows = this.workItem.childItems
      .map((child) => {
        const id = child.id || "N/A";
        const type = child.fields?.["System.WorkItemType"] || "Task";
        const title = child.fields?.["System.Title"] || "Sin título";
        const state = child.fields?.["System.State"] || "N/A";
 
        return `
        <tr>
          <td>#${this._escapeHtml(String(id))}</td>
          <td>${this._escapeHtml(type)}</td>
          <td>${this._escapeHtml(title)}</td>
          <td><span class="state-badge state-${this._sanitizeClassName(state)}">${this._escapeHtml(state)}</span></td>
        </tr>`;
      })
      .join("");
 
    return `
  <div class="workitem-field">
    <h2 class="workitem-field-label">Tareas (${this.workItem.childItems.length})</h2>
    <table class="child-items-table">
      <thead>
        <tr>
          <th style="width: 80px;">ID</th>
          <th style="width: 100px;">Tipo</th>
          <th>Título</th>
          <th style="width: 120px;">Estado</th>
        </tr>
      </thead>
      <tbody>
${rows}
      </tbody>
    </table>
  </div>`;
  }
 
  /**
   * Construye el footer del documento
   */
  _buildFooter() {
    const now = new Date().toLocaleString("es-ES", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
 
    return `
  <div class="workitem-footer">
    <p>Documento generado el ${this._escapeHtml(now)} por G-Bot</p>
  </div>`;
  }
 
  /**
   * Escapa caracteres HTML para prevenir XSS
   */
  _escapeHtml(text) {
    if (!text) return "";
    const str = String(text);
    const map = {
      "&": "&amp;",
      "<": "&lt;",
      ">": "&gt;",
      '"': "&quot;",
      "'": "&#039;",
    };
    return str.replace(/[&<>"']/g, (m) => map[m]);
  }
 
  /**
   * Sanitiza texto para usar como nombre de clase CSS
   */
  _sanitizeClassName(text) {
    if (!text) return "unknown";
    return String(text)
      .toLowerCase()
      .replace(/[^a-z0-9]/g, "-");
  }
 
  /**
   * Sanitiza contenido HTML usando DOMPurify para prevenir XSS
   * Permite solo tags seguros y remueve atributos peligrosos
   * @param {string} html - Contenido HTML a sanitizar
   * @returns {string} HTML sanitizado
   */
  _sanitizeHtml(html) {
    if (!html) return "";
 
    // CRÍTICO: Usar DOMPurify con configuración estricta
    const DOMPurify = createDOMPurify();
 
    // Configuración de whitelist estricta
    const config = {
      ALLOWED_TAGS: [
        "p",
        "br",
        "strong",
        "b",
        "em",
        "i",
        "u",
        "ul",
        "ol",
        "li",
        "h1",
        "h2",
        "h3",
        "h4",
        "h5",
        "h6",
        "span",
        "div",
        "table",
        "tr",
        "td",
        "th",
        "thead",
        "tbody",
      ],
      ALLOWED_ATTR: ["class"],
      FORBID_TAGS: ["script", "iframe", "embed", "object"],
      FORBID_ATTR: ["onerror", "onload", "onclick", "onmouseover"],
    };
 
    return DOMPurify.sanitize(html, config);
  }
}
 
module.exports = { WorkItemHTMLBuilder };