All files / src/lib/monitoring sanitize.ts

98.36% Statements 180/183
86.66% Branches 26/30
100% Functions 3/3
98.36% Lines 180/183

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 1841x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 126x 126x 50x 50x 76x 76x 76x 126x 1596x 1596x 76x 76x 76x 1x 1x 1x 1x 1x 1x 1x 13x 13x 13x 13x     13x 13x 13x 13x 21x 21x 21x 21x 9x 9x 9x 12x 12x 21x 3x 3x 3x 9x 9x 21x 1x 1x 1x 8x 8x 21x 2x 2x 2x 6x 6x 21x 2x 4x 2x 2x 4x 2x 2x   2x 2x 2x 4x 4x 4x 4x 13x 13x 13x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x  
/**
 * Data Sanitization for Error Monitoring
 *
 * Redacts sensitive information from error data before storage.
 * Prevents accidental PII or credential exposure in error logs.
 */
 
/**
 * Patterns that indicate sensitive data
 * Order matters - more specific patterns should come first
 */
const SENSITIVE_PATTERNS: Array<{ pattern: RegExp; replacement: string }> = [
  // Authorization headers
  { pattern: /Bearer\s+[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+\.[A-Za-z0-9\-_]+/gi, replacement: 'Bearer [JWT_REDACTED]' },
  { pattern: /Bearer\s+\S+/gi, replacement: 'Bearer [TOKEN_REDACTED]' },
  { pattern: /Basic\s+[A-Za-z0-9+/=]+/gi, replacement: 'Basic [CREDENTIALS_REDACTED]' },
 
  // API keys and tokens (common patterns)
  { pattern: /api[_-]?key[=:]["']?\s*[A-Za-z0-9\-_]{16,}/gi, replacement: 'api_key=[KEY_REDACTED]' },
  { pattern: /secret[_-]?key[=:]["']?\s*[A-Za-z0-9\-_]{16,}/gi, replacement: 'secret_key=[KEY_REDACTED]' },
  { pattern: /access[_-]?token[=:]["']?\s*[A-Za-z0-9\-_]{16,}/gi, replacement: 'access_token=[TOKEN_REDACTED]' },
  { pattern: /refresh[_-]?token[=:]["']?\s*[A-Za-z0-9\-_]{16,}/gi, replacement: 'refresh_token=[TOKEN_REDACTED]' },
 
  // Passwords
  { pattern: /password[=:]["']?\s*\S+/gi, replacement: 'password=[PASSWORD_REDACTED]' },
  { pattern: /passwd[=:]["']?\s*\S+/gi, replacement: 'passwd=[PASSWORD_REDACTED]' },
  { pattern: /pwd[=:]["']?\s*\S+/gi, replacement: 'pwd=[PASSWORD_REDACTED]' },
 
  // Database connection strings
  { pattern: /mysql:\/\/[^@]+@[^\s]+/gi, replacement: 'mysql://[DB_REDACTED]' },
  { pattern: /postgres:\/\/[^@]+@[^\s]+/gi, replacement: 'postgres://[DB_REDACTED]' },
  { pattern: /mongodb:\/\/[^@]+@[^\s]+/gi, replacement: 'mongodb://[DB_REDACTED]' },
  { pattern: /redis:\/\/[^@]+@[^\s]+/gi, replacement: 'redis://[DB_REDACTED]' },
 
  // Credit card numbers (simple pattern)
  { pattern: /\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g, replacement: '[CARD_REDACTED]' },
 
  // SSN pattern
  { pattern: /\b\d{3}[-]?\d{2}[-]?\d{4}\b/g, replacement: '[SSN_REDACTED]' },
 
  // Email addresses
  { pattern: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g, replacement: '[EMAIL_REDACTED]' },
 
  // Phone numbers (various formats)
  { pattern: /\b\+?1?[-.\s]?\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}\b/g, replacement: '[PHONE_REDACTED]' },
 
  // IP addresses (IPv4)
  { pattern: /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g, replacement: '[IP_REDACTED]' },
 
  // AWS keys
  { pattern: /AKIA[0-9A-Z]{16}/g, replacement: '[AWS_KEY_REDACTED]' },
 
  // Private keys
  { pattern: /-----BEGIN\s+(?:RSA\s+)?PRIVATE\s+KEY-----[\s\S]*?-----END\s+(?:RSA\s+)?PRIVATE\s+KEY-----/g, replacement: '[PRIVATE_KEY_REDACTED]' },
];
 
/**
 * Keys in metadata that should be completely redacted
 */
const SENSITIVE_KEYS = new Set([
  'password',
  'passwd',
  'pwd',
  'secret',
  'token',
  'apikey',
  'api_key',
  'apiKey',
  'auth',
  'authorization',
  'credential',
  'credentials',
  'private',
  'privateKey',
  'private_key',
  'ssn',
  'creditcard',
  'credit_card',
  'cardnumber',
  'card_number',
  'cvv',
  'cvc',
]);
 
/**
 * Sanitize a string by redacting sensitive patterns
 *
 * @param data - String to sanitize
 * @returns Sanitized string with sensitive data redacted
 */
export function sanitizeErrorData(data: string): string {
  if (!data || typeof data !== 'string') {
    return data;
  }
 
  let sanitized = data;
 
  for (const { pattern, replacement } of SENSITIVE_PATTERNS) {
    sanitized = sanitized.replace(pattern, replacement);
  }
 
  return sanitized;
}
 
/**
 * Sanitize metadata object by redacting sensitive keys and values
 *
 * @param metadata - Metadata object to sanitize
 * @returns Sanitized metadata with sensitive data redacted
 */
export function sanitizeMetadata(
  metadata: Record<string, unknown>
): Record<string, unknown> {
  if (!metadata || typeof metadata !== 'object') {
    return metadata;
  }
 
  const sanitized: Record<string, unknown> = {};
 
  for (const [key, value] of Object.entries(metadata)) {
    const lowerKey = key.toLowerCase();
 
    // Completely redact sensitive keys
    if (SENSITIVE_KEYS.has(lowerKey)) {
      sanitized[key] = '[REDACTED]';
      continue;
    }
 
    // Check for partial matches in key name
    if (/password|token|secret|key|auth|credential|private/i.test(key)) {
      sanitized[key] = '[REDACTED]';
      continue;
    }
 
    // Recursively sanitize nested objects
    if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
      sanitized[key] = sanitizeMetadata(value as Record<string, unknown>);
      continue;
    }
 
    // Sanitize string values
    if (typeof value === 'string') {
      sanitized[key] = sanitizeErrorData(value);
      continue;
    }
 
    // Sanitize arrays
    if (Array.isArray(value)) {
      sanitized[key] = value.map((item) => {
        if (typeof item === 'string') {
          return sanitizeErrorData(item);
        }
        if (item !== null && typeof item === 'object') {
          return sanitizeMetadata(item as Record<string, unknown>);
        }
        return item;
      });
      continue;
    }
 
    // Pass through other values unchanged
    sanitized[key] = value;
  }
 
  return sanitized;
}
 
/**
 * Sanitize a complete error object
 *
 * @param error - Error object with message, stack, and metadata
 * @returns Sanitized error object
 */
export function sanitizeError<T extends { message?: string; stack?: string; metadata?: Record<string, unknown> }>(
  error: T
): T {
  return {
    ...error,
    message: error.message ? sanitizeErrorData(error.message) : error.message,
    stack: error.stack ? sanitizeErrorData(error.stack) : error.stack,
    metadata: error.metadata ? sanitizeMetadata(error.metadata) : error.metadata,
  };
}