Login + ABM de operadores + audit log con UI
Backend:
- 3 migrations: system_users (citext email único, password_hash, active),
system_sessions (UUID + expires_at + revoked_at), ALTER audit_log con
actor_user_id/actor_email/actor_ip/action_path/summary y entity_id NULL.
- src/modules/auth/: usersRepo, sessionsRepo, passwords (bcrypt cost 10),
auth (login/logout), bootstrap (crea admin desde ADMIN_EMAIL/PASSWORD si
la tabla está vacía). 4 tests passwords (hash distinto cada vez, verify
rechaza, longitud mínima 8).
- middleware/requireAuth: lee cookie bot_session, busca sesión activa,
popula req.user. Whitelist: /styles, /components, /lib, /login, /, /home
y SPA paths (HTML carga sin auth, el JS gatea con /api/auth/me).
- middleware/auditWriter: registra cada POST/PUT/DELETE 2xx en audit_log
con req.user, IP, body redactado (passwords/tokens/secrets). Handlers
pueden enriquecer summary via res.locals.audit.
- routes: /api/auth/{login,logout,me} (cookie httpOnly + DB session),
/api/system-users (ABM con guards: cant_delete_self, cant_deactivate_self,
email único, password ≥ 8), /api/audit-log + /api/audit-log/actors.
- src/app.js: orden estricto — webhooks (sin auth) → auth routes (sin auth)
→ /login HTML → static → SPA HTML → requireAuth + auditWriter → API admin.
Bootstrap del primer admin se ejecuta en index.js antes de listen. Usa
ADMIN_EMAIL/ADMIN_PASSWORD/ADMIN_NAME del .env. Si no están seteados y la
tabla está vacía, warn y exit (nadie puede loguearse).
Frontend:
- /login.html + /login.js: form simple, POST a /api/auth/login con
credentials:include, redirect a ?next=... o /home. Si ya hay sesión
activa, va directo a /home.
- public/app.js gate: chequea /api/auth/me antes de initRouter; sin sesión
redirige a /login?next=<path>. window.__USER__ disponible para shell.
- ops-shell: nav agrega "Operadores" + "Actividad". Header derecha muestra
email del user + botón Salir (POST /api/auth/logout + redirect /login).
- system-users-crud: CRUD lista/form (estilo settings). Crear/editar/
cambiar password/eliminar. UI muestra badge "Vos" + bloquea eliminarse
ni desactivarse a uno mismo.
- audit-log: tabla read-only con filtros (actor, entity_type, since,
search), paginación 50, badges por acción, modal de detalles con
changes JSON. /api/audit-log/actors pobla el dropdown de operadores.
Smoke E2E: login OK + cookie set, /me 200; logout → /me 401; settings POST
genera fila en audit_log con actor_email + action_path; ABM crea/borra
operadores con guards; intentar borrarse devuelve 400 cant_delete_self.
161/161 tests verde (pre-existentes 157 + 4 passwords nuevos).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
202
public/components/audit-log.js
Normal file
202
public/components/audit-log.js
Normal file
@@ -0,0 +1,202 @@
|
||||
import { api } from "../lib/api.js";
|
||||
import { modal } from "../lib/modal.js";
|
||||
|
||||
class AuditLog extends HTMLElement {
|
||||
constructor() {
|
||||
super();
|
||||
this.attachShadow({ mode: "open" });
|
||||
this.items = [];
|
||||
this.actors = [];
|
||||
this.loading = false;
|
||||
this.filters = { actor_id: "", entity_type: "", since: "", q: "" };
|
||||
this.limit = 50;
|
||||
|
||||
this.shadowRoot.innerHTML = `
|
||||
<style>
|
||||
:host { display:block; height:100%; padding:16px 24px 24px; overflow:auto; }
|
||||
* { box-sizing:border-box; font-family: var(--font-sans); }
|
||||
.container { max-width:1400px; margin:0 auto; }
|
||||
.toolbar { display:flex; align-items:center; justify-content:space-between; gap:12px; padding:12px 4px 16px; position:sticky; top:0; background:var(--bg); border-bottom:1px solid var(--border); margin-bottom:16px; flex-wrap:wrap; z-index:5; }
|
||||
.toolbar-title { margin:0; font-size:18px; font-weight:600; }
|
||||
.filters { display:flex; gap:8px; align-items:center; flex-wrap:wrap; }
|
||||
.filters input, .filters select { padding:7px 10px; font-size:13px; border:1px solid var(--border-hi); border-radius:var(--r-md); background:var(--panel); color:var(--text); }
|
||||
.filters input:focus, .filters select:focus { outline:none; border-color:var(--accent); }
|
||||
button { cursor:pointer; background:var(--accent); color:var(--text-on-acc, #fff); border:none; border-radius:var(--r-md); padding:7px 12px; font-size:12px; font-weight:500; }
|
||||
button:hover { background:var(--accent-hover); }
|
||||
button.secondary { background:var(--panel); color:var(--text); border:1px solid var(--border-hi); }
|
||||
button.secondary:hover { border-color:var(--accent); color:var(--accent-hover); }
|
||||
|
||||
.panel { background:var(--panel); border:1px solid var(--border); border-radius:10px; overflow:hidden; }
|
||||
table { width:100%; border-collapse:collapse; font-size:13px; }
|
||||
thead th { text-align:left; padding:10px 12px; background:var(--panel-2); border-bottom:1px solid var(--border); color:var(--text-muted); font-weight:600; font-size:11px; text-transform:uppercase; letter-spacing:.4px; }
|
||||
tbody td { padding:10px 12px; border-bottom:1px solid var(--border); vertical-align:top; }
|
||||
tbody tr:last-child td { border-bottom:none; }
|
||||
tbody tr:hover { background:var(--panel-2); }
|
||||
td.ts { font-family: var(--font-mono); color:var(--text-muted); white-space:nowrap; font-size:12px; }
|
||||
td.actor { color:var(--text); }
|
||||
td.actor.system { color:var(--text-muted); font-style:italic; }
|
||||
td.path { font-family: var(--font-mono); font-size:12px; color:var(--accent-hover); white-space:nowrap; }
|
||||
td.summary { color:var(--text); }
|
||||
td.entity { color:var(--text-muted); font-size:12px; }
|
||||
td.actions { text-align:right; }
|
||||
td.actions button { padding:4px 8px; font-size:11px; background:transparent; color:var(--text-muted); border:1px solid var(--border-hi); }
|
||||
td.actions button:hover { color:var(--accent); border-color:var(--accent); background:var(--accent-soft); }
|
||||
|
||||
.empty { padding:32px; text-align:center; color:var(--text-muted); font-size:13px; }
|
||||
.footer { display:flex; justify-content:space-between; align-items:center; padding:12px; background:var(--panel-2); border-top:1px solid var(--border); font-size:12px; color:var(--text-muted); }
|
||||
|
||||
.badge-action { display:inline-block; font-size:11px; padding:2px 8px; border-radius:6px; font-weight:500; }
|
||||
.badge-action.create { background:var(--ok-soft); color:var(--ok); }
|
||||
.badge-action.update { background:var(--accent-soft); color:var(--accent-hover); }
|
||||
.badge-action.delete { background:var(--err-soft); color:var(--err); }
|
||||
.badge-action.login { background:var(--accent-soft); color:var(--accent-hover); }
|
||||
.badge-action.login_failed { background:var(--err-soft); color:var(--err); }
|
||||
.badge-action.logout { background:var(--panel-3); color:var(--text-muted); }
|
||||
</style>
|
||||
<div class="container">
|
||||
<div class="toolbar">
|
||||
<h2 class="toolbar-title">Actividad</h2>
|
||||
<div class="filters">
|
||||
<select id="fActor"><option value="">Todos los actores</option></select>
|
||||
<select id="fEntity">
|
||||
<option value="">Toda entidad</option>
|
||||
<option value="auth">auth</option>
|
||||
<option value="settings">settings</option>
|
||||
<option value="system_user">system_user</option>
|
||||
<option value="product">product</option>
|
||||
<option value="conversations">conversations</option>
|
||||
<option value="takeovers">takeovers</option>
|
||||
</select>
|
||||
<input id="fSince" type="datetime-local" />
|
||||
<input id="fSearch" type="text" placeholder="Buscar en summary..." />
|
||||
<button id="btnApply" type="button">Aplicar</button>
|
||||
<button id="btnRefresh" class="secondary" type="button">↻</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width:160px;">Fecha</th>
|
||||
<th style="width:180px;">Operador</th>
|
||||
<th style="width:100px;">Acción</th>
|
||||
<th style="width:200px;">Ruta</th>
|
||||
<th>Resumen</th>
|
||||
<th style="width:80px;"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="rows"></tbody>
|
||||
</table>
|
||||
<div class="footer" id="footer">—</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
this.shadowRoot.getElementById("btnApply").addEventListener("click", () => this.applyFilters());
|
||||
this.shadowRoot.getElementById("btnRefresh").addEventListener("click", () => this.load());
|
||||
this.shadowRoot.getElementById("fSearch").addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter") this.applyFilters();
|
||||
});
|
||||
this.loadActors();
|
||||
this.load();
|
||||
}
|
||||
|
||||
applyFilters() {
|
||||
this.filters.actor_id = this.shadowRoot.getElementById("fActor").value || "";
|
||||
this.filters.entity_type = this.shadowRoot.getElementById("fEntity").value || "";
|
||||
this.filters.since = this.shadowRoot.getElementById("fSince").value || "";
|
||||
this.filters.q = this.shadowRoot.getElementById("fSearch").value.trim();
|
||||
this.load();
|
||||
}
|
||||
|
||||
async loadActors() {
|
||||
try {
|
||||
const data = await api.auditActors();
|
||||
this.actors = data.items || [];
|
||||
const sel = this.shadowRoot.getElementById("fActor");
|
||||
const current = sel.value;
|
||||
sel.innerHTML = `<option value="">Todos los actores</option>` +
|
||||
this.actors.map((a) => `<option value="${a.id}">${this.escapeHtml(a.email)}</option>`).join("");
|
||||
sel.value = current;
|
||||
} catch {}
|
||||
}
|
||||
|
||||
async load() {
|
||||
this.loading = true;
|
||||
this.renderRows();
|
||||
try {
|
||||
const params = { limit: this.limit };
|
||||
if (this.filters.actor_id) params.actor_id = this.filters.actor_id;
|
||||
if (this.filters.entity_type) params.entity_type = this.filters.entity_type;
|
||||
if (this.filters.since) params.since = new Date(this.filters.since).toISOString();
|
||||
if (this.filters.q) params.q = this.filters.q;
|
||||
const data = await api.auditLog(params);
|
||||
this.items = data.items || [];
|
||||
this.loading = false;
|
||||
this.renderRows();
|
||||
} catch (e) {
|
||||
this.loading = false;
|
||||
this.items = [];
|
||||
this.renderRows();
|
||||
}
|
||||
}
|
||||
|
||||
renderRows() {
|
||||
const rows = this.shadowRoot.getElementById("rows");
|
||||
const footer = this.shadowRoot.getElementById("footer");
|
||||
if (this.loading) {
|
||||
rows.innerHTML = `<tr><td colspan="6" class="empty">Cargando...</td></tr>`;
|
||||
footer.textContent = "—";
|
||||
return;
|
||||
}
|
||||
if (!this.items.length) {
|
||||
rows.innerHTML = `<tr><td colspan="6" class="empty">Sin actividad para los filtros aplicados.</td></tr>`;
|
||||
footer.textContent = "0 eventos";
|
||||
return;
|
||||
}
|
||||
rows.innerHTML = this.items.map((r) => {
|
||||
const ts = new Date(r.created_at);
|
||||
const tsStr = ts.toLocaleString("es-AR", { day: "2-digit", month: "2-digit", year: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit" });
|
||||
const actor = r.actor_email || r.actor || "system";
|
||||
const actorClass = r.actor_user_id ? "" : "system";
|
||||
const actionClass = String(r.action || "").replace(/[^a-z_]/g, "");
|
||||
return `
|
||||
<tr data-id="${r.id}">
|
||||
<td class="ts">${this.escapeHtml(tsStr)}</td>
|
||||
<td class="actor ${actorClass}">${this.escapeHtml(actor)}</td>
|
||||
<td><span class="badge-action ${actionClass}">${this.escapeHtml(r.action || "—")}</span></td>
|
||||
<td class="path">${this.escapeHtml(r.action_path || "")}</td>
|
||||
<td class="summary">${this.escapeHtml(r.summary || `${r.entity_type || ""}${r.entity_id ? "#"+r.entity_id : ""}`)}</td>
|
||||
<td class="actions"><button data-action="details" data-id="${r.id}">Detalles</button></td>
|
||||
</tr>
|
||||
`;
|
||||
}).join("");
|
||||
rows.querySelectorAll('button[data-action="details"]').forEach((btn) => {
|
||||
btn.addEventListener("click", () => this.showDetails(btn.dataset.id));
|
||||
});
|
||||
footer.textContent = `${this.items.length} evento${this.items.length === 1 ? "" : "s"}${this.items.length >= this.limit ? " (mostrando últimos)" : ""}`;
|
||||
}
|
||||
|
||||
showDetails(id) {
|
||||
const r = this.items.find((x) => String(x.id) === String(id));
|
||||
if (!r) return;
|
||||
const lines = [];
|
||||
lines.push(`Fecha: ${new Date(r.created_at).toLocaleString("es-AR")}`);
|
||||
lines.push(`Operador: ${r.actor_email || r.actor || "system"}`);
|
||||
if (r.actor_ip) lines.push(`IP: ${r.actor_ip}`);
|
||||
lines.push(`Acción: ${r.action}`);
|
||||
lines.push(`Entidad: ${r.entity_type || "-"}${r.entity_id ? "#"+r.entity_id : ""}`);
|
||||
if (r.action_path) lines.push(`Ruta: ${r.action_path}`);
|
||||
if (r.summary) lines.push(`Resumen: ${r.summary}`);
|
||||
if (r.changes) lines.push("\nCambios:\n" + JSON.stringify(r.changes, null, 2));
|
||||
modal.info(lines.join("\n"));
|
||||
}
|
||||
|
||||
escapeHtml(s) {
|
||||
return String(s ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
}
|
||||
}
|
||||
|
||||
customElements.define("audit-log", AuditLog);
|
||||
Reference in New Issue
Block a user