import { CallHandler, ExecutionContext, Injectable, NestInterceptor } from '@nestjs/common'; import { Request } from 'express'; import { Observable, throwError } from 'rxjs'; import { catchError, tap } from 'rxjs/operators'; import { AuthUser } from '../common/decorators/current-user.decorator'; import { OperationLogService } from './operation-log.service'; const SENSITIVE_KEYS = new Set(['password', 'oldPassword', 'newPassword', 'token', 'authorization']); function sanitize(value: unknown, depth = 0): unknown { if (depth > 3) return '[Truncated]'; if (value === null || value === undefined) return value; if (typeof value !== 'object') return value; if (Array.isArray(value)) return value.slice(0, 20).map((item) => sanitize(item, depth + 1)); const out: Record = {}; for (const [key, val] of Object.entries(value as Record)) { if (SENSITIVE_KEYS.has(key)) { out[key] = '[Redacted]'; } else if (typeof val === 'string' && val.length > 300) { out[key] = `${val.slice(0, 300)}...`; } else { out[key] = sanitize(val, depth + 1); } } return out; } function pathSegments(path: string): string[] { return path .split('?')[0] .replace(/^\/api\/?/, '') .split('/') .filter(Boolean); } export function moduleOf(path: string): string { const segments = pathSegments(path); if (segments.includes('certificates')) return 'certificates'; if (segments.includes('nodes')) return 'nodes'; return segments[0] || 'root'; } export function actionOf(method: string, path: string): string { const segments = pathSegments(path); const [resource, second, third] = segments; const last = segments[segments.length - 1] || ''; if (resource === 'auth' && segments.includes('login')) return 'login'; if (resource === 'auth' && segments.includes('change-password')) return 'update'; if (resource === 'backups') { if (method === 'POST' && segments.length === 1) return 'backup'; if (second === 'restore' && third === 'preview') return 'upload'; if (second === 'restore' && third === 'commit') return 'restore'; if (last === 'download') return 'download'; } if (resource === 'trace-codes' && second === 'batch' && third === 'delete') return 'delete'; if (resource === 'outbound') { if (second === 'import') return 'upload'; if (second === 'import-sessions' && last === 'commit') return 'update'; } if (resource === 'storage' && ['test', 'migrate', 'confirm'].includes(second || '')) return 'update'; if (segments.includes('export')) return 'export'; if (segments.includes('download') || last === 'template') return 'download'; if (segments.includes('upload')) return 'upload'; if (segments.includes('audit')) return 'audit'; if (resource === 'blockchain-proofs' && ['retry', 'confirm'].includes(last)) return 'onchain'; if (segments.includes('onchain')) return 'onchain'; if (method === 'POST') return 'create'; if (method === 'PUT' || method === 'PATCH') return 'update'; if (method === 'DELETE') return 'delete'; return method.toLowerCase(); } function shouldLog(method: string, path: string): boolean { if (path.includes('/operation-logs')) return false; if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) return true; return path.includes('/export') || path.includes('/download'); } @Injectable() export class OperationLogInterceptor implements NestInterceptor { constructor(private readonly logs: OperationLogService) {} intercept(context: ExecutionContext, next: CallHandler): Observable { const req = context.switchToHttp().getRequest(); const method = req.method.toUpperCase(); const path = req.originalUrl || req.url; if (!shouldLog(method, path)) return next.handle(); const started = Date.now(); const user = req.user; const base = { userId: user?.id ?? null, username: user?.username ?? (req.body as any)?.username ?? null, role: user?.role ?? null, module: moduleOf(path), action: actionOf(method, path), method, path, targetId: String(req.params?.id ?? req.params?.shortCode ?? ''), ip: (req.headers['x-forwarded-for'] as string)?.split(',')[0]?.trim() || req.ip, userAgent: req.headers['user-agent'] || null, requestSummary: sanitize({ params: req.params, query: req.query, body: req.body }) as any, }; return next.handle().pipe( tap(() => { void this.logs.create({ ...base, status: 'SUCCESS', durationMs: Date.now() - started, }); }), catchError((err) => { void this.logs.create({ ...base, status: 'FAILED', message: (err as Error)?.message || String(err), durationMs: Date.now() - started, }); return throwError(() => err); }), ); } }