// Tiny AWS audit dashboard on top of the audit.events table.
//
//   npm install pg
//   node server.mjs
//
// Config via env: DATABASE_URL (default: local docker-compose Postgres), PORT.

import { createServer } from "node:http";
import pg from "pg";

const pool = new pg.Pool({
  connectionString:
    process.env.DATABASE_URL ??
    "postgres://postgres:postgres@localhost:5432/aws",
});

// username is only set for IAM users; role sessions and federated
// identities leave it null, so fall back to the userIdentity JSON.
const ACTOR = `COALESCE(username, user_identity::jsonb ->> 'arn', 'unknown')`;

const QUERIES = {
  actors: `
    SELECT ${ACTOR} AS actor, count(*) AS changes
    FROM audit.events
    WHERE event_time > now() AT TIME ZONE 'utc' - interval '24 hours'
    GROUP BY 1
    ORDER BY changes DESC
    LIMIT 10`,
  recent: `
    SELECT event_time::text, event_name, event_source, aws_region,
           ${ACTOR} AS actor, source_ip_address, error_code
    FROM audit.events
    ORDER BY event_time DESC
    LIMIT 50`,
  errors: `
    SELECT event_time::text, event_name, ${ACTOR} AS actor,
           error_code, error_message
    FROM audit.events
    WHERE error_code IS NOT NULL
    ORDER BY event_time DESC
    LIMIT 20`,
};

const PAGE = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>AWS audit</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="max-w-5xl mx-auto my-10 px-4 text-sm text-slate-800 bg-slate-50">
<header class="flex items-baseline gap-3 mb-8">
  <h1 class="text-2xl font-semibold tracking-tight">AWS audit</h1>
  <span id="updated" class="text-xs text-slate-500"></span>
</header>
<section class="mb-8 rounded-lg border border-slate-200 bg-white shadow-sm overflow-hidden">
  <h2 class="px-4 py-2.5 text-xs font-semibold uppercase tracking-wide text-sky-800 bg-sky-50 border-b border-sky-100">Most active identities (last 24 hours)</h2>
  <table id="actors" class="w-full"></table>
</section>
<section class="mb-8 rounded-lg border border-slate-200 bg-white shadow-sm overflow-hidden">
  <h2 class="px-4 py-2.5 text-xs font-semibold uppercase tracking-wide text-emerald-800 bg-emerald-50 border-b border-emerald-100">Latest changes</h2>
  <table id="recent" class="w-full"></table>
</section>
<section class="mb-8 rounded-lg border border-slate-200 bg-white shadow-sm overflow-hidden">
  <h2 class="px-4 py-2.5 text-xs font-semibold uppercase tracking-wide text-rose-800 bg-rose-50 border-b border-rose-100">Errors</h2>
  <table id="errors" class="w-full"></table>
</section>
<script>
const CELL = "text-left align-top px-4 py-1.5";
const NOWRAP = new Set(["event_source", "aws_region"]);
async function load(name) {
  const table = document.getElementById(name);
  let rows;
  try {
    const response = await fetch("/api/" + name);
    rows = await response.json();
    if (!response.ok) throw new Error(rows.error ?? response.statusText);
  } catch (error) {
    table.innerHTML = "";
    table.insertRow().insertCell().className = CELL + " text-rose-700";
    table.rows[0].cells[0].textContent = "query failed: " + error.message;
    return;
  }
  table.textContent = "";
  if (rows.length === 0) {
    table.insertRow().insertCell().className = CELL + " text-slate-400 italic";
    table.rows[0].cells[0].textContent = "no rows yet";
    return;
  }
  const cols = Object.keys(rows[0]);
  const header = table.createTHead().insertRow();
  header.className = "bg-slate-50 border-b border-slate-200";
  for (const col of cols) {
    const th = document.createElement("th");
    th.className = CELL + " text-xs font-medium text-slate-500";
    th.textContent = col;
    header.appendChild(th);
  }
  const body = table.createTBody();
  for (const row of rows) {
    const tr = body.insertRow();
    tr.className = "border-b border-slate-100 last:border-0 hover:bg-slate-50";
    for (const col of cols) {
      const td = tr.insertCell();
      td.className = CELL + (NOWRAP.has(col) ? " whitespace-nowrap" : " break-all")
        + (col.startsWith("error") ? " text-rose-700" : "")
        + (col === "changes" ? " tabular-nums" : "");
      td.textContent = row[col] === null ? "" : String(row[col]);
    }
  }
}
function refresh() {
  for (const name of ["actors", "recent", "errors"]) load(name);
  document.getElementById("updated").textContent =
    "as of " + new Date().toLocaleTimeString();
}
refresh();
setInterval(refresh, 30000);
</script>
</body>
</html>`;

const server = createServer(async (request, response) => {
  const name = request.url.replace(/^\/api\//, "");
  if (request.url.startsWith("/api/") && Object.hasOwn(QUERIES, name)) {
    try {
      const { rows } = await pool.query(QUERIES[name]);
      response.setHeader("content-type", "application/json");
      response.end(JSON.stringify(rows));
    } catch (error) {
      response.statusCode = 500;
      response.end(JSON.stringify({ error: error.message }));
    }
    return;
  }
  response.setHeader("content-type", "text/html; charset=utf-8");
  response.end(PAGE);
});

const port = process.env.PORT ?? 8080;
server.listen(port, () => {
  console.log(`audit dashboard on http://localhost:${port}`);
});
