import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { AuditEvent } from '../common/enums/audit-event.enum'; import { isUuid } from '../database/postgres.helpers'; import { AuditLog } from './schemas/audit-log.schema'; export interface AuditContext { userId?: string; actorId?: string; username?: string; ip?: string; userAgent?: string; metadata?: Record; } /** * Central audit writer — all security-sensitive actions flow through here. */ @Injectable() export class AuditService { constructor( @InjectRepository(AuditLog) private readonly auditLogs: Repository, ) {} async log(event: AuditEvent, context: AuditContext = {}): Promise { await this.auditLogs.save( this.auditLogs.create({ event, userId: isUuid(context.userId) ? context.userId : null, actorId: isUuid(context.actorId) ? context.actorId : null, username: context.username, ip: context.ip, userAgent: context.userAgent, metadata: context.metadata ?? {}, }), ); } }