import { CallHandler, ExecutionContext, Injectable, NestInterceptor, } from "@nestjs/common"; import type { Request, Response } from "express"; import { Observable, tap } from "rxjs"; import { createAppLogger } from "../common/app-logger"; export function redactAuthRequestBody(path: string, body: unknown): unknown { const normalizedPath = path.toLowerCase().replace(/\/+$/, ""); if ( (normalizedPath !== "/auth/login" && normalizedPath !== "/api/v1/auth/login") || !body || typeof body !== "object" || Array.isArray(body) ) { return body; } const requestBody = body as Record; return { ...requestBody, password: requestBody.password ? "[REDACTED]" : requestBody.password, }; } @Injectable() export class LoggingInterceptor implements NestInterceptor { private readonly logger = createAppLogger(LoggingInterceptor.name); intercept(context: ExecutionContext, next: CallHandler): Observable { const http = context.switchToHttp(); const req = http.getRequest(); const res = http.getResponse(); const { method, url, body } = req; const start = Date.now(); const safeBody = redactAuthRequestBody(req.path, body); const bodyStr = safeBody && Object.keys(safeBody).length ? ` ${JSON.stringify(safeBody)}` : ""; this.logger.debug(`→ ${method} ${url}${bodyStr}`); return next.handle().pipe( tap((responseBody) => { const ms = Date.now() - start; const len = responseBody != null ? JSON.stringify(responseBody).length : 0; const lenStr = len > 0 ? ` [${len}b]` : ""; this.logger.debug( `← ${method} ${url} ${res.statusCode} (${ms}ms)${lenStr}`, ); }), ); } }