feat: marca Uriel Jareth Consulting, API segura para agentes, aprobacion humana y webhooks HMAC

This commit is contained in:
urieljareth
2026-11-25 00:55:18 -06:00
parent 75180b0fe4
commit 0d4f19f35d
111 changed files with 7167 additions and 1272 deletions
+248
View File
@@ -0,0 +1,248 @@
/**
* Provisioning CLI de claves de agente (AgentApiKey) para Uriel Jareth Consulting.
*
* Uso dentro del contenedor web o en local con variables DB_* cargadas:
* npx tsx scripts/provision-agent-keys.ts --list
* npx tsx scripts/provision-agent-keys.ts --nombre sales-agent --scopes catalogo:leer,clientes:leer,clientes:escribir,cotizaciones:leer,cotizaciones:borrador,cotizaciones:enviar --rate-limit 60
* npx tsx scripts/provision-agent-keys.ts --nombre sales-agent --rotate
* npx tsx scripts/provision-agent-keys.ts --preset [--rotate]
*
* Imprime JSON limpio en stdout para que un operador/orquestador guarde las
* claves directamente en accesos/cotizador.env sin exponerlas en logs.
*/
import { createHash, randomBytes } from "node:crypto";
import { PrismaClient } from "../src/generated/prisma/client";
import { PrismaPg } from "@prisma/adapter-pg";
const VALID_SCOPES = new Set([
"catalogo:leer",
"clientes:leer",
"clientes:escribir",
"cotizaciones:leer",
"cotizaciones:leer_aceptadas",
"cotizaciones:borrador",
"cotizaciones:enviar",
"cobros:leer",
"cobros:registrar",
]);
const PRESETS: Array<{ nombre: string; scopes: string[]; rateLimitPerMin: number }> = [
{
nombre: "sales-agent",
scopes: [
"catalogo:leer",
"clientes:leer",
"clientes:escribir",
"cotizaciones:leer",
"cotizaciones:borrador",
"cotizaciones:enviar",
],
rateLimitPerMin: 60,
},
{
nombre: "jefe-operaciones",
scopes: [
"catalogo:leer",
"clientes:leer",
"cotizaciones:leer",
"cobros:leer",
],
rateLimitPerMin: 120,
},
{
nombre: "cobranza",
scopes: [
"clientes:leer",
"cobros:leer",
],
rateLimitPerMin: 60,
},
{
nombre: "entrega",
scopes: [
"clientes:leer",
"cotizaciones:leer_aceptadas",
],
rateLimitPerMin: 60,
},
{
nombre: "n8n-ecosystem",
scopes: [
"catalogo:leer",
"clientes:leer",
"cotizaciones:leer",
"cotizaciones:enviar",
"cobros:leer",
],
rateLimitPerMin: 180,
},
];
function generateKey() {
const rawKey = `ujc_live_${randomBytes(32).toString("hex")}`;
const prefijo = rawKey.slice(0, 14);
const keyHash = createHash("sha256").update(rawKey, "utf8").digest("hex");
return { rawKey, prefijo, keyHash };
}
function parseArgs(argv: string[]) {
const args: Record<string, string | boolean> = {};
for (let i = 0; i < argv.length; i++) {
const token = argv[i];
if (!token.startsWith("--")) continue;
const key = token.slice(2);
const next = argv[i + 1];
if (!next || next.startsWith("--")) {
args[key] = true;
} else {
args[key] = next;
i++;
}
}
return args;
}
async function main() {
const args = parseArgs(process.argv.slice(2));
const adapter = new PrismaPg({
host: process.env.DB_HOST || "localhost",
port: parseInt(process.env.DB_PORT || "5432", 10),
user: process.env.DB_USER || "postgres",
password: process.env.DB_PASSWORD || "postgres",
database: process.env.DB_DATABASE || process.env.DB_NAME || "cotizador_e3",
});
const prisma = new PrismaClient({ adapter });
try {
if (args.list) {
const keys = await prisma.agentApiKey.findMany({
orderBy: { createdAt: "asc" },
select: {
id: true,
nombre: true,
prefijo: true,
scopes: true,
rateLimitPerMin: true,
activo: true,
revokedAt: true,
lastUsedAt: true,
createdAt: true,
},
});
console.log(JSON.stringify({ ok: true, keys }, null, 2));
return;
}
const targets: Array<{ nombre: string; scopes: string[]; rateLimitPerMin: number }> = [];
if (args.preset) {
targets.push(...PRESETS);
} else if (typeof args.nombre === "string" && args.nombre.trim()) {
const nombre = args.nombre.trim();
const rawScopes =
typeof args.scopes === "string"
? args.scopes
.split(",")
.map((s) => s.trim())
.filter(Boolean)
: [];
const rateLimitPerMin =
typeof args["rate-limit"] === "string" ? parseInt(args["rate-limit"], 10) || 60 : 60;
for (const sc of rawScopes) {
if (!VALID_SCOPES.has(sc)) {
throw new Error(`Scope invalido: "${sc}". Validos: ${Array.from(VALID_SCOPES).join(", ")}`);
}
}
targets.push({ nombre, scopes: rawScopes, rateLimitPerMin });
} else {
console.error(
"Uso: npx tsx scripts/provision-agent-keys.ts --list | --preset [--rotate] | --nombre <nombre> --scopes <a,b> [--rate-limit 60] [--rotate]"
);
process.exit(2);
}
const rotate = Boolean(args.rotate);
const results: Array<Record<string, unknown>> = [];
for (const target of targets) {
const existing = await prisma.agentApiKey.findUnique({
where: { nombre: target.nombre },
});
if (existing && !rotate) {
results.push({
nombre: existing.nombre,
action: "exists",
id: existing.id,
prefijo: existing.prefijo,
scopes: existing.scopes,
rateLimitPerMin: existing.rateLimitPerMin,
activo: existing.activo,
});
continue;
}
const scopesFinal =
target.scopes.length > 0 ? Array.from(new Set(target.scopes)) : existing?.scopes ?? [];
if (scopesFinal.length === 0) {
throw new Error(`Debes indicar --scopes al crear la clave "${target.nombre}"`);
}
const { rawKey, prefijo, keyHash } = generateKey();
if (existing) {
const updated = await prisma.agentApiKey.update({
where: { id: existing.id },
data: {
prefijo,
keyHash,
scopes: scopesFinal,
rateLimitPerMin: target.rateLimitPerMin || existing.rateLimitPerMin,
activo: true,
revokedAt: null,
},
});
results.push({
nombre: updated.nombre,
action: "rotated",
id: updated.id,
prefijo: updated.prefijo,
scopes: updated.scopes,
rateLimitPerMin: updated.rateLimitPerMin,
rawKey,
});
} else {
const created = await prisma.agentApiKey.create({
data: {
nombre: target.nombre,
prefijo,
keyHash,
scopes: scopesFinal,
rateLimitPerMin: target.rateLimitPerMin,
activo: true,
},
});
results.push({
nombre: created.nombre,
action: "created",
id: created.id,
prefijo: created.prefijo,
scopes: created.scopes,
rateLimitPerMin: created.rateLimitPerMin,
rawKey,
});
}
}
console.log(JSON.stringify({ ok: true, results }, null, 2));
} finally {
await prisma.$disconnect();
}
}
main().catch((err) => {
console.error(JSON.stringify({ ok: false, error: err instanceof Error ? err.message : String(err) }));
process.exit(1);
});