feat: marca Uriel Jareth Consulting, API segura para agentes, aprobacion humana y webhooks HMAC
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
import type { NextRequest } from "next/server";
|
||||
import type { Prisma } from "@/generated/prisma/client";
|
||||
import { prisma } from "@/lib/db";
|
||||
import type { ActorContext } from "@/lib/agent-auth-core";
|
||||
|
||||
export type AuditActor =
|
||||
| ActorContext
|
||||
| { type: "system"; nombre?: string; id?: string };
|
||||
|
||||
export function obtenerIp(request?: NextRequest | Request | null): string | null {
|
||||
if (!request) return null;
|
||||
const xff = request.headers.get("x-forwarded-for");
|
||||
if (xff) {
|
||||
const first = xff.split(",")[0]?.trim();
|
||||
if (first) return first;
|
||||
}
|
||||
return request.headers.get("x-real-ip")?.trim() || null;
|
||||
}
|
||||
|
||||
export async function registrarAuditoria(params: {
|
||||
actor?: AuditActor | null;
|
||||
accion: string;
|
||||
recursoTipo: string;
|
||||
recursoId?: string | null;
|
||||
request?: NextRequest | Request | null;
|
||||
exito?: boolean;
|
||||
detalle?: Record<string, unknown> | null;
|
||||
}): Promise<void> {
|
||||
try {
|
||||
let actorTipo = "system";
|
||||
let actorId: string | null = null;
|
||||
let actorNombre = "system";
|
||||
|
||||
if (params.actor) {
|
||||
if (params.actor.type === "user") {
|
||||
actorTipo = "user";
|
||||
actorId = params.actor.userId;
|
||||
actorNombre = params.actor.email || params.actor.name || params.actor.userId;
|
||||
} else if (params.actor.type === "agent") {
|
||||
actorTipo = "agent";
|
||||
actorId = params.actor.keyId;
|
||||
actorNombre = params.actor.nombre;
|
||||
} else {
|
||||
actorTipo = "system";
|
||||
actorId = params.actor.id ?? null;
|
||||
actorNombre = params.actor.nombre ?? "system";
|
||||
}
|
||||
}
|
||||
|
||||
const requestId = params.request?.headers.get("x-request-id") ?? null;
|
||||
|
||||
await prisma.auditLog.create({
|
||||
data: {
|
||||
actorTipo,
|
||||
actorId,
|
||||
actorNombre,
|
||||
accion: params.accion,
|
||||
recursoTipo: params.recursoTipo,
|
||||
recursoId: params.recursoId ?? null,
|
||||
ip: obtenerIp(params.request),
|
||||
requestId,
|
||||
exito: params.exito ?? true,
|
||||
detalle: (params.detalle ?? undefined) as Prisma.InputJsonValue | undefined,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[audit] fallo al registrar AuditLog:", params.accion, err);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user