All files / middlewares transaction-logger.ts

85.57% Statements 178/208
62.85% Branches 22/35
75% Functions 3/4
85.57% Lines 178/208

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 2091x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 5x 1x 1x 4x 4x 4x 4x 5x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 24x 24x 24x     12x 12x 24x 17x 5x 17x 12x 12x 17x 12x 12x 5x 5x 12x 12x 12x             12x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 48x 48x 48x 4x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x               4x 5x 5x 5x 5x 7x 1x 1x                                
import { ElasticLogger } from '../logger'
import { LogTransaction } from '../logger/types'
import { Request, Response, NextFunction } from 'express'
import crypto from 'crypto'
 
declare global {
  namespace Express {
    interface Request {
      transactionId?: string
    }
  }
}
 
export const transactionLoggerMiddleware = (
  microservice: string,
  operation: string,
  elasticLogger: ElasticLogger | null
) => {
  return (req: Request, res: Response, next: NextFunction) => {
    if (!elasticLogger) {
      return next()
    }
 
    const startTime = Date.now()
    const transactionId =
      (req.headers['x-transaction-id'] as string) ||
      (req.headers['x-request-id'] as string) ||
      `tx_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`
 
    req.transactionId = transactionId
 
    const SENSITIVE_KEYS = new Set<string>([
      'password',
      'newPassword',
      'token',
      'secret',
      'authorization',
      'cpf',
      'ssn',
      'creditCard',
      'cvv',
      'pin',
    ])
 
    const sanitize = (value: unknown, depth = 0): unknown => {
      if (depth > 6) return '[DEPTH_LIMIT]'
      if (value === null || typeof value !== 'object') return value
      if (Array.isArray(value)) {
        return value.slice(0, 100).map((v) => sanitize(v, depth + 1))
      }
      const obj = value as Record<string, unknown>
      const out: Record<string, unknown> = {}
      for (const [k, v] of Object.entries(obj)) {
        if (SENSITIVE_KEYS.has(k)) {
          out[k] = '[REDACTED]'
        } else {
          out[k] = sanitize(v, depth + 1)
        }
      }
      return out
    }
 
    const toLimitedJson = (obj: unknown, maxBytes = 64 * 1024): string => {
      try {
        const s = JSON.stringify(obj)
        if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s
        const preview = s.slice(0, maxBytes)
        const hash = crypto.createHash('sha256').update(s).digest('hex')
        return `${preview}...[TRUNCATED:${hash}]`
      } catch {
        return '[UNSERIALIZABLE]'
      }
    }
 
    const requestMeta = {
      method: req.method,
      path: req.originalUrl,
      baseUrl: req.baseUrl,
      route: (req as { route?: { path?: string } }).route?.path,
      host: req.get('host'),
      referrer: req.get('referer') || req.get('referrer'),
      ip: req.ip || req.socket.remoteAddress,
      xForwardedFor: req.get('x-forwarded-for'),
      userAgent: req.get('User-Agent'),
      httpVersion: req.httpVersion,
    }
 
    const relevantHeaders = [
      'x-user-id',
      'x-appointment-id',
      'x-platform',
      'x-tenant-id',
      'x-locale',
      'x-correlation-id',
      'x-trace-id',
      'x-parent-span-id',
      'x-span-id',
      'authorization',
      'content-type',
      'accept',
    ]
 
    const headerContext: Record<string, unknown> = {}
    for (const h of relevantHeaders) {
      const v = req.get(h)
      if (v) headerContext[h] = h === 'authorization' ? '[REDACTED]' : v
    }
 
    const paramsSan = sanitize(req.params || {})
    const querySan = sanitize(req.query || {})
    const bodySan = typeof req.body === 'object' ? sanitize(req.body) : req.body
 
    const requestPayload = {
      params: paramsSan,
      query: querySan,
      body: bodySan,
      paramsStr: toLimitedJson(paramsSan),
      queryStr: toLimitedJson(querySan),
      bodyStr: toLimitedJson(bodySan),
      contentLength: req.get('content-length'),
    }
 
    res.once('finish', () => {
      const duration = Date.now() - startTime
      const status = res.statusCode >= 400 ? 'fail' : 'success'
 
      const resContentLengthHeader = res.getHeader('content-length')
      const responseSizeValue =
        typeof resContentLengthHeader === 'string'
          ? parseInt(resContentLengthHeader, 10)
          : typeof resContentLengthHeader === 'number'
            ? resContentLengthHeader
            : undefined
      const responseMeta: {
        statusCode: number
        data?: unknown
        responseSize?: number
      } = {
        statusCode: res.statusCode,
        ...(typeof responseSizeValue === 'number'
          ? { responseSize: responseSizeValue }
          : {}),
      }
 
      const context: Record<string, unknown> = {
        ...headerContext,
        ...requestPayload,
        trace: {
          requestId: req.headers['x-request-id'],
          transactionId,
          traceId: req.headers['x-trace-id'],
          parentSpanId: req.headers['x-parent-span-id'],
          spanId: req.headers['x-span-id'],
        },
        env: {
          nodeEnv: process.env['NODE_ENV'],
          serviceVersion: process.env['npm_package_version'],
          podName: process.env['HOSTNAME'],
          region: process.env['AWS_REGION'] || process.env['GCP_REGION'],
        },
      }
 
      const transactionData: LogTransaction = {
        name: operation,
        microservice,
        transactionId,
        operation,
        status,
        duration,
        context,
        requestMeta,
        responseMeta,
      }
 
      setImmediate(async () => {
        try {
          await elasticLogger.logTransaction(transactionData)
        } catch (error) {
          console.error('❌ Erro ao registrar log transacional:', {
            transactionId,
            microservice,
            operation,
            error: error instanceof Error ? error.message : 'Unknown error',
          })
        }
      })
    })
 
    next()
  }
}
 
export const addTransactionId = (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  if (!req.transactionId) {
    req.transactionId =
      (req.headers['x-transaction-id'] as string) ||
      (req.headers['x-request-id'] as string) ||
      `tx_${Date.now()}_${Math.random().toString(36).slice(2, 11)}`
  }

  res.setHeader('X-Transaction-ID', req.transactionId)

  next()
}