Files
crosscode-platform/apps/accounts/frontend/src/app/admin/Admin.tsx
T
joshuaandClaude Opus 5.5 f202a5a88e Accounts 1.0.0 frontend and @crosscode/ui
Sign-in steps (password, sign-up, email code, two-step sign-in and its
setup with recovery codes, privacy notice, news question), forgot and
reset password, the account page, admin (people, deletions, church
profile, linked products, settings, notice, licence, audit) and setup.
Strict CSP with a nonce per page; church colours from the profile.
@crosscode/ui gets its first components (shell, card, fields, buttons).
Plan: roles stay in each product (asked 2026-11-18).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:42:45 +02:00

370 lines
23 KiB
TypeScript

"use client";
import React, { useCallback, useState } from "react";
import { Button, Card, Checkbox, Field, Heading, Notice, Shell } from "@crosscode/ui";
import { useBranding } from "@/components/BrandingProvider";
import { call, selfSignIn } from "@/lib/api";
import { useExternalEffect } from "@/lib/hooks";
const TABS = [
["people", "People"], ["deletions", "Deletion requests"], ["church", "Church profile"], ["linked", "Linked products"],
["signin", "Sign-in settings"], ["messages", "Email and WhatsApp"], ["notice", "Privacy notice"], ["licence", "Licence"], ["audit", "Audit log"],
] as const;
type Tab = (typeof TABS)[number][0];
const when = (iso: string | null | undefined) => (iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "—");
type Flash = (tone: "success" | "error", text: string) => void;
/** Accounts' admin (docs/ACCOUNTS-1.0-PLAN.md §8). Admins only, signed in with their second step. */
export function Admin() {
const branding = useBranding();
const [tab, setTab] = useState<Tab>("people");
const [allowed, setAllowed] = useState<boolean | null>(null);
const [msg, setMsg] = useState<{ tone: "success" | "error"; text: string } | null>(null);
useExternalEffect(() => {
let alive = true;
call("GET", "/admin/licence").then((r) => {
if (!alive) return;
if (r.status === 401) return window.location.assign(selfSignIn("/admin"));
if (!r.ok && r.error.code === "MFA_REQUIRED") return window.location.assign(selfSignIn("/admin", "&acr=mfa"));
setAllowed(r.ok);
});
return () => { alive = false; };
}, []);
const flash: Flash = (tone, text) => setMsg({ tone, text });
if (allowed === null) return <Shell branding={branding} wide><p className="text-gray-600">Loading…</p></Shell>;
if (!allowed) return <Shell branding={branding}><Card><Notice tone="error">Only Accounts admins can open this page.</Notice><a href="/account" className="text-brand underline">Your account</a></Card></Shell>;
return (
<Shell branding={branding} wide aside={<a href="/account" className="text-sm text-brand underline">Your account</a>}>
<h1 className="mb-4 text-2xl font-semibold">Accounts admin</h1>
<nav className="mb-6 flex flex-wrap gap-2" aria-label="Admin sections">
{TABS.map(([id, label]) => (
<button key={id} type="button" onClick={() => { setTab(id); setMsg(null); }} aria-current={tab === id ? "page" : undefined}
className={`rounded-full px-3 py-1.5 text-sm ${tab === id ? "bg-brand text-white" : "border bg-white text-gray-700"}`}>{label}</button>
))}
</nav>
{msg && <Notice tone={msg.tone}>{msg.text}</Notice>}
{tab === "people" && <People flash={flash} />}
{tab === "deletions" && <Deletions flash={flash} />}
{tab === "church" && <Church flash={flash} />}
{tab === "linked" && <Linked flash={flash} />}
{tab === "signin" && <Settings flash={flash} keys={["signup_enabled", "two_factor_required_for_admins", "session_days"]} />}
{tab === "messages" && <Settings flash={flash} keys={["smtp_host", "smtp_port", "smtp_user", "smtp_pass", "smtp_from", "smtp_secure", "wawp_access_token", "wawp_instance_id"]} />}
{tab === "notice" && <NoticeTab flash={flash} />}
{tab === "licence" && <Licence flash={flash} />}
{tab === "audit" && <Audit />}
</Shell>
);
}
// ─── People ──────────────────────────────────────────────────────────────────
type Person = { id: string; name: string; email: string; role: string; status: string; twoFactor: string | null; lastSignInAt: string | null };
type PersonDetail = Person & { phone: string | null; emailVerified: boolean; recoveryCodesLeft: number; createdAt: string; lockedUntil: string | null; signIns: { type: string; at: string; ip: string | null }[] };
function People({ flash }: { flash: Flash }) {
const [q, setQ] = useState("");
const [list, setList] = useState<{ items: Person[]; total: number } | null>(null);
const [open, setOpen] = useState<PersonDetail | null>(null);
const search = useCallback(async (query: string) => {
const r = await call<{ items: Person[]; total: number }>("GET", `/admin/people?q=${encodeURIComponent(query)}`);
if (r.ok) setList(r.data);
}, []);
useExternalEffect(() => { void search(""); }, [search]);
const show = async (id: string) => {
const r = await call<PersonDetail>("GET", `/admin/people/${id}`);
if (r.ok) setOpen(r.data);
};
const act = async (path: string, body: unknown, ok: string) => {
const r = await call(path.endsWith("/role") || path.endsWith("/status") ? "PUT" : "POST", path, body);
if (r.ok) { flash("success", ok); if (open) void show(open.id); void search(q); } else flash("error", r.error.message);
};
return (
<div className="grid gap-6 md:grid-cols-2">
<Card>
<form onSubmit={(e) => { e.preventDefault(); void search(q); }} className="mb-4 flex gap-2">
<input aria-label="Search people" value={q} onChange={(e) => setQ(e.target.value)} placeholder="Name or email" className="flex-1 rounded-lg border px-3 py-2" />
<Button type="submit" variant="secondary">Search</Button>
</form>
<p className="mb-2 text-sm text-gray-500">{list?.total ?? 0} people</p>
<ul className="divide-y">
{list?.items.map((p) => (
<li key={p.id}>
<button type="button" onClick={() => show(p.id)} className="w-full py-2 text-left hover:bg-gray-50">
<span className="block font-medium">{p.name}{p.role === "admin" && <span className="ml-2 rounded bg-brand/10 px-1.5 text-xs text-brand">admin</span>}{p.status !== "active" && <span className="ml-2 text-xs text-amber-700">{p.status}</span>}</span>
<span className="block text-sm text-gray-500">{p.email}</span>
</button>
</li>
))}
</ul>
</Card>
{open && (
<Card>
<Heading sub={open.email}>{open.name}</Heading>
<dl className="mb-4 grid grid-cols-2 gap-y-1 text-sm">
<dt className="text-gray-500">Phone</dt><dd>{open.phone ?? "—"}</dd>
<dt className="text-gray-500">Email confirmed</dt><dd>{open.emailVerified ? "yes" : "no"}</dd>
<dt className="text-gray-500">Two-step sign-in</dt><dd>{open.twoFactor ?? "off"}{open.twoFactor ? ` (${open.recoveryCodesLeft} codes left)` : ""}</dd>
<dt className="text-gray-500">Account since</dt><dd>{when(open.createdAt)}</dd>
<dt className="text-gray-500">Locked until</dt><dd>{when(open.lockedUntil)}</dd>
</dl>
<div className="mb-4 flex flex-wrap gap-2">
{open.twoFactor && <Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/reset-two-factor`, {}, "Two-step sign-in reset. They'll set it up again when they next sign in, if they need it.")}>Reset two-step sign-in</Button>}
{open.lockedUntil && <Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/unlock`, {}, "Unlocked.")}>Unlock</Button>}
<Button variant="secondary" onClick={() => act(`/admin/people/${open.id}/role`, { role: open.role === "admin" ? "member" : "admin" }, "Role changed.")}>{open.role === "admin" ? "Remove admin" : "Make Accounts admin"}</Button>
<Button variant={open.status === "active" ? "danger" : "secondary"} onClick={() => act(`/admin/people/${open.id}/status`, { active: open.status !== "active" }, open.status === "active" ? "Deactivated and signed out everywhere." : "Reactivated.")}>{open.status === "active" ? "Deactivate" : "Reactivate"}</Button>
</div>
<p className="mb-1 text-xs text-gray-500">Roles in each product (an Events supervisor, for example) are set in that product, not here.</p>
<p className="mb-2 mt-4 text-sm font-medium">Recent sign-ins</p>
<ul className="space-y-1 text-sm text-gray-700">{open.signIns.map((s, i) => <li key={i}>{s.type} · {when(s.at)} {s.ip && <span className="text-gray-400">· {s.ip}</span>}</li>)}</ul>
</Card>
)}
</div>
);
}
// ─── Deletions ───────────────────────────────────────────────────────────────
type Deletion = { id: string; status: string; requestedAt: string; products: Record<string, { status: string; product?: string; reason?: string; retryAfter?: string }>; person: { name: string; email: string } };
function Deletions({ flash }: { flash: Flash }) {
const [items, setItems] = useState<Deletion[]>([]);
const load = useCallback(async () => {
const r = await call<{ items: Deletion[] }>("GET", "/admin/deletions");
if (r.ok) setItems(r.data.items);
}, []);
useExternalEffect(() => { void load(); }, [load]);
return (
<Card>
<Heading sub="People who asked to delete their account. They're signed out and can't sign in while this is open.">Deletion requests</Heading>
{!items.length && <p className="text-sm text-gray-500">None waiting.</p>}
<ul className="divide-y">
{items.map((d) => (
<li key={d.id} className="py-3">
<p className="font-medium">{d.person.name} <span className="text-sm font-normal text-gray-500">{d.person.email} · asked {when(d.requestedAt)}</span></p>
{d.status === "waiting_approval" ? (
<div className="mt-2 flex gap-2">
<Button variant="danger" onClick={async () => { const r = await call("POST", `/admin/deletions/${d.id}/approve`); if (r.ok) { flash("success", "Approved: each site is deleting what it holds."); void load(); } else flash("error", r.error.message); }}>Approve</Button>
<Button variant="secondary" onClick={async () => { const r = await call("POST", `/admin/deletions/${d.id}/cancel`); if (r.ok) { flash("success", "Cancelled; the account works again."); void load(); } else flash("error", r.error.message); }}>Cancel</Button>
</div>
) : (
<ul className="mt-2 text-sm text-gray-700">
{Object.entries(d.products).map(([id, s]) => <li key={id}>{s.product ?? id}: {s.status === "deferred" ? `waiting — ${s.reason} (asking again ${when(s.retryAfter)})` : s.status}</li>)}
</ul>
)}
</li>
))}
</ul>
</Card>
);
}
// ─── Church profile ──────────────────────────────────────────────────────────
type ChurchData = { name: string; shortName: string | null; branding: { logoUrl: string | null; colours: { primary: string; accent: string | null } }; contact: { email: string | null; phone: string | null; whatsapp: string | null } };
function Church({ flash }: { flash: Flash }) {
const [c, setC] = useState<ChurchData | null>(null);
const [fields, setFields] = useState<Record<string, string>>({});
useExternalEffect(() => {
let alive = true;
call<ChurchData>("GET", "/admin/church").then((r) => { if (alive && r.ok) setC(r.data); });
return () => { alive = false; };
}, []);
if (!c) return <p className="text-gray-600">Loading…</p>;
const nul = (v: FormDataEntryValue | null) => (v ? String(v) : null);
return (
<Card>
<Heading sub="Shared with all the church's products: the sign-in pages, the website and the app use it.">Church profile</Heading>
<form onSubmit={async (e) => {
e.preventDefault();
const f = new FormData(e.currentTarget);
const r = await call<ChurchData>("PUT", "/admin/church", {
name: f.get("name"), shortName: nul(f.get("shortName")),
branding: { ...c.branding, logoUrl: nul(f.get("logoUrl")), colours: { primary: f.get("primary"), accent: nul(f.get("accent")) } },
contact: { ...c.contact, email: nul(f.get("email")), phone: nul(f.get("phone")), whatsapp: nul(f.get("whatsapp")) },
});
if (r.ok) { setC(r.data); setFields({}); flash("success", "Saved. The church's products are told about the change."); } else { setFields(r.error.fields ?? {}); flash("error", r.error.message); }
}}>
<Field label="Name" name="name" defaultValue={c.name} required error={fields.name} />
<Field label="Short name" name="shortName" defaultValue={c.shortName ?? ""} maxLength={30} hint="For small spaces, like the authenticator app's label." error={fields.shortName} />
<Field label="Logo address (https://…)" name="logoUrl" type="url" defaultValue={c.branding.logoUrl ?? ""} error={fields["branding.logoUrl"]} />
<div className="grid grid-cols-2 gap-4">
<Field label="Main colour" name="primary" type="color" defaultValue={c.branding.colours.primary} />
<Field label="Accent colour" name="accent" type="color" defaultValue={c.branding.colours.accent ?? "#f2a900"} />
</div>
<Field label="Office email" name="email" type="email" defaultValue={c.contact.email ?? ""} error={fields["contact.email"]} />
<Field label="Office phone" name="phone" defaultValue={c.contact.phone ?? ""} hint="With the country code, e.g. +27161234567." error={fields["contact.phone"]} />
<Field label="WhatsApp" name="whatsapp" defaultValue={c.contact.whatsapp ?? ""} error={fields["contact.whatsapp"]} />
<Button type="submit">Save</Button>
</form>
</Card>
);
}
// ─── Linked products ─────────────────────────────────────────────────────────
type LinkedItem = { installId: string; product: string; name: string; url: string; listed: boolean; connectedAt: string | null; signsInHere: boolean };
function Linked({ flash }: { flash: Flash }) {
const [data, setData] = useState<{ hubConnected: boolean; items: LinkedItem[] } | null>(null);
const load = useCallback(async () => {
const r = await call<{ hubConnected: boolean; items: LinkedItem[] }>("GET", "/admin/linked-products");
if (r.ok) setData(r.data);
}, []);
useExternalEffect(() => { void load(); }, [load]);
if (!data) return <p className="text-gray-600">Loading…</p>;
return (
<Card>
<Heading sub="Connected products sign people in here. Usually each product connects from its own settings; you can connect from here too.">Linked products</Heading>
{!data.hubConnected && <Notice tone="warning">Accounts isn&apos;t connected to the Hub yet (Licence).</Notice>}
{!data.items.length && <p className="text-sm text-gray-500">The church has no other Cross Code products yet.</p>}
<ul className="divide-y">
{data.items.map((l) => (
<li key={l.installId} className="flex flex-wrap items-center justify-between gap-2 py-3">
<span><span className="font-medium">{l.name}</span> <span className="text-sm text-gray-500">{l.url.replace(/^https?:\/\//, "")}</span><br />
<span className="text-sm text-gray-600">{l.signsInHere ? `Connected ${when(l.connectedAt)}` : "Not connected"}{!l.listed && " · no longer listed by the Hub"}</span></span>
{l.signsInHere
? <Button variant="secondary" onClick={async () => { if (!window.confirm(`Disconnect ${l.name}? People won't be able to sign in to it until it's connected again.`)) return; const r = await call("POST", `/admin/linked-products/${l.installId}/disconnect`); if (r.ok) { flash("success", "Disconnected."); void load(); } else flash("error", r.error.message); }}>Disconnect</Button>
: <Button disabled={!l.listed} onClick={async () => { const r = await call("POST", `/admin/linked-products/${l.installId}/connect`); if (r.ok) { flash("success", `Connected: ${l.name} signs people in here now.`); void load(); } else flash("error", r.error.message); }}>Connect</Button>}
</li>
))}
</ul>
</Card>
);
}
// ─── Settings ────────────────────────────────────────────────────────────────
const SETTING_LABELS: Record<string, [string, "bool" | "text" | "secret" | "number"]> = {
signup_enabled: ["Members can create their own account", "bool"],
two_factor_required_for_admins: ["Admins must use two-step sign-in", "bool"],
session_days: ['Days "Keep me signed in" lasts', "number"],
smtp_host: ["SMTP server", "text"], smtp_port: ["SMTP port", "number"], smtp_user: ["SMTP user name", "text"], smtp_pass: ["SMTP password", "secret"],
smtp_from: ["Send from (email address)", "text"], smtp_secure: ["Use TLS from the start (port 465)", "bool"],
wawp_access_token: ["WAWP access token", "secret"], wawp_instance_id: ["WAWP instance id", "text"],
};
function Settings({ flash, keys }: { flash: Flash; keys: string[] }) {
const [values, setValues] = useState<Record<string, string | boolean | null> | null>(null);
useExternalEffect(() => {
let alive = true;
call<Record<string, string | boolean | null>>("GET", "/admin/settings").then((r) => { if (alive && r.ok) setValues(r.data); });
return () => { alive = false; };
}, []);
if (!values) return <p className="text-gray-600">Loading…</p>;
const defaults: Record<string, boolean> = { signup_enabled: true, two_factor_required_for_admins: true };
return (
<Card>
<form onSubmit={async (e) => {
e.preventDefault();
const f = new FormData(e.currentTarget);
const body: Record<string, string> = {};
for (const k of keys) {
const kind = SETTING_LABELS[k]![1];
if (kind === "bool") body[k] = f.get(k) === "on" ? "true" : "false";
else body[k] = String(f.get(k) ?? "");
}
const r = await call("PUT", "/admin/settings", body);
if (r.ok) flash("success", "Saved."); else flash("error", r.error.message);
}}>
{keys.map((k) => {
const [label, kind] = SETTING_LABELS[k]!;
const v = values[k];
if (kind === "bool") return <Checkbox key={k} name={k} label={label} defaultChecked={v === null ? defaults[k] ?? false : v === "true"} />;
if (kind === "secret") return <Field key={k} name={k} label={label} type="password" autoComplete="off" placeholder={v ? "Saved — leave empty to keep it" : ""} />;
return <Field key={k} name={k} label={label} type={kind === "number" ? "number" : "text"} defaultValue={typeof v === "string" ? v : ""} />;
})}
<div className="flex gap-2">
<Button type="submit">Save</Button>
{keys.includes("smtp_host") && <Button type="button" variant="secondary" onClick={async () => { const r = await call("POST", "/admin/settings/test-email"); flash(r.ok ? "success" : "error", r.ok ? "A test email is on its way to you." : r.error.message); }}>Send a test email</Button>}
</div>
</form>
</Card>
);
}
// ─── Privacy notice, licence, audit ───────────────────────────────────────────
function NoticeTab({ flash }: { flash: Flash }) {
const [current, setCurrent] = useState<{ version: number; title: string; body: string } | null>(null);
const load = useCallback(async () => {
const r = await call<{ current: { version: number; title: string; body: string } }>("GET", "/admin/notices");
if (r.ok) setCurrent(r.data.current);
}, []);
useExternalEffect(() => { void load(); }, [load]);
if (!current) return <p className="text-gray-600">Loading…</p>;
return (
<Card>
<Heading sub={`Version ${current.version}. Publishing a new version asks everyone to read it the next time they sign in.`}>Privacy notice</Heading>
<form onSubmit={async (e) => {
e.preventDefault();
if (!window.confirm("Publish this as a new version? Everyone will be asked to read it when they next sign in.")) return;
const f = new FormData(e.currentTarget);
const r = await call("POST", "/admin/notices", { title: f.get("title"), body: f.get("body") });
if (r.ok) { flash("success", "Published."); void load(); } else flash("error", r.error.message);
}}>
<Field label="Title" name="title" defaultValue={current.title} required />
<label htmlFor="notice-body" className="mb-1 block text-sm font-medium">Text</label>
<textarea id="notice-body" name="body" defaultValue={current.body} rows={14} className="mb-4 w-full rounded-lg border p-3 text-sm" required />
<Button type="submit">Publish a new version</Button>
</form>
</Card>
);
}
function Licence({ flash }: { flash: Flash }) {
const [s, setS] = useState<{ connected: boolean; state: string; customer: string | null; endsAt: string | null; lastHeartbeatAt: string | null; lastError: string | null } | null>(null);
const load = useCallback(async () => {
const r = await call<NonNullable<typeof s>>("GET", "/admin/licence");
if (r.ok) setS(r.data);
}, []);
useExternalEffect(() => { void load(); }, [load]);
if (!s) return <p className="text-gray-600">Loading…</p>;
return (
<Card>
<Heading sub="Accounts is free with the church's other products. Members can always sign in, whatever the licence says.">Licence</Heading>
<dl className="mb-4 grid grid-cols-2 gap-y-1 text-sm">
<dt className="text-gray-500">Connected to the Hub</dt><dd>{s.connected ? "yes" : "no"}</dd>
<dt className="text-gray-500">Licence</dt><dd>{s.state}</dd>
<dt className="text-gray-500">Customer</dt><dd>{s.customer ?? "—"}</dd>
<dt className="text-gray-500">Last heartbeat</dt><dd>{when(s.lastHeartbeatAt)}</dd>
</dl>
{s.lastError && <Notice tone="warning">{s.lastError}</Notice>}
{!s.connected && (
<form onSubmit={async (e) => {
e.preventDefault();
const r = await call("POST", "/admin/licence", { licenceKey: new FormData(e.currentTarget).get("licenceKey") });
if (r.ok) { flash("success", "Connected to the Hub."); void load(); } else flash("error", r.error.message);
}}>
<Field label="Licence key" name="licenceKey" placeholder="CCA-XXXX-XXXX-XXXX-XXXX" required />
<Button type="submit">Connect</Button>
</form>
)}
</Card>
);
}
function Audit() {
const [items, setItems] = useState<{ id: string; action: string; actorRole: string; targetType: string; targetId: string | null; createdAt: string }[]>([]);
useExternalEffect(() => {
let alive = true;
call<{ items: typeof items }>("GET", "/admin/audit").then((r) => { if (alive && r.ok) setItems(r.data.items); });
return () => { alive = false; };
}, []);
return (
<Card>
<Heading>Audit log</Heading>
<ul className="divide-y text-sm">
{items.map((a) => <li key={a.id} className="flex justify-between gap-3 py-2"><span>{a.action.replace(/_/g, " ")} <span className="text-gray-500">({a.actorRole}{a.targetId ? ` · ${a.targetType}` : ""})</span></span><span className="shrink-0 text-gray-500">{when(a.createdAt)}</span></li>)}
{!items.length && <li className="py-2 text-gray-500">Nothing yet.</li>}
</ul>
</Card>
);
}