Files
coredns-web-ui/static/js/audit.js
T
bryanpedini 440f78ce9e
Test / test (push) Successful in 26m44s
Build and publish image / image (push) Successful in 27m27s
feat(ui): improve the records table, view state and record dialog
Sortable record columns, filters and sort kept in the URL on the zones,
zone and audit pages, a Show action that filters the records table to a
problem's owner, Save and add another, a highlight of the saved row, an
Audit history link on the zone page, and dialogs that keep typed input
on a backdrop click.
2026-11-22 17:36:46 +01:00

284 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
import { $, api, busy, formatTime, h, handleError, icon, readQuery, writeQuery } from "./common.js";
import { FIELD_SPECS } from "./records.js";
const state = { nextBeforeId: null, count: 0, filters: {}, counter: 0, generation: 0 };
const SOA_FIELDS = [
{ key: "ns", label: "Primary name server" },
{ key: "MBox", label: "Hostmaster" },
{ key: "serial", label: "Serial" },
{ key: "refresh", label: "Refresh" },
{ key: "retry", label: "Retry" },
{ key: "expire", label: "Expire" },
{ key: "minttl", label: "Minimum TTL" },
];
function isObject(value) {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
function isRecord(value) {
return isObject(value) && Object.hasOwn(value, "id") && typeof value.record_type === "string";
}
function flatten(value, prefix, out) {
if (Array.isArray(value)) {
value.forEach((item, index) => flatten(item, prefix + "[" + index + "]", out));
} else if (value !== null && typeof value === "object") {
for (const [key, item] of Object.entries(value)) flatten(item, prefix ? prefix + "." + key : key, out);
} else {
out.set(prefix, value);
}
return out;
}
function show(value) {
if (value === undefined) return "(none)";
if (typeof value === "string" && value !== "") {
return value.replaceAll("\r", "\\r").replaceAll("\n", "\\n").replaceAll("\t", "\\t");
}
return JSON.stringify(value);
}
function itemLabel(item, index) {
if (isRecord(item)) return "record " + item.id;
if (isObject(item)) {
if ("zone" in item && "username" in item && !("id" in item)) return "delegation " + item.zone + " " + item.username;
if ("username" in item && "id" in item) return "user " + item.id;
}
return "[" + index + "]";
}
function keyed(value) {
const out = new Map();
const items = Array.isArray(value) ? value : value === null || value === undefined ? [] : [value];
items.forEach((item, index) => out.set(itemLabel(item, index), item));
return out;
}
function compareFields(left, right) {
const paths = [...new Set([...left.keys(), ...right.keys()])];
return paths.map((path) => {
const old = left.get(path);
const now = right.get(path);
let kind = "same";
if (!left.has(path)) kind = "added";
else if (!right.has(path)) kind = "removed";
else if (JSON.stringify(old) !== JSON.stringify(now)) kind = "changed";
return { path, kind, before: old, after: now };
});
}
function recordFields(value) {
if (!isRecord(value)) return value;
const { record_type, content, ...fields } = value;
return { ...fields, type: record_type };
}
function contentFields(record) {
const fields = new Map();
const labels = new Map();
if (!isRecord(record) || !Object.hasOwn(record, "content")) return { fields, labels };
let content = record.content;
if (typeof content === "string") {
try {
content = JSON.parse(content);
} catch {
// Unparseable records keep their original text in the audit.
}
}
if (!isObject(content) || Object.keys(content).length === 0) {
fields.set("", content);
return { fields, labels };
}
const type = record.record_type.toUpperCase();
if (type === "SOA" && !Object.hasOwn(content, "MBox") && Object.hasOwn(content, "mbox")) {
const { mbox, ...rest } = content;
content = { ...rest, MBox: mbox };
}
const specs = type === "SOA" ? SOA_FIELDS : Object.hasOwn(FIELD_SPECS, type) ? FIELD_SPECS[type] : [];
for (const { key, label } of specs) {
labels.set(key, label);
if (Object.hasOwn(content, key)) fields.set(key, content[key]);
}
for (const key of Object.keys(content).sort()) {
if (!fields.has(key)) fields.set(key, content[key]);
}
return { fields, labels };
}
function diffValues(before, after, prefix) {
const left = before == null ? new Map() : flatten(recordFields(before), prefix, new Map());
const right = after == null ? new Map() : flatten(recordFields(after), prefix, new Map());
const rows = compareFields(left, right).filter(({ path }) => path !== "");
if (isRecord(before) || isRecord(after)) {
const oldContent = contentFields(before);
const newContent = contentFields(after);
const fields = compareFields(oldContent.fields, newContent.fields);
if (fields.length !== 0) {
// Put changed fields first so they are visible before horizontal scrolling.
fields.sort((a, b) => Number(a.kind === "same") - Number(b.kind === "same"));
rows.push({
path: prefix ? prefix + ".content" : "content",
kind: fields[0].kind === "same" ? "same" : "changed",
fields,
beforeLabels: oldContent.labels,
afterLabels: newContent.labels,
});
}
}
return rows;
}
export function diffRows(before, after) {
if (!Array.isArray(before) && !Array.isArray(after)) {
return diffValues(before, after, "");
}
const left = keyed(before);
const right = keyed(after);
const labels = [...new Set([...left.keys(), ...right.keys()])];
return labels.flatMap((label) => diffValues(left.has(label) ? left.get(label) : undefined, right.has(label) ? right.get(label) : undefined, label));
}
function diffValue(value, kind, side, label = "") {
const changed = value !== undefined && kind !== "same";
const color = changed ? " diff-" + side : "";
return h("code", { class: "diff-value" + color },
changed ? h("span", { "aria-hidden": "true", text: side === "before" ? "− " : "+ " }) : null,
label ? h("strong", { text: label + ": " }) : null,
show(value));
}
function diffCell(row, side) {
if (!row.fields) return h("td", null, diffValue(row[side], row.kind, side));
const labels = side === "before" ? row.beforeLabels : row.afterLabels;
const parts = row.fields.filter((field) => field[side] !== undefined);
return h("td", null,
h("div", { class: "diff-content", role: "group", "aria-label": side === "before" ? "Before content" : "After content" },
parts.length ? parts.map((field) => diffValue(field[side], field.kind, side, labels.get(field.path) ?? field.path)) : show(undefined)));
}
function diffTable(entry) {
const rows = diffRows(entry.before, entry.after);
if (rows.length === 0) return h("p", { class: "muted", text: "No field-level data." });
return h("div", { class: "table-wrap" }, h("table", { class: "table diff" },
h("thead", null, h("tr", null, h("th", { scope: "col", text: "Field" }), h("th", { scope: "col", text: "Before" }), h("th", { scope: "col", text: "After" }))),
h("tbody", null, rows.map((row) => h("tr", { class: "diff-" + row.kind + (row.fields ? " diff-content-row" : "") },
h("th", { scope: "row", class: "mono", text: row.path }),
diffCell(row, "before"),
diffCell(row, "after"))))));
}
function entryRows(entry) {
state.counter += 1;
const detailId = "audit-detail-" + state.counter;
const hasDiff = entry.before !== null && entry.before !== undefined || entry.after !== null && entry.after !== undefined;
const target = [];
if (entry.zone) target.push(entry.zone);
if (entry.record_id !== null && entry.record_id !== undefined) target.push("record " + entry.record_id);
if (entry.target_user) target.push("user " + entry.target_user);
const failed = typeof entry.status === "number" && entry.status >= 400;
const detail = h("tr", { class: "detail-row", id: detailId, hidden: true }, h("td", { colspan: 7 }));
const toggle = h("button", {
type: "button",
class: "btn btn-small",
"aria-expanded": "false",
"aria-controls": detailId,
onclick: () => {
const open = toggle.getAttribute("aria-expanded") !== "true";
toggle.setAttribute("aria-expanded", String(open));
detail.hidden = !open;
if (open && detail.firstChild.childNodes.length === 0) detail.firstChild.append(diffTable(entry));
},
}, icon("chevron"), " Changes");
const row = h("tr", { class: failed ? "row-error" : null },
h("td", { class: "mono", text: formatTime(entry.time) }),
h("td", { text: entry.actor }),
h("td", { class: "mono", text: entry.origin }),
h("td", { class: "mono", text: entry.operation }),
h("td", null,
entry.status === null || entry.status === undefined ? "-" : h("span", { class: "badge " + (failed ? "badge-error" : "badge-ok"), text: String(entry.status) }),
entry.error ? h("div", { class: "muted", text: entry.error }) : null),
h("td", { text: target.length ? target.join(", ") : "-" }),
h("td", null, hasDiff ? toggle : "-"));
return [row, detail];
}
async function load(append) {
const body = $("#audit-body");
const status = $("#audit-status");
const query = { ...state.filters };
if (append && state.nextBeforeId !== null) query.before_id = state.nextBeforeId;
if (append && state.nextBeforeId === null) return;
if (!append) {
state.generation += 1;
$("#audit-more").hidden = true;
}
const generation = state.generation;
if (!append) {
body.replaceChildren();
state.count = 0;
status.textContent = "Loading...";
}
try {
const { data } = await api("GET", "/audit", { query });
if (generation !== state.generation) return;
const entries = data.entries || [];
for (const entry of entries) body.append(...entryRows(entry));
state.count += entries.length;
state.nextBeforeId = data.next_before_id === undefined ? null : data.next_before_id;
status.textContent = state.count === 0 ? "No audit rows match." : state.count + " rows shown.";
$("#audit-more").hidden = state.nextBeforeId === null;
} catch (err) {
if (generation !== state.generation) return;
status.textContent = "The audit could not be loaded.";
handleError(err);
}
}
const FILTERS = ["zone", "actor", "operation", "kind", "outcome"];
function prefill() {
const form = $("#audit-filters");
const query = readQuery();
for (const name of FILTERS) {
const value = query.get(name);
if (!value) continue;
const control = form.elements[name];
if (control.tagName === "SELECT" && ![...control.options].some((item) => item.value === value)) continue;
control.value = value;
}
}
function readFilters() {
const form = $("#audit-filters");
const filters = {};
for (const name of FILTERS) {
const value = form.elements[name].value.trim();
if (value) filters[name] = value;
}
return filters;
}
$("#audit-filters").addEventListener("submit", (event) => {
event.preventDefault();
state.filters = readFilters();
state.nextBeforeId = null;
writeQuery(state.filters);
load(false);
});
$("#audit-filters").addEventListener("reset", () => {
setTimeout(() => {
state.filters = {};
state.nextBeforeId = null;
writeQuery({});
load(false);
}, 0);
});
$("#audit-more").addEventListener("click", (event) => busy(event.target, () => load(true)));
prefill();
state.filters = readFilters();
load(false);