feat(server): admin panel pages for dashboard, users, archive, jobs, settings and logs

Vanilla ES modules under a strict CSP (bars and charts are SVG, no inline
styles), cookie session with CSRF header, first sign-in password change,
live updates over the events WebSocket, language menu fed by
/api/v1/i18n. Every label and tooltip is an Admin.* resource (en, it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-02 12:41:42 +00:00
1 parent 145ecf33d2
commit 26016f1621
16 files changed
+2029 -106

No files matched your search

+234
View File
@@ -0,0 +1,234 @@
// Users (mockup AdminUsers.html, BRIEF §14.8): accounts table and a side panel to create, edit and reset.
import { t, applyStrings } from "../i18n.js";
import { escapeHtml, attr, formatBytes, formatNumber, formatTime, bar, toast, confirmDialog, errorText } from "../ui.js";
import { icons } from "../icons.js";
const ROLES = ["viewer", "uploader", "editor", "admin"];
const TB = 1e12;
const RENDER_NODE = 32;
export async function render(root, { api, info, meta, actions }) {
let users = [];
let filter = "";
let freeBytes = 0;
let tokenDays = 30;
actions.innerHTML = `
<input class="input search" type="search" id="search" data-i18n-placeholder="Admin.Users.Search" data-i18n-title="Admin.Users.Search.Tip" aria-label="${attr(t("Admin.Users.Search"))}">
<button class="btn primary" id="new" data-i18n="Admin.Users.New" data-i18n-title="Admin.Users.New.Tip"></button>`;
applyStrings(actions);
actions.querySelector("#search").addEventListener("input", (e) => {
filter = e.target.value.trim().toLowerCase();
drawTable();
});
actions.querySelector("#new").addEventListener("click", () => openForm(null));
root.innerHTML = `
<div class="split">
<div class="panel flush">
<div class="table users">
<div class="thead"><span data-i18n="Admin.Users.User"></span><span data-i18n="Admin.Users.Role"></span><span data-i18n="Admin.Users.Quota"></span>
<span data-i18n="Admin.Users.LastSeen"></span><span class="right" data-i18n="Admin.Users.Uploads"></span><span data-i18n="Admin.Users.Status"></span><span></span></div>
<div id="rows"></div>
</div>
<div class="table-foot"><span id="policy" class="muted"></span><span class="spacer"></span>
<a href="#/logs?view=signins" data-i18n="Admin.Users.SignInLog" data-i18n-title="Admin.Users.SignInLog.Tip"></a></div>
</div>
<aside class="panel side" id="side" hidden></aside>
</div>`;
applyStrings(root);
async function load() {
try {
const [list, stats, settings] = await Promise.all([
api.get("/api/v1/users"),
api.get("/api/v1/archive/stats").catch(() => null),
api.get("/api/v1/server/settings").catch(() => null),
]);
users = list;
freeBytes = stats?.freeBytes ?? 0;
tokenDays = settings?.tokenLifetimeDays ?? tokenDays;
} catch (err) {
toast(errorText(err), true);
return;
}
const active = users.filter((u) => !u.user.disabled).length;
meta.textContent = t("Admin.Users.Meta", formatNumber(users.length), formatNumber(active));
root.querySelector("#policy").textContent = t("Admin.Users.Policy", info?.limits?.passwordMinLength ?? 10, tokenDays);
drawTable();
}
function drawTable() {
const rows = users.filter((u) => !filter || u.user.username.toLowerCase().includes(filter) || (u.user.displayName ?? "").toLowerCase().includes(filter));
const host = root.querySelector("#rows");
host.innerHTML = rows.map((row) => {
const u = row.user;
const subtitle = [u.displayName, u.mustChangePassword ? t("Admin.Users.MustChange") : null, u.disabled ? t("Admin.Users.Disabled") : null]
.filter(Boolean).join(" · ");
const quota = u.quotaBytes > 0
? `<div class="progress-cell">${bar(u.usedBytes / u.quotaBytes, u.disabled)}<span class="num nowrap">${escapeHtml(t("Admin.Users.QuotaOf", formatBytes(u.usedBytes), formatBytes(u.quotaBytes)))}</span></div>`
: `<span class="muted">${escapeHtml(u.usedBytes > 0 ? formatBytes(u.usedBytes) : "—")}</span>`;
const seen = row.lastSeen ? `${formatTime(row.lastSeen)}${row.lastClient ? " · " + row.lastClient : ""}` : "—";
const buttons = u.disabled
? `<button class="btn small" data-act="enable" data-i18n="Admin.Users.Enable" data-i18n-title="Admin.Users.Enable.Tip"></button>
<button class="btn small destructive" data-act="delete" data-i18n="Admin.Users.Delete" data-i18n-title="Admin.Users.Delete.Tip"></button>`
: `<button class="btn small" data-act="edit" data-i18n="Admin.Users.Edit" data-i18n-title="Admin.Users.Edit.Tip"></button>
<button class="btn small" data-act="reset" data-i18n="Admin.Users.Reset" data-i18n-title="Admin.Users.Reset.Tip"></button>
${u.id === api.user().id ? "" : `<button class="btn small" data-act="disable" data-i18n="Admin.Users.Disable" data-i18n-title="Admin.Users.Disable.Tip"></button>`}`;
return `
<div class="row${u.disabled ? " dim" : ""}" data-id="${attr(u.id)}">
<span class="who"><span class="avatar ${attr(u.role)}">${escapeHtml(u.username.slice(0, 1).toUpperCase())}</span>
<span class="stack"><strong>${escapeHtml(u.username)}</strong><small>${escapeHtml(subtitle)}</small></span></span>
<span data-i18n="Admin.Role.${cap(u.role)}"></span>
<span>${quota}</span>
<span class="ellipsis">${escapeHtml(seen)}</span>
<span class="num right">${formatNumber(row.uploadsLast30Days)}</span>
<span class="${u.disabled ? "muted" : "state done"}">${u.disabled ? "○" : "●"} <span data-i18n="${u.disabled ? "Admin.Users.Disabled" : "Admin.Users.Active"}"></span></span>
<span class="row-actions">${buttons}</span>
</div>`;
}).join("") || `<div class="empty" data-i18n="Admin.Users.Empty"></div>`;
applyStrings(host);
host.querySelectorAll("[data-act]").forEach((button) => button.addEventListener("click", () => {
const row = users.find((u) => u.user.id === button.closest(".row").dataset.id);
act(button.dataset.act, row.user);
}));
}
async function act(action, user) {
try {
if (action === "edit") return openForm(user);
if (action === "reset") {
const r = await api.post(`/api/v1/users/${user.id}/reset-password`, {});
showPassword(r);
} else if (action === "disable" || action === "enable") {
await api.patch(`/api/v1/users/${user.id}`, { disabled: action === "disable" });
} else if (action === "delete") {
const confirmed = await confirmDialog({
title: t("Admin.Users.DeleteTitle", user.username),
body: t("Admin.Users.DeleteBody"),
confirm: t("Admin.Users.DeleteConfirm"),
confirmTip: t("Admin.Users.Delete.Tip"),
cancel: t("Admin.Common.Keep"),
cancelTip: t("Admin.Common.Keep.Tip"),
typed: user.username,
});
if (!confirmed) return;
await api.del(`/api/v1/users/${user.id}`);
}
await load();
} catch (err) {
toast(errorText(err), true);
}
}
function openForm(user) {
const side = root.querySelector("#side");
const editing = user !== null;
const quotaTb = editing && user.quotaBytes > 0 ? +(user.quotaBytes / TB).toFixed(3) : 0;
const renderNode = editing ? (user.permissions & RENDER_NODE) !== 0 : false;
side.hidden = false;
side.innerHTML = `
<form class="form" novalidate>
<h2 data-i18n="${editing ? "Admin.Users.EditTitle" : "Admin.Users.New"}"></h2>
<label><span data-i18n="Admin.Users.Username"></span>
<input class="input" name="username" required autocomplete="off" value="${attr(user?.username ?? "")}" ${editing ? "disabled" : ""} data-i18n-title="Admin.Users.Username.Tip"></label>
<label><span data-i18n="Admin.Users.DisplayName"></span>
<input class="input" name="displayName" autocomplete="off" value="${attr(user?.displayName ?? "")}" data-i18n-title="Admin.Users.DisplayName.Tip"></label>
<fieldset><legend data-i18n="Admin.Users.Role"></legend>
${ROLES.map((r) => `<label class="check"><input type="radio" name="role" value="${r}" ${(user?.role ?? "editor") === r ? "checked" : ""} data-i18n-title="Admin.Users.Role.${cap(r)}.Tip"><span data-i18n="Admin.Role.${cap(r)}"></span></label>`).join("")}
</fieldset>
<label><span data-i18n="Admin.Users.Quota"></span>
<span class="inline"><input class="input narrow" name="quota" type="number" min="0" step="0.1" value="${quotaTb}" data-i18n-title="Admin.Users.Quota.Tip"><span>TB</span>
<small class="muted">${escapeHtml(t("Admin.Users.FreeOnServer", formatBytes(freeBytes)))}</small></span></label>
${editing ? "" : `
<label><span data-i18n="Admin.Users.TempPassword"></span>
<span class="inline"><input class="input mono" name="password" autocomplete="off" value="${attr(generatePassword())}" data-i18n-title="Admin.Users.TempPassword.Tip">
<button class="btn icon" type="button" id="regenerate" data-i18n-title="Admin.Users.Regenerate.Tip">${icons.refresh}</button></span></label>
<label class="check"><input type="checkbox" checked disabled data-i18n-title="Admin.Users.MustChangeFlag.Tip"><span data-i18n="Admin.Users.MustChangeFlag"></span></label>`}
<label class="check"><input type="checkbox" name="renderNode" ${renderNode ? "checked" : ""} data-i18n-title="Admin.Users.RenderNode.Tip"><span data-i18n="Admin.Users.RenderNode"></span></label>
<div class="error" role="alert"></div>
<div class="buttons">
<button class="btn" type="button" id="close" data-i18n="Admin.Common.Cancel" data-i18n-title="Admin.Common.Cancel.Tip"></button>
<button class="btn primary" type="submit" data-i18n="${editing ? "Admin.Common.Save" : "Admin.Users.Create"}" data-i18n-title="${editing ? "Admin.Common.Save.Tip" : "Admin.Users.Create.Tip"}"></button>
</div>
</form>`;
applyStrings(side);
const form = side.querySelector("form");
side.querySelector("#close").addEventListener("click", () => {
side.hidden = true;
});
side.querySelector("#regenerate")?.addEventListener("click", () => {
form.elements.password.value = generatePassword();
});
form.addEventListener("submit", async (e) => {
e.preventDefault();
const error = form.querySelector(".error");
error.textContent = "";
const data = new FormData(form);
const quotaBytes = Math.round(Number(data.get("quota") || 0) * TB);
try {
if (editing) {
await api.patch(`/api/v1/users/${user.id}`, {
displayName: String(data.get("displayName")), role: data.get("role"), quotaBytes, allowRenderNode: data.get("renderNode") === "on",
});
side.hidden = true;
} else {
const r = await api.post("/api/v1/users", {
username: String(data.get("username")).trim(), displayName: String(data.get("displayName")), role: data.get("role"), quotaBytes,
password: String(data.get("password")), allowRenderNode: data.get("renderNode") === "on",
});
showPassword(r);
}
await load();
} catch (err) {
error.textContent = errorText(err);
}
});
form.querySelector("input:not([disabled])").focus();
}
/** The one-time password of a new or reset account, shown once in the side panel. */
function showPassword(result) {
const side = root.querySelector("#side");
side.hidden = false;
side.innerHTML = `
<div class="form">
<h2>${escapeHtml(result.user.username)}</h2>
<label><span data-i18n="Admin.Users.TempPassword"></span>
<span class="inline"><input class="input mono" readonly value="${attr(result.temporaryPassword)}" data-i18n-title="Admin.Users.TempPassword.Tip">
<button class="btn icon" type="button" id="copy" data-i18n-title="Admin.Users.Copy.Tip">${icons.copy}</button></span></label>
<div class="buttons"><button class="btn" type="button" id="close" data-i18n="Admin.Common.Close" data-i18n-title="Admin.Common.Close.Tip"></button></div>
</div>`;
applyStrings(side);
side.querySelector("#copy").addEventListener("click", async () => {
try {
await navigator.clipboard.writeText(result.temporaryPassword);
toast(t("Admin.Users.Copied"));
} catch {
side.querySelector("input").select();
}
});
side.querySelector("#close").addEventListener("click", () => {
side.hidden = true;
});
}
await load();
}
/** Three groups of four unambiguous characters, like the server's own temporary passwords. */
function generatePassword() {
const alphabet = "abcdefghjkmnpqrstuvwxyz23456789";
const chars = [];
while (chars.length < 12) {
// Bytes at or above 248 (8 × 31) are skipped so every character is equally likely.
for (const b of crypto.getRandomValues(new Uint8Array(16))) {
if (b < 248 && chars.length < 12) chars.push(alphabet[b % alphabet.length]);
}
}
return `${chars.slice(0, 4).join("")}-${chars.slice(4, 8).join("")}-${chars.slice(8).join("")}`;
}
function cap(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
}