All files / src/utils logger.js

88.23% Statements 75/85
85.96% Branches 49/57
86.66% Functions 13/15
90.54% Lines 67/74

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                1x   1x 1x                 1x 1x                               2x 2x   2x 2x 10x 3x   2x             17x 17x 17x 17x 17x 17x 17x     65x 65x             61x 61x 4x   57x 3x   54x 2x   52x       64x 64x 64x 63x 62x 61x       56x   8x       49x             49x 392x 1x     49x       37x 37x 3x   37x 37x   37x                         64x 64x 64x 61x   61x 61x 56x   49x 49x 49x 12x   37x         4x 4x               3x     4x             5x     17x                     1x  
/**
 * Central logger utility with quota protection and sanitization.
 *
 * Usage:
 *   const logger = require('./loggerInstance');
 *   logger.log({ level: 'INFO', source: 'auth', message: 'User signed in', userId: '123' });
 */
 
const crypto = require('node:crypto');
 
const VALID_LEVELS = ['DEBUG', 'INFO', 'WARN', 'ERROR', 'FATAL'];
const SENSITIVE_KEYS = new Set([
  'password',
  'token',
  'idtoken',
  'accesstoken',
  'refreshtoken',
  'secret',
  'credential',
]);
const DEFAULT_HARD_CAP = 15000;
const PASSTHROUGH_FIELDS = [
  'sessionTraceId',
  'requestTraceId',
  'userId',
  'deviceId',
  'context',
  'appVersion',
  'platform',
  'osVersion',
];
 
/**
 * Recursively remove sensitive keys from an object.
 * Returns a new object; never mutates the input.
 */
function sanitize(obj) {
  Iif (obj === null || obj === undefined || typeof obj !== 'object') return obj;
  Iif (Array.isArray(obj)) return obj.map(sanitize);
 
  const clean = {};
  for (const [key, value] of Object.entries(obj)) {
    if (SENSITIVE_KEYS.has(key.toLowerCase())) continue;
    clean[key] = typeof value === 'object' ? sanitize(value) : value;
  }
  return clean;
}
 
/**
 * Create a logger bound to a Firestore db instance.
 */
function createLogger(db) {
  let dailyCount = 0;
  let hardCap = DEFAULT_HARD_CAP;
  let currentDay = new Date().toISOString().split('T')[0];
  let consecutiveFailures = 0;
  let circuitBreakerOpenedAt = 0;
  const CIRCUIT_BREAKER_THRESHOLD = 10;
  const CIRCUIT_BREAKER_COOLDOWN = 60000; // 60 seconds
 
  function resetIfNewDay() {
    const today = new Date().toISOString().split('T')[0];
    Iif (today !== currentDay) {
      dailyCount = 0;
      currentDay = today;
    }
  }
 
  function shouldThrottle(level) {
    const ratio = dailyCount / hardCap;
    if (ratio >= 1) {
      return level !== 'ERROR' && level !== 'FATAL';
    }
    if (ratio >= 0.8) {
      return level === 'DEBUG' || level === 'INFO';
    }
    if (ratio >= 0.6) {
      return level === 'DEBUG';
    }
    return false;
  }
 
  function validateEntry(entry) {
    Iif (!entry || typeof entry !== 'object') return null;
    const { level, source, message } = entry;
    if (!level || !VALID_LEVELS.includes(level)) return null;
    if (!source || typeof source !== 'string') return null;
    if (!message || typeof message !== 'string') return null;
    return { level, source, message };
  }
 
  function isCircuitBreakerBlocking() {
    if (consecutiveFailures < CIRCUIT_BREAKER_THRESHOLD) return false;
    // Half-open: allow one probe write every 60s to check if Firestore recovered
    return Date.now() - circuitBreakerOpenedAt < CIRCUIT_BREAKER_COOLDOWN;
  }
 
  function buildLogDoc(entry, level, source, message) {
    const doc = {
      id: crypto.randomBytes(16).toString('hex'),
      timestamp: new Date().toISOString(),
      level,
      source,
      message,
    };
    for (const field of PASSTHROUGH_FIELDS) {
      if (entry[field] !== undefined) {
        doc[field] = field === 'context' ? sanitize(entry[field]) : entry[field];
      }
    }
    return doc;
  }
 
  function handleLogError(err) {
    consecutiveFailures++;
    if (consecutiveFailures >= CIRCUIT_BREAKER_THRESHOLD) {
      circuitBreakerOpenedAt = Date.now();
    }
    try {
      if (consecutiveFailures <= CIRCUIT_BREAKER_THRESHOLD) {
        // eslint-disable-next-line no-console
        console.error('[logger] Failed to write log:', err.message);
      } else Eif (consecutiveFailures === CIRCUIT_BREAKER_THRESHOLD + 1) {
        // eslint-disable-next-line no-console
        console.error(
          '[logger] Circuit breaker open — suppressing Firestore writes until next success',
        );
      }
    } catch {
      // Intentionally swallowed — error reporting must never itself throw to avoid infinite loops
    }
  }
 
  async function log(entry) {
    try {
      const validated = validateEntry(entry);
      if (!validated) return;
      const { level, source, message } = validated;
 
      resetIfNewDay();
      if (shouldThrottle(level)) return;
      if (isCircuitBreakerBlocking()) return;
 
      const doc = buildLogDoc(entry, level, source, message);
      dailyCount++;
      await db.collection('logs').doc(doc.id).set(doc);
      consecutiveFailures = 0;
    } catch (err) {
      handleLogError(err);
    }
  }
 
  function getDailyStats() {
    resetIfNewDay();
    return { count: dailyCount, hardCap };
  }
 
  // Test helpers
  function _resetDailyCount() {
    dailyCount = 0;
  }
  function _setDailyCount(n) {
    dailyCount = n;
  }
  function _setHardCap(n) {
    hardCap = n;
  }
  function _resetCircuitBreaker() {
    consecutiveFailures = 0;
    circuitBreakerOpenedAt = 0;
  }
  function _getConsecutiveFailures() {
    return consecutiveFailures;
  }
 
  return {
    log,
    getDailyStats,
    _resetDailyCount,
    _setDailyCount,
    _setHardCap,
    _resetCircuitBreaker,
    _getConsecutiveFailures,
  };
}
 
module.exports = { createLogger, sanitize, VALID_LEVELS };