chore(ui): add module file and main stub

- chore(ui): add module file and main stub
- feat(ui): add layout, pages and partials
- feat(ui): add stylesheet and scripts
- feat(ui): add page renderer and static file handler
- test(ui): cover rendering, escaping and static serving
This commit is contained in:
bryanpedini committed 2026-11-19 15:46:12 +01:00
1 parent 7089a6f408
commit 5ac8f98f10
26 files changed
+3921

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
import { $, api, bindPasswordForm, clear, h, handleError, toast, zoneLink } from "./common.js";
async function load() {
const list = $("#account-zones");
try {
const { data } = await api("GET", "/account");
$("#account-username").textContent = data.username;
$("#account-role").textContent = data.role;
if (list) {
const zones = data.zones || [];
clear(list);
for (const zone of zones) list.append(h("li", null, zoneLink(zone)));
$("#account-zones-status").textContent = zones.length === 0 ? "No zone is delegated to you." : "";
}
} catch (err) {
if (list) $("#account-zones-status").textContent = "The account could not be loaded.";
handleError(err);
}
}
bindPasswordForm($("#password-form"), async (form) => {
await api("PUT", "/account/password", { body: { current: form.elements.current.value, password: form.elements.password.value } });
toast("Password changed. Your other sessions ended.");
});
load();
+132
View File
@@ -0,0 +1,132 @@
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
import { $, api, busy, formatTime, h, handleError, icon } from "./common.js";
const state = { nextBeforeId: null, count: 0, filters: {}, counter: 0 };
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) {
return value === undefined ? "(none)" : JSON.stringify(value);
}
export function diffRows(before, after) {
const left = flatten(before === undefined ? null : before, "", new Map());
const right = flatten(after === undefined ? null : after, "", new Map());
const paths = [...new Set([...left.keys(), ...right.keys()])].filter((path) => path !== "");
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: left.has(path) ? old : undefined, after: right.has(path) ? now : 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("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 },
h("th", { scope: "row", class: "mono", text: row.path }),
h("td", { class: "mono", text: show(row.before) }),
h("td", { class: "mono", text: show(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) {
body.replaceChildren();
state.count = 0;
status.textContent = "Loading...";
}
try {
const { data } = await api("GET", "/audit", { query });
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) {
status.textContent = "The audit could not be loaded.";
handleError(err);
}
}
function readFilters() {
const form = $("#audit-filters");
const filters = {};
for (const name of ["zone", "actor", "operation", "kind", "outcome"]) {
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;
load(false);
});
$("#audit-filters").addEventListener("reset", () => {
setTimeout(() => {
state.filters = {};
state.nextBeforeId = null;
load(false);
}, 0);
});
$("#audit-more").addEventListener("click", (event) => busy(event.target, () => load(true)));
load(false);
+406
View File
@@ -0,0 +1,406 @@
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
const SVG_NS = "http://www.w3.org/2000/svg";
const ICONS = {
edit: "M4 20h4l10-10-4-4L4 16v4zM14 6l4 4",
trash: "M5 7h14M10 7V4h4v3M7 7l1 13h8l1-13M10 11v6M14 11v6",
alert: "M12 4l9 16H3L12 4zM12 10v4M12 17v1",
chevron: "M9 6l6 6-6 6",
plus: "M12 5v14M5 12h14",
close: "M6 6l12 12M18 6L6 18",
};
export function h(tag, attrs, ...children) {
const el = document.createElement(tag);
applyAttrs(el, attrs);
append(el, children);
return el;
}
function applyAttrs(el, attrs) {
if (!attrs) return;
for (const [key, value] of Object.entries(attrs)) {
if (value === undefined || value === null || value === false) continue;
if (key === "class") {
el.className = value;
} else if (key === "text") {
el.textContent = value;
} else if (key.startsWith("on") && typeof value === "function") {
el.addEventListener(key.slice(2), value);
} else if (key === "value") {
el.value = value;
} else if (key === "checked" || key === "disabled" || key === "hidden" || key === "selected") {
el[key] = Boolean(value);
} else if (value === true) {
el.setAttribute(key, "");
} else {
el.setAttribute(key, String(value));
}
}
}
function append(el, children) {
for (const child of children.flat(Infinity)) {
if (child === undefined || child === null || child === false) continue;
el.append(child instanceof Node ? child : document.createTextNode(String(child)));
}
}
export function icon(name) {
const svg = document.createElementNS(SVG_NS, "svg");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("width", "16");
svg.setAttribute("height", "16");
svg.setAttribute("fill", "none");
svg.setAttribute("stroke", "currentColor");
svg.setAttribute("stroke-width", "2");
svg.setAttribute("stroke-linecap", "round");
svg.setAttribute("stroke-linejoin", "round");
svg.setAttribute("aria-hidden", "true");
svg.setAttribute("focusable", "false");
const path = document.createElementNS(SVG_NS, "path");
path.setAttribute("d", ICONS[name] || "");
svg.append(path);
return svg;
}
export function clear(el) {
el.replaceChildren();
}
export function $(selector, root = document) {
return root.querySelector(selector);
}
export function appData() {
const app = document.getElementById("app");
return {
app,
username: app.dataset.username || "",
role: app.dataset.role || "",
zone: app.dataset.zone || "",
targetUser: app.dataset.targetUser || "",
isAdmin: app.dataset.role === "admin",
};
}
export class ApiError extends Error {
constructor(status, body) {
const message = body && typeof body.error === "string" && body.error ? body.error : defaultMessage(status);
super(message);
this.status = status;
this.body = body;
this.fields = body && body.fields && typeof body.fields === "object" ? body.fields : {};
}
}
function defaultMessage(status) {
switch (status) {
case 0: return "The server cannot be reached.";
case 403: return "You are not allowed to do this.";
case 404: return "Not found.";
case 409: return "The request conflicts with the current state.";
case 412: return "The data was changed by someone else.";
case 428: return "The request needs a current version of the data.";
case 429: return "Too many attempts. Try again later.";
case 503: return "The service is unavailable. Try again later.";
default: return "The request failed (status " + status + ").";
}
}
export async function api(method, path, options = {}) {
const headers = { Accept: "application/json" };
const init = { method, headers, credentials: "include" };
if (options.body !== undefined) {
headers["Content-Type"] = "application/json";
init.body = JSON.stringify(options.body);
}
if (options.ifMatch) headers["If-Match"] = options.ifMatch;
let url = "/api/v1" + path;
if (options.query) {
const params = new URLSearchParams();
for (const [key, value] of Object.entries(options.query)) {
if (value !== undefined && value !== null && value !== "") params.set(key, String(value));
}
const text = params.toString();
if (text) url += "?" + text;
}
let response;
try {
response = await fetch(url, init);
} catch (err) {
throw new ApiError(0, null);
}
if (response.status === 401) {
const next = location.pathname + location.search;
location.assign("/login?next=" + encodeURIComponent(next));
return new Promise(() => {});
}
const text = await response.text();
let data = null;
if (text) {
try {
data = JSON.parse(text);
} catch (err) {
data = null;
}
}
if (!response.ok) throw new ApiError(response.status, data);
return { status: response.status, data, etag: response.headers.get("ETag") };
}
export const zonePath = (zone) => "/zones/" + encodeURIComponent(zone);
export const userPath = (username) => "/users/" + encodeURIComponent(username);
export function toast(message, options = {}) {
const region = document.getElementById("toasts");
const kind = options.kind || "info";
const item = h("div", { class: "toast toast-" + kind });
item.append(h("span", { class: "toast-text", text: message }));
if (options.action) {
item.append(h("button", {
type: "button",
class: "btn btn-small",
text: options.action.label,
onclick: () => {
item.remove();
options.action.run();
},
}));
}
const close = h("button", { type: "button", class: "btn btn-icon", "aria-label": "Dismiss notification", onclick: () => item.remove() });
close.append(icon("close"));
item.append(close);
region.append(item);
if (!options.action && kind !== "error") {
setTimeout(() => item.remove(), 8000);
}
return item;
}
export function flash(message) {
try {
sessionStorage.setItem("flash", message);
} catch (err) {
return;
}
}
export function showFlash() {
let message = null;
try {
message = sessionStorage.getItem("flash");
sessionStorage.removeItem("flash");
} catch (err) {
return;
}
if (message) toast(message);
}
export function clearErrors(form) {
for (const el of form.querySelectorAll(".field-error, .form-error")) el.remove();
for (const el of form.querySelectorAll("[aria-invalid]")) el.removeAttribute("aria-invalid");
}
let errorCounter = 0;
export function showFormError(form, message) {
let box = form.querySelector(".form-error");
if (!box) {
box = h("p", { class: "alert alert-error form-error", role: "alert" });
const body = form.querySelector(".dialog-body") || form;
body.prepend(box);
}
box.textContent = message;
}
export function showFieldErrors(form, fields, message) {
clearErrors(form);
const unmatched = [];
for (const [key, text] of Object.entries(fields || {})) {
const name = key.startsWith("data.") ? key.slice(5) : key;
const control = form.elements ? form.elements[name] : null;
if (control && control.nodeType === 1) {
errorCounter += 1;
const id = "field-error-" + errorCounter;
control.setAttribute("aria-invalid", "true");
control.setAttribute("aria-describedby", id);
control.insertAdjacentElement("afterend", h("p", { class: "field-error", id, text: String(text) }));
} else {
unmatched.push(key + ": " + text);
}
}
if (unmatched.length > 0 || message) {
showFormError(form, [message, ...unmatched].filter(Boolean).join(" "));
}
}
export function handleError(err, options = {}) {
if (!(err instanceof ApiError)) {
toast("Unexpected error: " + (err && err.message ? err.message : "unknown"), { kind: "error" });
return;
}
if (err.status === 422 && options.form) {
showFieldErrors(options.form, err.fields, Object.keys(err.fields).length === 0 ? err.message : "");
return;
}
if (err.status === 412) {
toast(err.message + " Reload to see the current data.", {
kind: "error",
action: { label: "Reload", run: options.reload || (() => location.reload()) },
});
return;
}
if (options.form) {
showFormError(options.form, err.message);
return;
}
toast(err.message, { kind: "error" });
}
export async function busy(button, task) {
if (button) button.disabled = true;
try {
return await task();
} finally {
if (button) button.disabled = false;
}
}
const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])';
function trapFocus(dialog, event) {
if (event.key !== "Tab") return;
const items = [...dialog.querySelectorAll(FOCUSABLE)].filter((el) => !el.hidden && el.offsetParent !== null);
if (items.length === 0) {
event.preventDefault();
return;
}
const first = items[0];
const last = items[items.length - 1];
if (event.shiftKey && (document.activeElement === first || !dialog.contains(document.activeElement))) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && (document.activeElement === last || !dialog.contains(document.activeElement))) {
event.preventDefault();
first.focus();
}
}
export function setupDialog(dialog) {
if (dialog.dataset.ready) return;
dialog.dataset.ready = "1";
dialog.addEventListener("keydown", (event) => trapFocus(dialog, event));
dialog.addEventListener("click", (event) => {
if (event.target === dialog) dialog.close();
});
for (const button of dialog.querySelectorAll("[data-close]")) {
button.addEventListener("click", () => dialog.close());
}
}
export function setupDialogs() {
for (const dialog of document.querySelectorAll("dialog")) setupDialog(dialog);
}
export function openDialog(dialog) {
setupDialog(dialog);
const form = dialog.querySelector("form");
if (form) clearErrors(form);
dialog.showModal();
const first = dialog.querySelector("input:not([type=hidden]):not([disabled]), select:not([disabled]), textarea");
if (first) first.focus();
}
export function confirmDialog(options) {
return new Promise((resolve) => {
const titleId = "confirm-title";
const dialog = h("dialog", { class: "dialog dialog-small", "aria-labelledby": titleId });
let result = false;
const confirmButton = h("button", {
type: "button",
class: "btn " + (options.danger === false ? "btn-primary" : "btn-danger"),
text: options.confirm || "Confirm",
onclick: () => {
result = true;
dialog.close();
},
});
dialog.append(
h("div", { class: "dialog-head" }, h("h2", { id: titleId, text: options.title })),
h("div", { class: "dialog-body" }, h("p", { text: options.message })),
h("div", { class: "dialog-actions" },
h("button", { type: "button", class: "btn", "data-close": true, text: "Cancel" }),
confirmButton),
);
dialog.addEventListener("close", () => {
dialog.remove();
resolve(result);
});
document.body.append(dialog);
setupDialog(dialog);
dialog.showModal();
confirmButton.focus();
});
}
export function formatTime(iso) {
if (!iso) return "-";
const date = new Date(iso);
if (Number.isNaN(date.getTime())) return String(iso);
return date.toISOString().replace("T", " ").replace(/\.\d+Z$/, "").replace("Z", "");
}
export function formatTTL(ttl) {
if (ttl === null || ttl === undefined) return "missing";
if (ttl === 0) return "default (360 s)";
return String(ttl);
}
export function debounce(fn, ms) {
let timer = null;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), ms);
};
}
export function parseNumber(text) {
const value = String(text).trim();
return /^-?\d+$/.test(value) ? Number(value) : value;
}
export function option(value, label, selected) {
return h("option", { value, text: label, selected: Boolean(selected) });
}
export function plural(count, one, many) {
return count + " " + (count === 1 ? one : many);
}
export function zoneLink(name) {
return h("a", { href: "/zones/" + encodeURIComponent(name), text: name });
}
export function bindPasswordForm(form, submit) {
form.addEventListener("submit", async (event) => {
event.preventDefault();
clearErrors(form);
const password = form.elements.password.value;
if (password !== form.elements.repeat.value) {
showFieldErrors(form, { repeat: "The two passwords differ." });
return;
}
const button = form.querySelector("button[type=submit]");
await busy(button, async () => {
try {
await submit(form);
form.reset();
} catch (err) {
handleError(err, { form });
}
});
});
}
+146
View File
@@ -0,0 +1,146 @@
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
import { $, ApiError, api, appData, busy, clear, clearErrors, flash, formatTTL, h, handleError, plural, showFieldErrors, toast, zonePath } from "./common.js";
const { zone } = appData();
const base = zonePath(zone);
const state = { fingerprint: null, mode: "merge", content: "" };
function entryTable(title, entries, withOld) {
if (!entries || entries.length === 0) return null;
const head = ["Name", "Type", "TTL", "Value"];
if (withOld) head.push("Old TTL");
return h("div", { class: "table-wrap" },
h("table", { class: "table" },
h("caption", { text: title + " (" + entries.length + ")" }),
h("thead", null, h("tr", null, head.map((label) => h("th", { scope: "col", text: label })))),
h("tbody", null, entries.map((entry) => h("tr", null,
h("th", { scope: "row", class: "mono", text: entry.name === "" ? "@" : entry.name }),
h("td", { text: entry.type }),
h("td", { class: "num", text: formatTTL(entry.ttl) }),
h("td", { class: "mono", text: entry.value }),
withOld ? h("td", { class: "num", text: formatTTL(entry.old_ttl) }) : null)))));
}
function skippedList(skipped) {
if (!skipped || skipped.length === 0) return null;
return h("div", null,
h("h3", { text: "Skipped (" + skipped.length + ")" }),
h("ul", { class: "list" }, skipped.map((item) => h("li", null,
item.line ? "Line " + item.line + ": " : "",
h("code", { class: "mono", text: item.text || "" }),
" ",
h("span", { class: "muted", text: item.reason })))));
}
function showErrors(list) {
const box = $("#import-errors");
clear(box);
box.hidden = !list || list.length === 0;
if (box.hidden) return;
box.append(h("div", { class: "alert alert-error", role: "alert" },
h("p", { text: "The file cannot be imported:" }),
h("ul", { class: "list" }, list.map((item) => h("li", { text: (item.line ? "Line " + item.line + ": " : "") + item.message })))));
}
function showPreview(data) {
const result = $("#import-result");
result.hidden = false;
showErrors([]);
const summary = $("#import-summary");
clear(summary);
const added = data.added || [];
const updated = data.updated || [];
const deleted = data.deleted || [];
const skipped = data.skipped || [];
summary.append(h("p", { text: plural(added.length, "addition", "additions") + ", " + plural(updated.length, "update", "updates") + ", " + plural(deleted.length, "deletion", "deletions") + ", " + (data.unchanged || 0) + " unchanged, " + plural(skipped.length, "skipped entry", "skipped entries") + "." }));
if (data.soa) {
summary.append(h("p", { text: "The SOA record is replaced: " + data.soa.ns + " " + data.soa.mbox + " refresh " + data.soa.refresh + " retry " + data.soa.retry + " expire " + data.soa.expire + " minimum " + data.soa.minttl + " TTL " + formatTTL(data.soa.ttl) + "." }));
}
for (const warning of data.warnings || []) {
summary.append(h("p", { class: "alert alert-warn", text: (warning.line ? "Line " + warning.line + ": " : "") + warning.message }));
}
const tables = $("#import-tables");
clear(tables);
for (const node of [entryTable("Additions", added, false), entryTable("Updates", updated, true), entryTable("Deletions", deleted, false), skippedList(skipped)]) {
if (node) tables.append(node);
}
state.fingerprint = data.fingerprint;
const total = added.length + updated.length + deleted.length + (data.soa ? 1 : 0);
$("#import-apply").hidden = total === 0;
if (total === 0) summary.append(h("p", { class: "muted", text: "Nothing to apply." }));
}
function currentInput() {
const form = $("#import-form");
return { mode: form.elements.mode.value, content: form.elements.content.value };
}
async function preview(event) {
event.preventDefault();
const form = $("#import-form");
clearErrors(form);
const input = currentInput();
if (input.content.trim() === "") {
showFieldErrors(form, { content: "Paste a zone file or load one." });
return;
}
await busy($("#import-preview"), async () => {
try {
const { data } = await api("POST", base + "/import/preview", { body: input });
state.mode = input.mode;
state.content = input.content;
showPreview(data);
} catch (err) {
$("#import-apply").hidden = true;
state.fingerprint = null;
if (err instanceof ApiError && err.status === 422 && Array.isArray(err.body && err.body.errors)) {
$("#import-result").hidden = false;
clear($("#import-summary"));
clear($("#import-tables"));
showErrors(err.body.errors);
return;
}
handleError(err, { form });
}
});
}
async function apply() {
if (!state.fingerprint) return;
await busy($("#import-apply"), async () => {
try {
const { data } = await api("POST", base + "/import/apply", { body: { mode: state.mode, content: state.content, fingerprint: state.fingerprint } });
flash("Import applied: " + plural(data.added || 0, "addition", "additions") + ", " + plural(data.updated || 0, "update", "updates") + ", " + plural(data.deleted || 0, "deletion", "deletions") + ".");
location.assign("/zones/" + encodeURIComponent(zone));
} catch (err) {
if (err instanceof ApiError && err.status === 409) {
$("#import-apply").hidden = true;
state.fingerprint = null;
toast("The zone changed since the preview. Run the preview again.", { kind: "error" });
return;
}
handleError(err);
}
});
}
$("#zone-link").href = "/zones/" + encodeURIComponent(zone);
$("#import-form").addEventListener("submit", preview);
$("#import-apply").addEventListener("click", apply);
$("#import-form").addEventListener("input", () => {
$("#import-apply").hidden = true;
state.fingerprint = null;
});
$("#import-file").addEventListener("change", async (event) => {
const file = event.target.files[0];
if (!file) return;
if (file.size > 2 * 1024 * 1024) {
toast("The file is larger than 2 MiB.", { kind: "error" });
return;
}
$("#import-content").value = await file.text();
$("#import-apply").hidden = true;
state.fingerprint = null;
});
+129
View File
@@ -0,0 +1,129 @@
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
export const EDITABLE_TYPES = ["A", "AAAA", "CNAME", "NS", "MX", "TXT", "SRV", "CAA"];
export const KNOWN_TYPES = [...EDITABLE_TYPES, "SOA"];
export const FIELD_SPECS = {
A: [
{ key: "ip", label: "IPv4 address", placeholder: "192.0.2.10" },
],
AAAA: [
{ key: "ip", label: "IPv6 address", placeholder: "2001:db8::10" },
],
CNAME: [
{ key: "host", label: "Target host", placeholder: "target.example.org" },
],
NS: [
{ key: "host", label: "Name server host", placeholder: "ns1.example.org" },
],
MX: [
{ key: "preference", label: "Preference", placeholder: "10", numeric: true },
{ key: "host", label: "Mail host", placeholder: "mail.example.org" },
],
TXT: [
{ key: "text", label: "Text", multiline: true, placeholder: "v=spf1 -all" },
],
SRV: [
{ key: "priority", label: "Priority", placeholder: "10", numeric: true },
{ key: "weight", label: "Weight", placeholder: "5", numeric: true },
{ key: "port", label: "Port", placeholder: "443", numeric: true },
{ key: "target", label: "Target host", placeholder: "host.example.org" },
],
CAA: [
{ key: "flag", label: "Flag", options: [["0", "0 (not critical)"], ["128", "128 (critical)"]] },
{ key: "tag", label: "Tag", placeholder: "issue" },
{ key: "value", label: "Value", placeholder: "ca.example.net" },
],
};
export function presentValue(record) {
const data = record.data;
if (!data || typeof data !== "object") return record.raw === null || record.raw === undefined ? "" : String(record.raw);
switch (record.type) {
case "A":
case "AAAA":
return String(data.ip);
case "CNAME":
case "NS":
return String(data.host);
case "MX":
return data.preference + " " + data.host;
case "TXT":
return '"' + data.text + '"';
case "SRV":
return data.priority + " " + data.weight + " " + data.port + " " + data.target;
case "CAA":
return data.flag + " " + data.tag + ' "' + data.value + '"';
case "SOA":
return [data.ns, data.MBox !== undefined ? data.MBox : data.mbox, data.serial === null || data.serial === undefined ? "dynamic" : data.serial, data.refresh, data.retry, data.expire, data.minttl].join(" ");
default:
return JSON.stringify(data);
}
}
export function displayName(record) {
return record.name === "" ? "@" : record.name;
}
function nameLabels(name) {
return name === "" ? [] : name.toLowerCase().split(".").reverse();
}
function compareLabels(a, b) {
const left = nameLabels(a);
const right = nameLabels(b);
const length = Math.min(left.length, right.length);
for (let i = 0; i < length; i += 1) {
if (left[i] < right[i]) return -1;
if (left[i] > right[i]) return 1;
}
return left.length - right.length;
}
function typeRank(type) {
if (type === "SOA") return 0;
if (type === "NS") return 1;
return 2;
}
export function compareRecords(a, b) {
const byName = compareLabels(a.name, b.name);
if (byName !== 0) return byName;
const byRank = typeRank(a.type) - typeRank(b.type);
if (byRank !== 0) return byRank;
if (a.type !== b.type) return a.type < b.type ? -1 : 1;
const left = presentValue(a);
const right = presentValue(b);
return left.localeCompare(right, "en", { numeric: true });
}
export function sortRecords(records) {
return [...records].sort(compareRecords);
}
export function matchesFilter(record, type, text) {
if (type && record.type !== type) return false;
if (!text) return true;
const needle = text.toLowerCase();
const haystack = [displayName(record), record.fqdn || "", record.type, presentValue(record)].join(" ").toLowerCase();
return haystack.includes(needle);
}
export function stripDot(name) {
return name.endsWith(".") ? name.slice(0, -1) : name;
}
export function previewName(input, zone) {
const apex = zone.endsWith(".") ? zone : zone + ".";
let text = input.trim().toLowerCase();
if (text === "" || text === "@") return { name: "", fqdn: apex, error: "" };
if (text.endsWith("." + apex)) {
text = text.slice(0, -(apex.length + 1));
} else if (text === apex) {
return { name: "", fqdn: apex, error: "" };
} else if (text.endsWith(".")) {
return { name: "", fqdn: "", error: "The name ends with a dot and is outside " + apex };
}
return { name: text, fqdn: text + "." + apex, error: "" };
}
+157
View File
@@ -0,0 +1,157 @@
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
import { $, api, appData, bindPasswordForm, busy, clear, confirmDialog, flash, formatTime, h, handleError, icon, option, setupDialogs, toast, userPath, zoneLink, zonePath } from "./common.js";
const { targetUser, username: self } = appData();
const base = userPath(targetUser);
const isSelf = targetUser === self;
const state = { user: null };
function summaryRow(dl, term, value) {
dl.append(h("dt", { text: term }), h("dd", { text: value }));
}
function renderSummary(user) {
const dl = $("#user-summary");
clear(dl);
summaryRow(dl, "Role", user.role);
summaryRow(dl, "Created (UTC)", formatTime(user.created_at));
summaryRow(dl, "Last login (UTC)", formatTime(user.last_login_at));
summaryRow(dl, "State", user.deleted_at ? "deleted " + formatTime(user.deleted_at) : "active");
$("#user-status").textContent = "";
const badge = $("#user-state");
badge.hidden = !user.deleted_at;
badge.textContent = "deleted";
}
function zoneItem(entry, removable) {
const item = h("li", null, entry.exists ? zoneLink(entry.zone) : h("span", { class: "mono", text: entry.zone }));
if (!entry.exists) item.append(" ", h("span", { class: "badge badge-warning", text: "zone not found" }));
if (removable) {
item.append(" ", h("button", { type: "button", class: "btn btn-small btn-danger", "aria-label": "Remove zone " + entry.zone, onclick: () => removeZone(entry.zone) }, icon("trash"), " Remove"));
}
return item;
}
async function renderZones(user) {
const readonly = Boolean(user.deleted_at);
const zones = user.zones || [];
if (readonly) {
const list = $("#user-zones-readonly");
clear(list);
for (const entry of zones) list.append(zoneItem(entry, false));
return;
}
const list = $("#user-zones");
clear(list);
for (const entry of zones) list.append(zoneItem(entry, true));
$("#user-zones-status").textContent = zones.length === 0 ? "No zone is delegated to this user." : "";
const form = $("#zone-add-form");
const pick = $("#user-zone-pick");
clear(pick);
if (user.role === "admin") {
form.hidden = true;
$("#user-zones-status").textContent = zones.length === 0 ? "Administrators see every zone and need no delegation." : "Administrators need no delegation; these delegations apply again if the user is demoted.";
return;
}
form.hidden = false;
try {
const { data } = await api("GET", "/zones");
const have = new Set(zones.map((entry) => entry.zone));
const candidates = (data.zones || []).filter((zone) => !have.has(zone.name));
for (const zone of candidates) pick.append(option(zone.name, zone.name, false));
if (candidates.length === 0) pick.append(option("", "No zone available", true));
pick.disabled = candidates.length === 0;
form.querySelector("button").disabled = candidates.length === 0;
} catch (err) {
handleError(err);
}
}
async function load() {
try {
const { data } = await api("GET", base);
state.user = data;
} catch (err) {
$("#user-status").textContent = "The user could not be loaded.";
handleError(err);
return;
}
const user = state.user;
renderSummary(user);
if (isSelf) return;
const deleted = Boolean(user.deleted_at);
$("#user-controls").hidden = deleted;
$("#user-readonly").hidden = !deleted;
$("#user-role").value = user.role;
await renderZones(user);
}
async function removeZone(zone) {
const ok = await confirmDialog({ title: "Remove zone", message: "Remove the delegation of " + zone + " from " + targetUser + "?", confirm: "Remove" });
if (!ok) return;
try {
await api("DELETE", zonePath(zone) + "/users/" + encodeURIComponent(targetUser));
toast("Delegation removed.");
await load();
} catch (err) {
handleError(err, { reload: load });
}
}
function setup() {
$("#role-form").addEventListener("submit", async (event) => {
event.preventDefault();
await busy(event.target.querySelector("button"), async () => {
try {
await api("PUT", base + "/role", { body: { role: $("#user-role").value } });
toast("Role saved.");
await load();
} catch (err) {
handleError(err);
await load();
}
});
});
bindPasswordForm($("#password-form"), async (form) => {
await api("PUT", base + "/password", { body: { password: form.elements.password.value } });
toast("Password set. The sessions of " + targetUser + " ended.");
});
$("#zone-add-form").addEventListener("submit", async (event) => {
event.preventDefault();
const zone = $("#user-zone-pick").value;
if (!zone) return;
await busy(event.target.querySelector("button"), async () => {
try {
await api("PUT", zonePath(zone) + "/users/" + encodeURIComponent(targetUser));
toast("Zone delegated.");
await load();
} catch (err) {
handleError(err);
}
});
});
const confirmInput = $("#user-delete-confirm");
const deleteButton = $("#user-delete");
confirmInput.addEventListener("input", () => {
deleteButton.disabled = confirmInput.value.trim() !== targetUser;
});
$("#user-delete-form").addEventListener("submit", async (event) => {
event.preventDefault();
if (deleteButton.disabled) return;
await busy(deleteButton, async () => {
try {
await api("DELETE", base, { body: { confirm: confirmInput.value.trim() } });
flash("User " + targetUser + " deleted.");
location.assign("/users");
} catch (err) {
handleError(err);
}
});
});
}
setupDialogs();
if (!isSelf) setup();
load();
+67
View File
@@ -0,0 +1,67 @@
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
import { $, api, busy, clear, clearErrors, formatTime, h, handleError, openDialog, setupDialogs, showFieldErrors, toast, userPath } from "./common.js";
const state = { users: [] };
function render() {
const body = $("#users-body");
clear(body);
for (const user of state.users) {
const deleted = Boolean(user.deleted_at);
body.append(h("tr", { class: deleted ? "row-muted" : null },
h("th", { scope: "row" }, h("a", { href: userPath(user.username), text: user.username })),
h("td", { text: user.role }),
h("td", { class: "num", text: user.zone_count }),
h("td", { class: "mono", text: formatTime(user.created_at) }),
h("td", { class: "mono", text: formatTime(user.last_login_at) }),
h("td", null, deleted ? h("span", { class: "badge badge-muted", text: "deleted " + formatTime(user.deleted_at) }) : h("span", { class: "badge badge-ok", text: "active" }))));
}
$("#users-status").textContent = state.users.length === 0 ? "No users." : state.users.length + (state.users.length === 1 ? " user." : " users.");
}
async function load() {
try {
const { data } = await api("GET", "/users", { query: { deleted: $("#show-deleted").checked ? "true" : "" } });
state.users = data.users || [];
render();
} catch (err) {
$("#users-status").textContent = "The users could not be loaded.";
handleError(err);
}
}
function setupCreate() {
const dialog = $("#user-dialog");
const form = $("#user-form");
$("#new-user").addEventListener("click", () => {
form.reset();
openDialog(dialog);
});
form.addEventListener("submit", async (event) => {
event.preventDefault();
clearErrors(form);
if (form.elements.password.value !== form.elements.repeat.value) {
showFieldErrors(form, { repeat: "The two passwords differ." });
return;
}
await busy(form.querySelector("button[type=submit]"), async () => {
try {
await api("POST", "/users", { body: { username: form.elements.username.value.trim(), role: form.elements.role.value, password: form.elements.password.value } });
} catch (err) {
handleError(err, { form });
return;
}
dialog.close();
form.reset();
toast("User created.");
await load();
});
});
}
setupDialogs();
setupCreate();
$("#show-deleted").addEventListener("change", load);
load();
+536
View File
@@ -0,0 +1,536 @@
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
import { $, api, appData, busy, clear, clearErrors, confirmDialog, flash, formatTTL, handleError, h, icon, openDialog, option, parseNumber, plural, setupDialogs, showFieldErrors, showFlash, toast, zonePath } from "./common.js";
import { EDITABLE_TYPES, FIELD_SPECS, displayName, matchesFilter, presentValue, previewName, sortRecords, stripDot } from "./records.js";
const PAGE_SIZE = 100;
const { zone: zoneParam, isAdmin } = appData();
const base = zonePath(zoneParam);
const state = {
summary: null,
records: [],
problems: [],
type: "",
text: "",
page: 0,
selected: new Set(),
};
function zoneName() {
return state.summary ? state.summary.name : zoneParam;
}
function soaRow() {
return state.records.find((record) => record.type === "SOA" && record.name === "") || null;
}
function problemBadge(problem) {
return h("li", { class: "problem problem-" + problem.severity },
h("span", { class: "badge badge-" + (problem.severity === "error" ? "error" : "warning"), text: problem.severity }),
" ",
h("code", { text: problem.code }),
" ",
problem.message);
}
function renderSoa() {
const summary = $("#soa-summary");
const status = $("#soa-status");
const managed = $("#soa-managed");
const edit = $("#soa-edit");
clear(summary);
managed.hidden = true;
const soa = state.summary ? state.summary.soa : null;
edit.disabled = !(soa || soaRow());
if (!soa) {
status.textContent = soaRow() ? "The SOA record cannot be read. Edit it to replace it." : "This zone has no SOA record.";
return;
}
status.textContent = "";
const dynamic = soa.serial === null || soa.serial === undefined;
const items = [
["Primary name server", soa.ns],
["Hostmaster", soa.mbox],
["Serial", dynamic ? "dynamic (Unix time)" : String(soa.serial)],
["Refresh", String(soa.refresh)],
["Retry", String(soa.retry)],
["Expire", String(soa.expire)],
["Minimum TTL", String(soa.minttl)],
["TTL", formatTTL(soa.ttl)],
];
for (const [term, value] of items) {
summary.append(h("dt", { text: term }), h("dd", { class: "mono", text: value }));
}
managed.hidden = !dynamic;
}
function renderProblems() {
const panel = $("#problems-panel");
const list = $("#problems-list");
clear(list);
panel.hidden = state.problems.length === 0;
$("#problems-title").textContent = "Problems (" + state.problems.length + ")";
for (const problem of state.problems) {
const where = problem.name === null || problem.name === undefined ? "zone" : (problem.name === "" ? "@" : problem.name) + (problem.type ? " " + problem.type : "");
const item = problemBadge(problem);
item.append(" ", h("span", { class: "muted", text: "(" + where + ")" }));
list.append(item);
}
}
function typeOptions() {
const select = $("#filter-type");
const types = [...new Set(state.records.map((record) => record.type))].sort();
if (state.type && !types.includes(state.type)) state.type = "";
clear(select);
select.append(option("", "All types", state.type === ""));
for (const type of types) select.append(option(type, type, state.type === type));
}
function visibleRecords() {
return sortRecords(state.records).filter((record) => matchesFilter(record, state.type, state.text));
}
function problemsCell(record) {
const list = h("ul", { class: "problems" });
for (const problem of record.problems || []) list.append(problemBadge(problem));
return list;
}
function renderRecords() {
const body = $("#records-body");
const all = visibleRecords();
const pages = Math.max(1, Math.ceil(all.length / PAGE_SIZE));
if (state.page >= pages) state.page = pages - 1;
const rows = all.slice(state.page * PAGE_SIZE, (state.page + 1) * PAGE_SIZE);
clear(body);
for (const record of rows) body.append(recordRow(record));
const status = $("#records-status");
if (state.records.length === 0) status.textContent = "This zone has no records.";
else if (all.length === 0) status.textContent = "No record matches the filter.";
else status.textContent = plural(all.length, "record", "records") + (all.length === state.records.length ? "." : " of " + state.records.length + ".");
const pager = $("#pager");
pager.hidden = all.length <= PAGE_SIZE;
$("#page-info").textContent = "Page " + (state.page + 1) + " of " + pages;
$("#page-prev").disabled = state.page === 0;
$("#page-next").disabled = state.page >= pages - 1;
updateSelection();
}
function recordRow(record) {
const label = displayName(record) + " " + record.type;
const broken = record.data === null || record.data === undefined;
const isSoa = record.type === "SOA";
const checkbox = h("input", {
type: "checkbox",
disabled: isSoa,
checked: state.selected.has(record.id),
"aria-label": "Select " + label,
onchange: (event) => {
if (event.target.checked) state.selected.add(record.id);
else state.selected.delete(record.id);
updateSelection();
},
});
const hasError = (record.problems || []).some((problem) => problem.severity === "error");
const hasWarning = (record.problems || []).length > 0;
const value = h("td", { class: "value" },
h("code", { class: broken ? "mono raw" : "mono", text: presentValue(record) }),
(record.problems || []).length > 0 ? problemsCell(record) : null);
const edit = h("button", { type: "button", class: "btn btn-small", "aria-label": "Edit " + label, onclick: () => (isSoa ? openSoa() : openRecord(record)) }, icon("edit"), " Edit");
const actions = h("td", { class: "actions-cell" }, edit);
if (!isSoa) {
actions.append(" ", h("button", { type: "button", class: "btn btn-small btn-danger", "aria-label": "Delete " + label, onclick: () => deleteRecord(record) }, icon("trash"), " Delete"));
}
return h("tr", { class: hasError ? "row-error" : hasWarning ? "row-warning" : null },
h("td", { class: "check" }, checkbox),
h("th", { scope: "row", title: record.fqdn || "" }, h("span", { class: "mono", text: displayName(record) })),
h("td", { text: record.type }),
h("td", { class: "num", text: formatTTL(record.ttl) }),
value,
actions);
}
function pageRows() {
return visibleRecords().slice(state.page * PAGE_SIZE, (state.page + 1) * PAGE_SIZE);
}
function updateSelection() {
const ids = new Set(state.records.map((record) => record.id));
for (const id of state.selected) if (!ids.has(id)) state.selected.delete(id);
const button = $("#bulk-delete");
button.disabled = state.selected.size === 0;
button.textContent = state.selected.size === 0 ? "Delete selected" : "Delete selected (" + state.selected.size + ")";
const selectable = pageRows().filter((record) => record.type !== "SOA");
$("#select-all").checked = selectable.length > 0 && selectable.every((record) => state.selected.has(record.id));
}
async function load() {
const results = await Promise.allSettled([
api("GET", base),
api("GET", base + "/records"),
api("GET", base + "/check"),
]);
const [summary, records, check] = results;
if (summary.status === "rejected") {
$("#soa-status").textContent = "The zone could not be loaded.";
$("#records-status").textContent = "The records could not be loaded.";
handleError(summary.reason);
return;
}
state.summary = summary.value.data;
state.records = records.status === "fulfilled" ? records.value.data.records || [] : [];
state.problems = check.status === "fulfilled" ? check.value.data.problems || [] : [];
if (records.status === "rejected") handleError(records.reason);
$("#zone-title").textContent = state.summary.name;
renderSoa();
renderProblems();
typeOptions();
renderRecords();
if (isAdmin) loadUsers();
}
function numberFields(form, names) {
const out = {};
for (const name of names) out[name] = parseNumber(form.elements[name].value);
return out;
}
function soaBody(form) {
return {
ns: form.elements.ns.value.trim(),
mbox: form.elements.mbox.value.trim(),
...numberFields(form, ["ttl", "refresh", "retry", "expire", "minttl"]),
};
}
function openSoa() {
const form = $("#soa-form");
const soa = state.summary ? state.summary.soa : null;
const row = soaRow();
$("#soa-broken").hidden = Boolean(soa);
const values = soa || { ns: "", mbox: "", ttl: row && Number.isInteger(row.ttl) && row.ttl >= 0 ? row.ttl : 3600, refresh: 3600, retry: 600, expire: 604800, minttl: 300 };
for (const name of ["ns", "mbox", "ttl", "refresh", "retry", "expire", "minttl"]) form.elements[name].value = String(values[name]);
openDialog($("#soa-dialog"));
}
function setupSoa() {
const dialog = $("#soa-dialog");
const form = $("#soa-form");
$("#soa-edit").addEventListener("click", openSoa);
form.addEventListener("submit", async (event) => {
event.preventDefault();
clearErrors(form);
const etag = (state.summary && state.summary.soa ? state.summary.soa.etag : null) || (soaRow() ? soaRow().etag : null);
await busy(form.querySelector("button[type=submit]"), async () => {
try {
const { data } = await api("PUT", base + "/soa", { body: soaBody(form), ifMatch: etag });
dialog.close();
reportWarnings("SOA saved.", data);
await load();
} catch (err) {
handleError(err, { form, reload: load });
}
});
});
$("#soa-managed").addEventListener("click", async (event) => {
const soa = state.summary && state.summary.soa;
if (!soa) return;
await busy(event.target, async () => {
try {
const body = { ns: soa.ns, mbox: soa.mbox, ttl: soa.ttl, refresh: soa.refresh, retry: soa.retry, expire: soa.expire, minttl: soa.minttl, managed_serial: true };
await api("PUT", base + "/soa", { body, ifMatch: soa.etag });
toast("The zone now uses a managed serial.");
await load();
} catch (err) {
handleError(err, { reload: load });
}
});
});
}
function reportWarnings(message, data) {
const warnings = data && Array.isArray(data.warnings) ? data.warnings : [];
toast(message);
for (const warning of warnings) toast("Warning: " + warning.message, { kind: "warning" });
}
const recordForm = {
editing: null,
ttlTouched: false,
};
function fieldId(key) {
return "rec-f-" + key;
}
function readTypeValues(form) {
const values = {};
for (const control of form.querySelectorAll("#rec-fields [name]")) values[control.name] = control.value;
return values;
}
function buildTypeFields(type, values) {
const container = $("#rec-fields");
clear(container);
const specs = FIELD_SPECS[type] || [];
for (const spec of specs) {
const id = fieldId(spec.key);
let control;
const current = values[spec.key] === undefined || values[spec.key] === null ? "" : String(values[spec.key]);
if (spec.options) {
control = h("select", { id, name: spec.key }, spec.options.map(([value, label]) => option(value, label, value === current)));
} else if (spec.multiline) {
control = h("textarea", { id, name: spec.key, rows: 3, autocomplete: "off", spellcheck: "false", placeholder: spec.placeholder, value: current });
} else {
control = h("input", {
id,
name: spec.key,
type: "text",
autocomplete: "off",
autocapitalize: "none",
spellcheck: "false",
inputmode: spec.numeric ? "numeric" : null,
placeholder: spec.placeholder,
value: current,
});
}
container.append(h("div", { class: "field" }, h("label", { for: id, text: spec.label }), control));
}
}
function updatePreview() {
const form = $("#record-form");
const result = previewName(form.elements.name.value, zoneName());
const hint = $("#rec-fqdn");
hint.textContent = result.error ? result.error : "Full name: " + result.fqdn;
if (!recordForm.ttlTouched && !recordForm.editing) applyRrsetTtl(result);
}
function applyRrsetTtl(result) {
const form = $("#record-form");
const type = form.elements.type.value;
let ttl = 3600;
if (!result.error) {
const match = state.records.find((record) => record.name === result.name && record.type === type && Number.isInteger(record.ttl) && record.ttl >= 0);
if (match) ttl = match.ttl;
}
form.elements.ttl.value = String(ttl);
}
function openRecord(record) {
const form = $("#record-form");
const broken = Boolean(record) && (record.data === null || record.data === undefined);
const known = Boolean(record) && EDITABLE_TYPES.includes(record.type);
recordForm.editing = record || null;
recordForm.ttlTouched = Boolean(record);
$("#record-dialog-title").textContent = record ? "Edit record" : "Add record";
$("#record-broken").hidden = !broken;
$("#record-raw").textContent = broken && record.raw !== null && record.raw !== undefined ? String(record.raw) : "";
const select = form.elements.type;
clear(select);
if (record && !known) select.append(option("", "Select a type", true));
for (const type of EDITABLE_TYPES) select.append(option(type, type, record ? record.type === type : type === "A"));
select.disabled = Boolean(record) && known;
form.elements.name.value = record ? displayName(record) : "";
const ttl = record && Number.isInteger(record.ttl) && record.ttl >= 0 ? record.ttl : 3600;
form.elements.ttl.value = String(ttl);
buildTypeFields(select.value, record && !broken ? record.data : {});
$("#rec-submit").textContent = record ? "Save changes" : "Add record";
updatePreview();
openDialog($("#record-dialog"));
}
function recordBody(form) {
const type = form.elements.type.value;
const data = {};
for (const spec of FIELD_SPECS[type] || []) {
const value = form.elements[spec.key].value;
data[spec.key] = spec.numeric || spec.options ? parseNumber(value) : spec.multiline ? value : value.trim();
}
return { name: form.elements.name.value.trim(), type, ttl: parseNumber(form.elements.ttl.value), data };
}
function setupRecordForm() {
const dialog = $("#record-dialog");
const form = $("#record-form");
$("#record-add").addEventListener("click", () => openRecord(null));
form.elements.name.addEventListener("input", updatePreview);
form.elements.ttl.addEventListener("input", () => {
recordForm.ttlTouched = true;
});
form.elements.type.addEventListener("change", () => {
buildTypeFields(form.elements.type.value, readTypeValues(form));
if (!recordForm.ttlTouched && !recordForm.editing) updatePreview();
});
form.addEventListener("submit", async (event) => {
event.preventDefault();
clearErrors(form);
if (!form.elements.type.value) {
showFieldErrors(form, { type: "Select a type." });
return;
}
const editing = recordForm.editing;
await busy(form.querySelector("button[type=submit]"), async () => {
try {
const body = recordBody(form);
const result = editing
? await api("PUT", base + "/records/" + editing.id, { body, ifMatch: editing.etag })
: await api("POST", base + "/records", { body });
dialog.close();
reportWarnings(editing ? "Record saved." : "Record added.", result.data);
await load();
} catch (err) {
handleError(err, { form, reload: () => { dialog.close(); return load(); } });
}
});
});
}
async function deleteRecord(record) {
const label = displayName(record) + " " + record.type + " " + presentValue(record);
const ok = await confirmDialog({ title: "Delete record", message: "Delete " + label + "?", confirm: "Delete" });
if (!ok) return;
try {
await api("DELETE", base + "/records/" + record.id, { ifMatch: record.etag });
state.selected.delete(record.id);
toast("Record deleted.");
await load();
} catch (err) {
handleError(err, { reload: load });
}
}
async function bulkDelete() {
const items = state.records.filter((record) => state.selected.has(record.id) && record.type !== "SOA");
if (items.length === 0) return;
const ok = await confirmDialog({ title: "Delete records", message: "Delete " + plural(items.length, "selected record", "selected records") + "? Either all of them are deleted or none.", confirm: "Delete" });
if (!ok) return;
try {
await api("POST", base + "/records/delete", { body: { records: items.map((record) => ({ id: record.id, etag: record.etag })) } });
state.selected.clear();
toast(plural(items.length, "record", "records") + " deleted.");
await load();
} catch (err) {
handleError(err, { reload: load });
}
}
function setupTable() {
$("#filter-type").addEventListener("change", (event) => {
state.type = event.target.value;
state.page = 0;
renderRecords();
});
$("#filter-text").addEventListener("input", (event) => {
state.text = event.target.value;
state.page = 0;
renderRecords();
});
$("#page-prev").addEventListener("click", () => {
state.page -= 1;
renderRecords();
});
$("#page-next").addEventListener("click", () => {
state.page += 1;
renderRecords();
});
$("#select-all").addEventListener("change", (event) => {
for (const record of pageRows()) {
if (record.type === "SOA") continue;
if (event.target.checked) state.selected.add(record.id);
else state.selected.delete(record.id);
}
renderRecords();
});
$("#bulk-delete").addEventListener("click", bulkDelete);
}
async function loadUsers() {
const list = $("#zone-users");
const status = $("#zone-users-status");
const pick = $("#zone-user-pick");
try {
const [delegated, users] = await Promise.all([api("GET", base + "/users"), api("GET", "/users")]);
const current = delegated.data.users || [];
const names = new Set(current.map((user) => user.username));
clear(list);
for (const user of current) {
list.append(h("li", null,
h("span", { class: "mono", text: user.username }),
" ",
h("button", { type: "button", class: "btn btn-small btn-danger", "aria-label": "Remove " + user.username + " from this zone", onclick: () => removeUser(user.username) }, icon("trash"), " Remove")));
}
status.textContent = current.length === 0 ? "The zone is not delegated to any user." : "";
const candidates = (users.data.users || []).filter((user) => user.role === "user" && !names.has(user.username));
clear(pick);
for (const user of candidates) pick.append(option(user.username, user.username, false));
$("#zone-user-add").disabled = candidates.length === 0;
pick.disabled = candidates.length === 0;
if (candidates.length === 0) pick.append(option("", "No user available", true));
} catch (err) {
status.textContent = "The users could not be loaded.";
handleError(err);
}
}
async function removeUser(username) {
const ok = await confirmDialog({ title: "Remove user", message: "Remove " + username + " from this zone?", confirm: "Remove" });
if (!ok) return;
try {
await api("DELETE", base + "/users/" + encodeURIComponent(username));
toast("Delegation removed.");
await loadUsers();
} catch (err) {
handleError(err, { reload: loadUsers });
}
}
function setupAdmin() {
$("#zone-user-form").addEventListener("submit", async (event) => {
event.preventDefault();
const username = $("#zone-user-pick").value;
if (!username) return;
await busy($("#zone-user-add"), async () => {
try {
await api("PUT", base + "/users/" + encodeURIComponent(username));
toast("Zone delegated to " + username + ".");
await loadUsers();
} catch (err) {
handleError(err);
}
});
});
const confirmInput = $("#zone-delete-confirm");
const deleteButton = $("#zone-delete");
confirmInput.addEventListener("input", () => {
deleteButton.disabled = stripDot(confirmInput.value.trim().toLowerCase()) !== stripDot(zoneName().toLowerCase());
});
$("#zone-delete-form").addEventListener("submit", async (event) => {
event.preventDefault();
if (deleteButton.disabled) return;
await busy(deleteButton, async () => {
try {
await api("DELETE", base, { body: { confirm: confirmInput.value.trim() } });
flash("Zone " + zoneName() + " deleted. The DNS server stops serving it after its next zone list reload, which happens every 10 minutes by default.");
location.assign("/");
} catch (err) {
handleError(err);
}
});
});
}
setupDialogs();
showFlash();
const exportLink = $("#export-link");
exportLink.href = "/api/v1" + base + "/export";
exportLink.setAttribute("download", "");
$("#import-link").href = "/zones/" + encodeURIComponent(zoneParam) + "/import";
setupSoa();
setupRecordForm();
setupTable();
if (isAdmin) setupAdmin();
load();
+128
View File
@@ -0,0 +1,128 @@
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
import { $, api, appData, busy, clear, clearErrors, handleError, h, openDialog, parseNumber, plural, setupDialogs, showFlash, toast, zoneLink } from "./common.js";
const { isAdmin } = appData();
const state = { zones: [], counts: null, countsFailed: false, search: "" };
function problemCell(zone) {
const cell = h("td");
if (state.countsFailed) {
cell.textContent = "unavailable";
return cell;
}
if (state.counts === null) {
cell.textContent = "loading...";
return cell;
}
const counts = state.counts.get(zone.name) || { error: 0, warning: 0 };
if (counts.error === 0 && counts.warning === 0) {
cell.append(h("span", { class: "badge badge-ok", text: "none" }));
return cell;
}
if (counts.error > 0) cell.append(h("span", { class: "badge badge-error", text: plural(counts.error, "error", "errors") }), " ");
if (counts.warning > 0) cell.append(h("span", { class: "badge badge-warning", text: plural(counts.warning, "warning", "warnings") }));
return cell;
}
function render() {
const body = $("#zones-body");
const needle = state.search.trim().toLowerCase();
const zones = state.zones.filter((zone) => zone.name.toLowerCase().includes(needle));
clear(body);
for (const zone of zones) {
const serial = zone.serial === null || zone.serial === undefined ? "dynamic" : String(zone.serial);
body.append(h("tr", null,
h("th", { scope: "row" }, zoneLink(zone.name)),
h("td", { class: "num", text: zone.records }),
h("td", { class: "mono", text: serial }),
problemCell(zone)));
}
const status = $("#zones-status");
if (state.zones.length === 0) {
status.textContent = isAdmin ? "There are no zones yet." : "No zone is delegated to you.";
} else if (zones.length === 0) {
status.textContent = "No zone matches the search.";
} else {
status.textContent = plural(zones.length, "zone", "zones") + ".";
}
}
async function loadCounts() {
try {
const { data } = await api("GET", "/check");
const counts = new Map();
for (const problem of data.problems || []) {
const entry = counts.get(problem.zone) || { error: 0, warning: 0 };
if (problem.severity === "error") entry.error += 1;
else entry.warning += 1;
counts.set(problem.zone, entry);
}
state.counts = counts;
} catch (err) {
state.countsFailed = true;
}
render();
}
async function load() {
try {
const { data } = await api("GET", "/zones");
state.zones = data.zones || [];
} catch (err) {
$("#zones-status").textContent = "The zones could not be loaded.";
handleError(err);
return;
}
state.counts = null;
state.countsFailed = false;
render();
loadCounts();
}
function zoneBody(form) {
const el = form.elements;
return {
name: el.name.value.trim(),
ns: el.ns.value.trim(),
mbox: el.mbox.value.trim(),
extra_ns: el.extra_ns.value.split("\n").map((line) => line.trim()).filter(Boolean),
refresh: parseNumber(el.refresh.value),
retry: parseNumber(el.retry.value),
expire: parseNumber(el.expire.value),
minttl: parseNumber(el.minttl.value),
ttl: parseNumber(el.ttl.value),
};
}
function setupCreate() {
const dialog = $("#zone-dialog");
const form = $("#zone-form");
$("#new-zone").addEventListener("click", () => openDialog(dialog));
form.addEventListener("submit", async (event) => {
event.preventDefault();
clearErrors(form);
await busy(form.querySelector("button[type=submit]"), async () => {
try {
await api("POST", "/zones", { body: zoneBody(form) });
} catch (err) {
handleError(err, { form });
return;
}
dialog.close();
form.reset();
toast("Zone created. The DNS server serves a new zone after its next zone list reload, which happens every 10 minutes by default.");
await load();
});
});
}
setupDialogs();
showFlash();
$("#zone-search").addEventListener("input", (event) => {
state.search = event.target.value;
render();
});
if (isAdmin) setupCreate();
load();