/* ═══════════════════════════════════════════════════════════════ ADMIN PANEL Superadmin only, guarded by RequireRole on the route and by requireRole("superadmin") on every endpoint it calls. This page assumes neither: it renders whatever the API gives it and shows whatever the API refuses. Four blocks, deliberately boring: System what's actually running, for when something is off Content row counts, the cheapest "is the database there" Accounts roles, access and live sessions Google groups check someone's groups, re-sync every group account (server/src/accessGroups.js) A group account's role comes from its Google group, so its role select is locked; Disable still works, and sticks. The role select is driven by ROLES from lib/roles.ts, so a new rung on the ladder appears here without this file changing. The legend beside it is the same list: four roles is past the point where "Editor" explains itself. Every account write signs that person out, which the server does rather than this page. Two things you can't do here: edit your own row, or take the last active superadmin away. Both are enforced server-side and mirrored in the disabled states, so the reason shows up before the click rather than after it. ═══════════════════════════════════════════════════════════════ */ import { useCallback, useEffect, useState } from "react"; import { ApiError, del, get, patch, post } from "../../lib/api.ts"; import { isUnauthorized, useAuth } from "../../lib/auth.tsx"; import { useNavigate } from "react-router-dom"; import { ROLES, ROLE_LABELS, ROLE_NOTES, isSuper } from "../../lib/roles.ts"; /* SQLite hands back "2026-09-22 04:11:07": UTC, but without the marker that says so. Left alone, browsers read it as local time and last-login drifts by the timezone offset. */ function when(value) { if (!value) return "-"; const iso = value.includes("T") ? value : `${value.replace(" ", "T")}Z`; const date = new Date(iso); return Number.isNaN(date.getTime()) ? value : date.toLocaleString(); } function uptime(seconds) { if (seconds == null) return "-"; const d = Math.floor(seconds / 86400); const h = Math.floor((seconds % 86400) / 3600); const m = Math.floor((seconds % 3600) / 60); if (d) return `${d}d ${h}h`; if (h) return `${h}h ${m}m`; return `${m}m`; } function Block({ title, note, children }: any) { return (

{title}

{note &&

{note}

}
{children}
); } function Stat({ label, value }) { return (
{label}
{value}
); } /* Google groups: what's set, who a group would let in, and a re-sync of every group account. */ function AccessGroups({ access, onSynced }) { const [email, setEmail] = useState(""); const [busy, setBusy] = useState<"check" | "sync" | null>(null); const [note, setNote] = useState<{ tone: "ok" | "error"; text: string } | null>(null); const [changes, setChanges] = useState([]); const groups = Object.entries(access?.groups ?? {}); async function send(kind: "check" | "sync") { setBusy(kind); setNote(null); setChanges([]); try { if (kind === "check") { const { role } = await post("/admin/panel/access-check", { email }); setNote( role ? { tone: "ok", text: `${email} would sign in as ${ROLE_LABELS[role] ?? role}.` } : { tone: "error", text: `${email} isn't in any of these groups.` }, ); } else { const result = await post("/admin/panel/access-sync", {}); setNote({ tone: result.failed.length ? "error" : "ok", text: `Checked ${result.checked} group account${result.checked === 1 ? "" : "s"}, ` + `${result.changes.length} changed` + (result.failed.length ? `, ${result.failed.length} couldn't be checked.` : "."), }); setChanges([...result.changes, ...result.failed]); onSynced(); } } catch (err) { setNote({ tone: "error", text: err instanceof ApiError ? err.message : "Couldn't reach the server." }); } finally { setBusy(null); } } const button = "btn border border-brand px-4 py-1.5 text-sm text-link transition-colors hover:bg-tint disabled:cursor-default disabled:opacity-50"; return ( {!access?.directory && (

Group lookups aren't set up on the server (GOOGLE_DIRECTORY_AS, docs/google-sign-in.md).

)} {groups.length > 0 ? (
{groups.map(([role, group]) => (
{ROLE_LABELS[role] ?? role}
{group as string}
))}
) : (

No groups set: accounts come from admin-cli only.

)}
setEmail(e.target.value)} className="min-w-0 flex-1 border border-muted/25 bg-surface px-3 py-1.5 text-sm text-body outline-none focus:border-brand focus:ring-2 focus:ring-brand/25 sm:max-w-sm" />
{note && (

{note.text}

)} {changes.length > 0 && ( )}
); } export default function AdminPanel() { const { user: me } = useAuth(); const navigate = useNavigate(); const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); // Which row is mid-request, and what went wrong on it. Scoped to // the row so a failure on one account doesn't blank the table. const [busyId, setBusyId] = useState(null); const [rowError, setRowError] = useState(null); const load = useCallback(async () => { setLoading(true); setError(null); try { setData(await get("/admin/panel/overview", { ttl: 0 })); } catch (err: any) { if (isUnauthorized(err)) return navigate("/admin/login", { replace: true }); setError(err.message || "Couldn't load the panel."); } finally { setLoading(false); } }, [navigate]); useEffect(() => { load(); }, [load]); // After a re-sync: the accounts table again, without the loading // screen (which would clear the sync's result). const refresh = async () => { try { setData(await get("/admin/panel/overview", { ttl: 0 })); } catch { // The table stays as it was; the next load shows any error. } }; /* Replace the one row the server returns rather than refetching the whole overview; the counts didn't change. */ function mergeUser(updated) { setData((current) => current ? { ...current, users: current.users.map((u) => (u.id === updated.id ? updated : u)), } : current, ); } async function run(id, work) { setBusyId(id); setRowError(null); try { mergeUser(await work()); } catch (err: any) { if (isUnauthorized(err)) return navigate("/admin/login", { replace: true }); setRowError({ id, message: err.message || "That didn't work." }); } finally { setBusyId(null); } } const changeRole = (row, role) => run(row.id, async () => (await patch(`/admin/panel/users/${row.id}`, { role })).user); const setActive = (row, is_active) => run( row.id, async () => (await patch(`/admin/panel/users/${row.id}`, { is_active })).user, ); const revoke = (row) => run(row.id, async () => (await del(`/admin/panel/users/${row.id}/sessions`)).user); if (loading) { return (

Loading the panel…

); } if (error) { return (

{error}

); } const { system, content, users, access } = data; const activeSupers = users.filter( (u) => isSuper(u) && u.is_active === 1, ).length; return (

Panel

Accounts and server state. Everything here is superadmin-only.

{system.dbPath && (

{system.dbPath}

)}
{content.map((row) => ( {row.label}{" "} {row.count ?? "-"} ))}
{users.map((row) => { const isMe = row.id === me?.id; const lastSuper = isSuper(row) && row.is_active === 1 && activeSupers <= 1; const locked = isMe || lastSuper; const fromGroup = row.access_source === "group"; const busy = busyId === row.id; return ( ); })}
Account Role Last login Sessions Access
{row.name || row.email} {isMe && ( you )}
{row.name && (
{row.email}
)} {fromGroup && (
Google group {row.group_disabled === 1 && ": in no access group"}
)} {rowError?.id === row.id && (
{rowError.message}
)}
{when(row.last_login_at)} {row.sessions} {row.sessions > 0 && ( )}
{/* Each rung adds to the one above it. Worth stating, because "Editor" doesn't tell you where the line falls. */}
{ROLES.map((role) => (
{ROLE_LABELS[role]}
{ROLE_NOTES[role]}
))}

New accounts are created with admin-cli.js on the server, or by signing in with Google while in one of the groups below.

); }