All files / src/services businessImpactService.ts

61.87% Statements 237/383
71.42% Branches 45/63
66.66% Functions 16/24
61.87% Lines 237/383

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 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572                1x         1x 1x 1x 1x 1x 1x 1x 1x                       1x 274x   274x 274x 274x                 274x 22x 22x 22x 22x 22x     22x 22x       22x 8x 8x     14x 22x               274x 8x 8x                 274x 15x 15x 15x 15x   15x 15x     15x 15x     15x                 274x 2x 2x 2x 2x 1x 1x   1x 1x 2x                   274x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x   1x       1x       1x 1x     1x           1x       1x       1x       1x 1x                   274x 18x 18x 18x 18x     18x 18x 18x 18x 18x 18x 18x     18x 18x 18x 18x 18x     18x 18x 18x     18x 18x 3x 18x 4x 18x 4x 18x 4x 18x 3x 18x   18x 18x                 274x                             274x 14x 14x 14x 14x   14x     14x   14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x         274x 14x 14x 3x 14x 3x 14x 2x 14x 3x 14x 3x 14x   14x 14x         274x 14x 14x 3x 14x 3x 14x 2x 14x 3x 14x 3x 14x   14x 14x         274x 14x 14x 3x 14x 3x 14x 2x 14x 3x 14x 3x 14x   14x 14x         274x 37x 37x 37x 37x 12x 37x 12x 37x 13x 37x   37x 37x         274x 1x 1x       274x             274x 274x 274x 274x 274x 274x 274x 274x 274x 274x 274x 274x 274x 274x 274x 274x 274x 274x 274x 274x 274x 274x 274x 274x 274x 274x 274x             274x       16x 16x 16x 274x               1x 1x 1x 1x 1x                   1x                                                                                                                                                                                                                                                                        
import { SecurityLevel } from "../types/cia";
import {
  BusinessImpactDetail,
  BusinessImpactDetails,
  CIAComponentType,
  CIADataProvider,
  CIADetails,
} from "../types/cia-services";
import { normalizeSecurityLevel } from "../utils/securityLevelUtils";
 
/**
 * Category icons for business impact categories
 */
const CATEGORY_ICONS: Record<string, string> = {
  financial: "💰",
  operational: "⚙️",
  reputational: "🏆",
  strategic: "🎯",
  regulatory: "📜",
  summary: "📊",
};
 
/**
 * Service for business impact related functionality
 *
 * ## Business Perspective
 *
 * This service quantifies the business impact of security controls across
 * different dimensions including financial, operational, reputational,
 * strategic, and regulatory perspectives. It helps organizations understand
 * the business value of their security investments. 💼
 */
export class BusinessImpactService {
  private dataProvider: CIADataProvider;
 
  constructor(dataProvider: CIADataProvider) {
    this.dataProvider = dataProvider;
  }
 
  /**
   * Get business impact details for a security level
   *
   * @param component - CIA component (confidentiality, integrity, availability)
   * @param level - Security level
   * @returns Business impact details
   */
  public getBusinessImpact(
    component: CIAComponentType,
    level: SecurityLevel = "Moderate" as SecurityLevel
  ): BusinessImpactDetails {
    const normalizedLevel = normalizeSecurityLevel(level);
    const options = this.getCIAOptions(component);
 
    // Fix the type by adding a more specific return type for getCIAOptions
    const componentDetails = options
      ? (options[normalizedLevel] as CIADetails | undefined)
      : undefined;
 
    // If we have detailed business impact details, use them
    if (componentDetails?.businessImpactDetails) {
      return componentDetails.businessImpactDetails;
    }
 
    // Otherwise, create a default structure
    return this.createDefaultBusinessImpact(component, normalizedLevel);
  }
 
  /**
   * Get impact category icon
   *
   * @param category - Impact category
   * @returns Emoji icon representing the category
   */
  public getCategoryIcon(category: string): string {
    return CATEGORY_ICONS[category.toLowerCase()] || "❓";
  }
 
  /**
   * Get business impact description for a security level
   *
   * @param component - CIA component
   * @param level - Security level
   * @returns Business impact description
   */
  public getBusinessImpactDescription(
    component: CIAComponentType,
    level: SecurityLevel
  ): string {
    const options = this.getCIAOptions(component);
    // Fix the type by adding a more specific return type for getCIAOptions
    const componentDetails = options
      ? (options[level] as CIADetails | undefined)
      : undefined;
    // Use nullish coalescing for null/undefined handling
    return (
      componentDetails?.businessImpact ??
      this.getDefaultBusinessImpactDescription(component, level)
    );
  }
 
  /**
   * Get detailed description of business impact
   *
   * @param category - Impact category
   * @param detail - Business impact detail
   * @returns Formatted detailed description
   */
  public getDetailedDescription(
    category: string,
    detail?: BusinessImpactDetail
  ): string {
    if (!detail) {
      return `No ${category} impact details available`;
    }
 
    const icon = this.getCategoryIcon(category);
    return this.formatImpactDetail(detail, category, icon);
  }
 
  /**
   * Format impact detail
   *
   * @param detail - Business impact detail
   * @param category - Impact category
   * @param icon - Category icon
   * @returns Formatted impact detail
   */
  private formatImpactDetail(
    detail: BusinessImpactDetail,
    category: string,
    icon: string
  ): string {
    let description = `${icon} **${this.capitalizeFirstLetter(
      category
    )} Impact**: ${detail.description}`;
 
    if (detail.riskLevel) {
      description += `\n- Risk Level: ${detail.riskLevel}`;
    }
 
    if (category === "financial" && detail.annualRevenueLoss) {
      description += `\n- Potential Revenue Loss: ${detail.annualRevenueLoss}`;
    }
 
    if (category === "operational" && detail.meanTimeToRecover) {
      description += `\n- Mean Time to Recover: ${detail.meanTimeToRecover}`;
    }
 
    if (
      category === "regulatory" &&
      detail.complianceViolations &&
      detail.complianceViolations.length > 0
    ) {
      description += `\n- Compliance Violations: ${detail.complianceViolations.join(
        ", "
      )}`;
    }
 
    if (category === "strategic" && detail.competitiveAdvantage) {
      description += `\n- Competitive Advantage: ${detail.competitiveAdvantage}`;
    }
 
    if (detail.complianceImpact) {
      description += `\n- Compliance Impact: ${detail.complianceImpact}`;
    }
 
    if (detail.reputationalImpact) {
      description += `\n- Reputational Impact: ${detail.reputationalImpact}`;
    }
 
    return description;
  }
 
  /**
   * Calculate business impact level based on security levels
   *
   * @param availabilityLevel - Availability security level
   * @param integrityLevel - Integrity security level
   * @param confidentialityLevel - Confidentiality security level
   * @returns Business impact level description
   */
  public calculateBusinessImpactLevel(
    availabilityLevel: SecurityLevel,
    integrityLevel: SecurityLevel = availabilityLevel,
    confidentialityLevel: SecurityLevel = availabilityLevel
  ): string {
    // Get the minimum security level across all three components
    // as it represents the weakest link in the security chain
    const levelValues = {
      None: 0,
      Low: 1,
      Moderate: 2,
      High: 3,
      "Very High": 4,
    };
 
    // Find the minimum level value
    const minLevelValue = Math.min(
      levelValues[availabilityLevel],
      levelValues[integrityLevel],
      levelValues[confidentialityLevel]
    );
 
    // Map back to a SecurityLevel
    const minLevel = Object.keys(levelValues).find(
      (key) => levelValues[key as SecurityLevel] === minLevelValue
    ) as SecurityLevel;
 
    // Calculate impact based on the minimum security level
    switch (minLevel) {
      case "None":
        return "Critical";
      case "Low":
        return "High";
      case "Moderate":
        return "Medium";
      case "High":
        return "Low";
      case "Very High":
        return "Minimal";
      default:
        return "Unknown";
    }
  }
 
  /**
   * Get default business impact description based on component and level
   *
   * @param component - CIA component
   * @param level - Security level
   * @returns Default business impact description
   */
  private getDefaultBusinessImpactDescription(
    component: CIAComponentType,
    level: SecurityLevel
  ): string {
    const impact = this.calculateBusinessImpactLevel(level);
    return `${impact} business impact due to ${level.toLowerCase()} ${component} security level`;
  }
 
  /**
   * Create default business impact details
   *
   * @param component - CIA component
   * @param level - Security level
   * @returns Default business impact details
   */
  private createDefaultBusinessImpact(
    component: CIAComponentType,
    level: SecurityLevel
  ): BusinessImpactDetails {
    const impact = this.calculateBusinessImpactLevel(level);
    // Use the riskLevel in the description to make it consistent
    const riskLevel = this.getRiskLevelForSecurityLevel(level);
 
    // Use the impact mapping to get detailed impact descriptions
    const impactDetails = this.getImpactForLevel(level);
 
    return {
      summary: `${impact} impact for ${level} ${component}`,
      financial: {
        description: `${
          impactDetails.financialImpact
        } financial impact with ${riskLevel} risk due to ${level.toLowerCase()} ${component} controls`,
        riskLevel: riskLevel,
        annualRevenueLoss: this.getDefaultRevenueLoss(level),
      },
      operational: {
        description: `${
          impactDetails.operationalImpact
        } operational impact due to ${level.toLowerCase()} ${component} controls`,
        riskLevel: `${impact} Risk`,
        meanTimeToRecover: this.getDefaultRecoveryTime(level),
      },
      reputational: {
        description: `${
          impactDetails.reputationalImpact
        } reputational impact due to ${level.toLowerCase()} ${component} controls`,
        riskLevel: `${impact} Risk`,
      },
    };
  }
 
  /**
   * Get risk level based on security level
   */
  private getRiskLevelForSecurityLevel(level: SecurityLevel): string {
    switch (level) {
      case "None":
        return "Critical Risk";
      case "Low":
        return "High Risk";
      case "Moderate":
        return "Medium Risk";
      case "High":
        return "Low Risk";
      case "Very High":
        return "Minimal Risk";
      default:
        return "Unknown Risk";
    }
  }
 
  /**
   * Get default annual revenue loss percentage based on security level
   */
  private getDefaultRevenueLoss(level: SecurityLevel): string {
    switch (level) {
      case "None":
        return ">20% of annual revenue";
      case "Low":
        return "10-20% of annual revenue";
      case "Moderate":
        return "5-10% of annual revenue";
      case "High":
        return "1-5% of annual revenue";
      case "Very High":
        return "<1% of annual revenue";
      default:
        return "Unknown revenue impact";
    }
  }
 
  /**
   * Get default recovery time based on security level
   */
  private getDefaultRecoveryTime(level: SecurityLevel): string {
    switch (level) {
      case "None":
        return "Unpredictable";
      case "Low":
        return "24-48 hours";
      case "Moderate":
        return "4-8 hours";
      case "High":
        return "1 hour";
      case "Very High":
        return "<15 minutes";
      default:
        return "Unknown recovery time";
    }
  }
 
  /**
   * Get options for a CIA component
   */
  private getCIAOptions(
    component: CIAComponentType
  ): Record<string, CIADetails> {
    switch (component) {
      case "confidentiality":
        return this.dataProvider.confidentialityOptions;
      case "integrity":
        return this.dataProvider.integrityOptions;
      case "availability":
        return this.dataProvider.availabilityOptions;
      default:
        return {};
    }
  }
 
  /**
   * Capitalize first letter of a string
   */
  private capitalizeFirstLetter(string: string): string {
    return string.charAt(0).toUpperCase() + string.slice(1);
  }
 
  // Convert unused constants and functions to proper implementation
  // We're properly marking mapping as a utility type with clearer usage intent
  private readonly impactMapping: Record<
    SecurityLevel,
    {
      financialImpact: string;
      operationalImpact: string;
      reputationalImpact: string;
    }
  > = {
    None: {
      financialImpact: "Negligible",
      operationalImpact: "Minimal",
      reputationalImpact: "Insignificant",
    },
    Low: {
      financialImpact: "Minor",
      operationalImpact: "Limited",
      reputationalImpact: "Localized",
    },
    Moderate: {
      financialImpact: "Significant",
      operationalImpact: "Substantial",
      reputationalImpact: "Moderate",
    },
    High: {
      financialImpact: "Major",
      operationalImpact: "Severe",
      reputationalImpact: "Extensive",
    },
    "Very High": {
      financialImpact: "Critical",
      operationalImpact: "Catastrophic",
      reputationalImpact: "Global",
    },
  };
 
  /**
   * Gets impact details for a security level from the mapping
   * @param level - Security level to look up
   * @returns Impact details for the specified level
   */
  private getImpactForLevel(level: SecurityLevel): {
    financialImpact: string;
    operationalImpact: string;
    reputationalImpact: string;
  } {
    return this.impactMapping[level] || this.impactMapping.Moderate;
  }
}
 
/**
 * Create a BusinessImpactService with the provided data provider
 *
 * @param dataProvider - Data provider with CIA options
 * @returns BusinessImpactService instance
 */
export function createBusinessImpactService(
  dataProvider: CIADataProvider
): BusinessImpactService {
  return new BusinessImpactService(dataProvider);
}
 
/**
 * Get business impact details based on security levels
 *
 * @param availabilityLevel - Availability security level
 * @param integrityLevel - Integrity security level
 * @param confidentialityLevel - Confidentiality security level
 * @returns Business impact details
 */
export const getBusinessImpact = async (
  availabilityLevel: SecurityLevel,
  integrityLevel: SecurityLevel,
  confidentialityLevel: SecurityLevel
): Promise<BusinessImpactDetail> => {
  // This would normally fetch from an API, but for now we'll return mock data
 
  // Calculate overall risk level based on security levels
  const overallSecurityLevel = calculateOverallSecurityLevel(
    availabilityLevel,
    integrityLevel,
    confidentialityLevel
  );
 
  // Map security level to risk level (inverse relationship)
  const riskLevel = securityLevelToRiskLevel(overallSecurityLevel);
 
  return {
    description: `Business impact assessment based on A:${availabilityLevel}, I:${integrityLevel}, C:${confidentialityLevel}`,
    riskLevel: riskLevel,
    annualRevenueLoss: calculateRevenueLoss(riskLevel),
    complianceViolations: ["GDPR", "HIPAA", "PCI DSS"],
    meanTimeToRecover: calculateOperationalDowntime(riskLevel),
    complianceImpact: `Potential compliance violations with ${calculateRegulatoryImpact(
      riskLevel
    )}`,
    reputationalImpact: `Reputation damage could affect ${calculateReputationImpact(
      riskLevel
    )} of customers`,
    // Remove summary property as it's not in the interface
  };
};
 
// Helper functions
function calculateOverallSecurityLevel(
  availabilityLevel: SecurityLevel,
  integrityLevel: SecurityLevel,
  confidentialityLevel: SecurityLevel
): SecurityLevel {
  const levels = [availabilityLevel, integrityLevel, confidentialityLevel];
 
  if (levels.includes("None")) return "None";
  if (levels.includes("Low")) return "Low";
  if (levels.includes("Moderate")) return "Moderate";
  if (levels.includes("High")) return "High";
  return "Very High";
}
 
function securityLevelToRiskLevel(securityLevel: SecurityLevel): string {
  switch (securityLevel) {
    case "None":
      return "Critical";
    case "Low":
      return "High";
    case "Moderate":
      return "Medium";
    case "High":
      return "Low";
    case "Very High":
      return "Minimal";
    default:
      return "Unknown";
  }
}
 
function calculateRevenueLoss(riskLevel: string): string {
  switch (riskLevel) {
    case "Critical":
      return "$500,000+";
    case "High":
      return "$100,000-$500,000";
    case "Medium":
      return "$50,000-$100,000";
    case "Low":
      return "$10,000-$50,000";
    case "Minimal":
      return "Under $10,000";
    default:
      return "Unknown";
  }
}
 
function calculateOperationalDowntime(riskLevel: string): string {
  switch (riskLevel) {
    case "Critical":
      return "7+ days";
    case "High":
      return "3-7 days";
    case "Medium":
      return "1-3 days";
    case "Low":
      return "4-24 hours";
    case "Minimal":
      return "Under 4 hours";
    default:
      return "Unknown";
  }
}
 
function calculateReputationImpact(riskLevel: string): string {
  switch (riskLevel) {
    case "Critical":
      return "50%+";
    case "High":
      return "25-50%";
    case "Medium":
      return "10-25%";
    case "Low":
      return "5-10%";
    case "Minimal":
      return "Under 5%";
    default:
      return "Unknown";
  }
}
 
function calculateRegulatoryImpact(riskLevel: string): string {
  switch (riskLevel) {
    case "Critical":
      return "major regulatory frameworks with severe penalties";
    case "High":
      return "multiple regulatory frameworks";
    case "Medium":
      return "at least one major regulatory framework";
    case "Low":
      return "minor regulatory requirements";
    case "Minimal":
      return "few or no regulatory requirements";
    default:
      return "Unknown";
  }
}