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>
This commit is contained in:
@@ -9,6 +9,7 @@ import { handle, limit } from '../http.js';
|
||||
import { branding, church } from '../church/profile.js';
|
||||
import { acceptConnect, acceptDisconnect, LinkError } from '../links/connect.js';
|
||||
import { setupNeeded } from '../setup/routes.js';
|
||||
import { currentNotice } from '../privacy/notice.js';
|
||||
|
||||
const strip = (p: string) => p.replace(/^\/api/, '');
|
||||
|
||||
@@ -24,6 +25,12 @@ export function publicRouter(ctx: Ctx) {
|
||||
|
||||
r.get('/v2/branding', handle(async () => ({ ...(await branding(ctx)), setupNeeded: await setupNeeded(ctx) })));
|
||||
|
||||
// The privacy notice, for the sign-up page's link (public).
|
||||
r.get('/v2/notice', handle(async () => {
|
||||
const n = await currentNotice(ctx);
|
||||
return { version: n.version, title: n.title, body: n.body, publishedAt: n.publishedAt };
|
||||
}));
|
||||
|
||||
r.get(strip(CHURCH_PATHS.profile), limit(600), handle(async (_req, res) => {
|
||||
res.set('Cache-Control', 'public, max-age=60');
|
||||
return church(ctx);
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
.next/
|
||||
next-env.d.ts
|
||||
.env*
|
||||
@@ -0,0 +1,17 @@
|
||||
import { defineConfig, globalIgnores } from "eslint/config";
|
||||
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||
import nextTs from "eslint-config-next/typescript";
|
||||
|
||||
// Next.js 16's own flat configs, as Cross Events. Run with `npm run lint`.
|
||||
export default defineConfig([
|
||||
...nextVitals,
|
||||
...nextTs,
|
||||
{
|
||||
rules: {
|
||||
"react-hooks/exhaustive-deps": ["warn", { additionalHooks: "^useExternalEffect$" }],
|
||||
// Logos and QR codes are small and come from the church's own settings.
|
||||
"@next/next/no-img-element": "off",
|
||||
},
|
||||
},
|
||||
globalIgnores([".next/**", "out/**", "next-env.d.ts"]),
|
||||
]);
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
// Everything under /api is the backend (docs/ACCOUNTS-1.0-PLAN.md §1). On a server nginx sends it
|
||||
// there; in development (and when Next is reached directly) this rewrite does.
|
||||
const api = (process.env.ACCOUNTS_API_URL || "http://127.0.0.1:5200").replace(/\/+$/, "");
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
poweredByHeader: false,
|
||||
transpilePackages: ["@crosscode/ui"],
|
||||
async rewrites() {
|
||||
return [{ source: "/api/:path*", destination: `${api}/api/:path*` }];
|
||||
},
|
||||
async headers() {
|
||||
return [{
|
||||
source: "/:path*",
|
||||
headers: [
|
||||
{ key: "X-Robots-Tag", value: "noindex, nofollow" },
|
||||
{ key: "Referrer-Policy", value: "same-origin" },
|
||||
{ key: "X-Content-Type-Options", value: "nosniff" },
|
||||
],
|
||||
}];
|
||||
},
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
@@ -0,0 +1 @@
|
||||
module.exports = { plugins: { tailwindcss: {}, autoprefixer: {} } };
|
||||
@@ -0,0 +1,269 @@
|
||||
"use client";
|
||||
|
||||
import React, { useCallback, useState } from "react";
|
||||
import QRCode from "qrcode";
|
||||
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";
|
||||
|
||||
type Me = {
|
||||
id: string; name: string; email: string; emailVerified: boolean; phone: string | null; role: "member" | "admin";
|
||||
twoFactor: "totp" | "email" | "whatsapp" | null; recoveryCodesLeft: number; news: { email: boolean; whatsapp: boolean };
|
||||
noticeVersionAccepted: number; noticeVersion: number; lastSignInAt: string | null;
|
||||
};
|
||||
type SignIn = { type: string; at: string; ip: string | null; device: string | null; site: string | null };
|
||||
type Export = { id: string; status: string; createdAt: string; readyAt: string | null; expiresAt: string };
|
||||
|
||||
const METHOD = { totp: "an authenticator app", email: "a code by email", whatsapp: "a code on WhatsApp" } as const;
|
||||
const EVENT: Record<string, string> = {
|
||||
sign_in: "Signed in", sign_in_failed: "Wrong password", locked: "Locked after too many tries", password_reset: "Password reset", password_changed: "Password changed",
|
||||
two_factor_on: "Two-step sign-in turned on", two_factor_off: "Two-step sign-in turned off", recovery_code_used: "Recovery code used", recovery_codes_replaced: "New recovery codes",
|
||||
signed_out_everywhere: "Signed out everywhere", email_changed: "Email address changed", account_created: "Account created",
|
||||
};
|
||||
const when = (iso: string | null) => (iso ? new Date(iso).toLocaleString("en-ZA", { day: "numeric", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" }) : "—");
|
||||
|
||||
/** The account page (docs/ACCOUNTS-1.0-PLAN.md §8): everything about one's own account. */
|
||||
export function Account() {
|
||||
const branding = useBranding();
|
||||
const [me, setMe] = useState<Me | null>(null);
|
||||
const [msg, setMsg] = useState<{ tone: "success" | "error"; text: string } | null>(null);
|
||||
|
||||
const load = useCallback(async () => {
|
||||
const r = await call<Me>("GET", "/me");
|
||||
if (r.status === 401) return window.location.assign(selfSignIn("/account"));
|
||||
if (r.ok) setMe(r.data);
|
||||
}, []);
|
||||
useExternalEffect(() => { void load(); }, [load]);
|
||||
|
||||
const done = (text: string) => { setMsg({ tone: "success", text }); void load(); };
|
||||
const fail = (text: string) => setMsg({ tone: "error", text });
|
||||
|
||||
if (!me) return <Shell branding={branding}><p className="text-gray-600">Loading…</p></Shell>;
|
||||
|
||||
const signOut = <a href={`/api/oidc/session/end?client_id=accounts-self&post_logout_redirect_uri=${encodeURIComponent(`${window.location.origin}/signed-out`)}`} className="text-sm text-brand underline">Sign out</a>;
|
||||
return (
|
||||
<Shell branding={branding} wide aside={<div className="flex gap-4">{me.role === "admin" && <a href="/admin" className="text-sm text-brand underline">Admin</a>}{signOut}</div>}>
|
||||
<h1 className="mb-1 text-2xl font-semibold">Your account</h1>
|
||||
<p className="mb-6 text-sm text-gray-600">One account for all of {branding.name}'s sites and apps.</p>
|
||||
{msg && <Notice tone={msg.tone}>{msg.text}</Notice>}
|
||||
<div className="grid gap-6 md:grid-cols-2">
|
||||
<Profile me={me} onDone={done} onFail={fail} />
|
||||
<Security me={me} onDone={done} onFail={fail} />
|
||||
<Privacy me={me} onDone={done} onFail={fail} />
|
||||
<Activity onDone={done} />
|
||||
</div>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
|
||||
type Props = { me: Me; onDone: (t: string) => void; onFail: (t: string) => void };
|
||||
|
||||
function Profile({ me, onDone, onFail }: Props) {
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [changingEmail, setChangingEmail] = useState(false);
|
||||
return (
|
||||
<Card>
|
||||
<Heading>Your details</Heading>
|
||||
<form onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
const f = new FormData(e.currentTarget);
|
||||
setBusy(true);
|
||||
const r = await call("PUT", "/me", { name: f.get("name"), phone: f.get("phone") || null });
|
||||
setBusy(false);
|
||||
if (r.ok) onDone("Your details are saved, and the church's sites have them too.");
|
||||
else onFail(r.error.message);
|
||||
}}>
|
||||
<Field label="Name" name="name" defaultValue={me.name} required autoComplete="name" />
|
||||
<Field label="Mobile number" name="phone" type="tel" defaultValue={me.phone ?? ""} autoComplete="tel" />
|
||||
<Button type="submit" busy={busy}>Save</Button>
|
||||
</form>
|
||||
<div className="mt-6 border-t pt-4">
|
||||
<p className="text-sm text-gray-700">Email address: <strong>{me.email}</strong></p>
|
||||
{!changingEmail ? (
|
||||
<Button variant="link" className="mt-1 text-sm" onClick={() => setChangingEmail(true)}>Change it</Button>
|
||||
) : (
|
||||
<form className="mt-3" onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
const f = new FormData(e.currentTarget);
|
||||
const r = await call("POST", "/me/email", { email: f.get("email"), password: f.get("password") });
|
||||
if (r.ok) { setChangingEmail(false); onDone("Check your new email address for a link to confirm it. Until then you sign in with the old one."); } else onFail(r.error.message);
|
||||
}}>
|
||||
<Field label="New email address" name="email" type="email" required />
|
||||
<Field label="Your password" name="password" type="password" required autoComplete="current-password" />
|
||||
<Button type="submit">Send the link</Button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function Security({ me, onDone, onFail }: Props) {
|
||||
const [setup, setSetup] = useState<{ method: string; secret?: string; otpauthUrl?: string; sentTo?: string; qr?: string } | null>(null);
|
||||
const [codes, setCodes] = useState<string[] | null>(null);
|
||||
|
||||
const start = async (method: string) => {
|
||||
const r = await call<{ method: string; secret?: string; otpauthUrl?: string; sentTo?: string }>("POST", "/me/two-factor/setup", { method });
|
||||
if (!r.ok) return onFail(r.error.message);
|
||||
setSetup({ ...r.data, qr: r.data.otpauthUrl ? await QRCode.toDataURL(r.data.otpauthUrl, { margin: 1, width: 200 }) : undefined });
|
||||
};
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<Heading>Signing in</Heading>
|
||||
<p className="mb-3 text-sm text-gray-700">
|
||||
Two-step sign-in: {me.twoFactor ? <strong>on, with {METHOD[me.twoFactor]}</strong> : <strong>off</strong>}
|
||||
{me.twoFactor && <span className="text-gray-500"> · {me.recoveryCodesLeft} recovery codes left</span>}
|
||||
</p>
|
||||
{codes && (
|
||||
<Notice tone="warning">
|
||||
Save these recovery codes somewhere safe. Each works once; they won't be shown again.
|
||||
<pre className="mt-2 font-mono">{codes.join("\n")}</pre>
|
||||
</Notice>
|
||||
)}
|
||||
{setup ? (
|
||||
<form onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
const r = await call<{ recoveryCodes: string[] }>("POST", "/me/two-factor/confirm", { method: setup.method, code: new FormData(e.currentTarget).get("code") });
|
||||
if (!r.ok) return onFail(r.error.message);
|
||||
setSetup(null);
|
||||
setCodes(r.data.recoveryCodes);
|
||||
onDone("Two-step sign-in is on.");
|
||||
}}>
|
||||
{setup.qr && <img src={setup.qr} alt="QR code for your authenticator app" className="mb-2 h-40 w-40" />}
|
||||
{setup.secret && <p className="mb-3 break-all font-mono text-xs text-gray-600">Key: {setup.secret}</p>}
|
||||
{setup.sentTo && <p className="mb-3 text-sm">We sent a code to <strong>{setup.sentTo}</strong>.</p>}
|
||||
<Field label="Code" name="code" inputMode="numeric" autoComplete="one-time-code" required />
|
||||
<div className="flex gap-2"><Button type="submit">Turn on</Button><Button type="button" variant="secondary" onClick={() => setSetup(null)}>Cancel</Button></div>
|
||||
</form>
|
||||
) : (
|
||||
<div className="mb-4 flex flex-wrap gap-2">
|
||||
<Button variant="secondary" onClick={() => start("totp")}>{me.twoFactor ? "Use an authenticator app" : "Turn on with an app"}</Button>
|
||||
<Button variant="secondary" onClick={() => start("email")}>{me.twoFactor ? "Use email codes" : "Turn on with email"}</Button>
|
||||
</div>
|
||||
)}
|
||||
{me.twoFactor && !setup && (
|
||||
<PasswordAction label="New recovery codes" button="Make new codes" onSubmit={async (password) => {
|
||||
const r = await call<{ recoveryCodes: string[] }>("POST", "/me/recovery-codes", { password });
|
||||
if (r.ok) { setCodes(r.data.recoveryCodes); onDone("New recovery codes made; the old ones no longer work."); } else onFail(r.error.message);
|
||||
}} />
|
||||
)}
|
||||
{me.twoFactor && !setup && me.role !== "admin" && (
|
||||
<PasswordAction label="Turn off two-step sign-in" button="Turn off" danger onSubmit={async (password) => {
|
||||
const r = await call("POST", "/me/two-factor/off", { password });
|
||||
if (r.ok) onDone("Two-step sign-in is off."); else onFail(r.error.message);
|
||||
}} />
|
||||
)}
|
||||
<div className="mt-4 border-t pt-4">
|
||||
<form onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
const f = new FormData(e.currentTarget);
|
||||
const r = await call("POST", "/me/password", { current: f.get("current"), password: f.get("password") });
|
||||
if (r.ok) { e.currentTarget.reset(); onDone("Your password is changed."); } else onFail(r.error.message);
|
||||
}}>
|
||||
<Field label="Current password" name="current" type="password" autoComplete="current-password" required />
|
||||
<Field label="New password" name="password" type="password" autoComplete="new-password" minLength={8} required />
|
||||
<Button type="submit" variant="secondary">Change password</Button>
|
||||
</form>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function PasswordAction({ label, button, danger, onSubmit }: { label: string; button: string; danger?: boolean; onSubmit: (password: string) => void }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
if (!open) return <p className="mb-2"><Button variant="link" className="text-sm" onClick={() => setOpen(true)}>{label}</Button></p>;
|
||||
return (
|
||||
<form className="mb-3 rounded-lg border p-3" onSubmit={(e) => { e.preventDefault(); onSubmit(String(new FormData(e.currentTarget).get("password"))); setOpen(false); }}>
|
||||
<Field label="Your password" name="password" type="password" autoComplete="current-password" required />
|
||||
<div className="flex gap-2"><Button type="submit" variant={danger ? "danger" : "primary"}>{button}</Button><Button type="button" variant="secondary" onClick={() => setOpen(false)}>Cancel</Button></div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function Privacy({ me, onDone, onFail }: Props) {
|
||||
const [exports, setExports] = useState<Export[]>([]);
|
||||
const [confirmDelete, setConfirmDelete] = useState(false);
|
||||
const loadExports = useCallback(async () => {
|
||||
const r = await call<{ items: Export[] }>("GET", "/me/exports");
|
||||
if (r.ok) setExports(r.data.items);
|
||||
}, []);
|
||||
useExternalEffect(() => { void loadExports(); }, [loadExports]);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<Heading>Privacy</Heading>
|
||||
<form onChange={async (e) => {
|
||||
const f = new FormData(e.currentTarget);
|
||||
const r = await call("PUT", "/me/news", { email: f.get("email") === "on", whatsapp: f.get("whatsapp") === "on" });
|
||||
if (r.ok) onDone("Your news choices are saved."); else onFail(r.error.message);
|
||||
}}>
|
||||
<Checkbox name="email" label="Church news by email" defaultChecked={me.news.email} />
|
||||
<Checkbox name="whatsapp" label="Church news on WhatsApp" defaultChecked={me.news.whatsapp} disabled={!me.phone} hint={!me.phone ? "Add your mobile number first." : undefined} />
|
||||
</form>
|
||||
<p className="mb-4 text-sm"><a href="/privacy" className="text-brand underline">Read the privacy notice</a></p>
|
||||
|
||||
<div className="border-t pt-4">
|
||||
<p className="mb-2 text-sm font-medium">Download my data</p>
|
||||
<p className="mb-3 text-sm text-gray-600">Everything the church's sites hold about you, in one file. It takes a few minutes; we'll email you when it's ready.</p>
|
||||
{exports.map((x) => (
|
||||
<p key={x.id} className="mb-2 text-sm">
|
||||
{when(x.createdAt)}: {x.status === "ready" ? <a className="text-brand underline" href={`/api/v2/me/exports/${x.id}/download`}>Download</a> : x.status === "collecting" ? "being put together…" : "expired"}
|
||||
</p>
|
||||
))}
|
||||
<Button variant="secondary" onClick={async () => {
|
||||
const r = await call("POST", "/me/exports");
|
||||
if (r.ok) { onDone("We're putting your data together. We'll email you when it's ready."); void loadExports(); } else onFail(r.error.message);
|
||||
}}>Ask for a copy</Button>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 border-t pt-4">
|
||||
<p className="mb-2 text-sm font-medium">Delete my account</p>
|
||||
{!confirmDelete ? (
|
||||
<Button variant="link" className="text-sm text-red-700" onClick={() => setConfirmDelete(true)}>Delete my account…</Button>
|
||||
) : (
|
||||
<form onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
const r = await call("POST", "/me/delete", { password: new FormData(e.currentTarget).get("password") });
|
||||
// A full page load: the signed-out page has nothing of this session left.
|
||||
// eslint-disable-next-line @next/next/no-location-assign-relative-destination
|
||||
if (r.ok) window.location.assign("/signed-out"); else onFail(r.error.message);
|
||||
}}>
|
||||
<Notice tone="warning">You'll be signed out of all the church's sites straight away. An admin then confirms the deletion, and each site removes what it holds about you (a site may wait until an event you're booked for is over).</Notice>
|
||||
<Field label="Your password" name="password" type="password" autoComplete="current-password" required />
|
||||
<div className="flex gap-2"><Button type="submit" variant="danger">Delete my account</Button><Button type="button" variant="secondary" onClick={() => setConfirmDelete(false)}>Cancel</Button></div>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function Activity({ onDone }: { onDone: (t: string) => void }) {
|
||||
const [items, setItems] = useState<SignIn[]>([]);
|
||||
useExternalEffect(() => {
|
||||
let alive = true;
|
||||
call<{ items: SignIn[] }>("GET", "/me/sign-ins").then((r) => { if (alive && r.ok) setItems(r.data.items); });
|
||||
return () => { alive = false; };
|
||||
}, []);
|
||||
return (
|
||||
<Card>
|
||||
<Heading sub="If you see something you don't recognise, change your password and sign out everywhere.">Recent activity</Heading>
|
||||
<ul className="mb-4 max-h-72 space-y-2 overflow-y-auto text-sm">
|
||||
{items.map((e, i) => (
|
||||
<li key={i} className="flex justify-between gap-3 border-b pb-2 last:border-0">
|
||||
<span>{EVENT[e.type] ?? e.type}{e.site ? <span className="text-gray-500"> · {e.site.replace(/^https?:\/\//, "")}</span> : null}</span>
|
||||
<span className="shrink-0 text-gray-500">{when(e.at)}</span>
|
||||
</li>
|
||||
))}
|
||||
{!items.length && <li className="text-gray-500">Nothing yet.</li>}
|
||||
</ul>
|
||||
<Button variant="secondary" onClick={async () => {
|
||||
const r = await call("POST", "/me/sign-out-everywhere");
|
||||
// eslint-disable-next-line @next/next/no-location-assign-relative-destination
|
||||
if (r.ok) { onDone("You're signed out everywhere."); window.location.assign("/signed-out"); }
|
||||
}}>Sign out everywhere</Button>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Card, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
import { call, selfSignIn } from "@/lib/api";
|
||||
import { useExternalEffect } from "@/lib/hooks";
|
||||
|
||||
export function ConfirmEmail({ token }: { token: string }) {
|
||||
const branding = useBranding();
|
||||
const [state, setState] = useState<{ ok: boolean; text: string } | null>(null);
|
||||
useExternalEffect(() => {
|
||||
let alive = true;
|
||||
call("POST", "/me/email/confirm", { token }).then((r) => {
|
||||
if (!alive) return;
|
||||
if (r.status === 401) return window.location.assign(selfSignIn(`/account/confirm-email?token=${encodeURIComponent(token)}`));
|
||||
setState(r.ok ? { ok: true, text: "Your new email address is confirmed. Sign in with it from now on." } : { ok: false, text: r.error.message });
|
||||
});
|
||||
return () => { alive = false; };
|
||||
}, [token]);
|
||||
return (
|
||||
<Shell branding={branding}>
|
||||
<Card>
|
||||
<Heading>Your email address</Heading>
|
||||
{state ? <Notice tone={state.ok ? "success" : "error"}>{state.text}</Notice> : <p className="text-gray-600">Confirming…</p>}
|
||||
<a href="/account" className="text-brand underline">Back to your account</a>
|
||||
</Card>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { ConfirmEmail } from "./ConfirmEmail";
|
||||
|
||||
export const metadata = { title: "Confirm your email address" };
|
||||
|
||||
export default async function Page({ searchParams }: { searchParams: Promise<{ token?: string }> }) {
|
||||
const { token } = await searchParams;
|
||||
return <ConfirmEmail token={token ?? ""} />;
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { Account } from "./Account";
|
||||
|
||||
export const metadata = { title: "Your account" };
|
||||
|
||||
export default function AccountPage() {
|
||||
return <Account />;
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
"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'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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { Admin } from "./Admin";
|
||||
|
||||
export const metadata = { title: "Admin" };
|
||||
|
||||
export default function AdminPage() {
|
||||
return <Admin />;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
import { call } from "@/lib/api";
|
||||
|
||||
export function Forgot({ uid }: { uid: string | null }) {
|
||||
const branding = useBranding();
|
||||
const [sent, setSent] = useState(false);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
return (
|
||||
<Shell branding={branding}>
|
||||
<Card>
|
||||
<Heading sub="We'll email you a link to choose a new one.">Forgot your password?</Heading>
|
||||
{sent ? (
|
||||
<Notice tone="success">If there's an account with that email address, a link is on its way. It works for an hour. You can close this page: the link brings you back.</Notice>
|
||||
) : (
|
||||
<form onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
const r = await call("POST", "/password/forgot", { email: new FormData(e.currentTarget).get("email"), uid: uid ?? undefined });
|
||||
setBusy(false);
|
||||
if (r.ok) setSent(true); else setError(r.error.message);
|
||||
}}>
|
||||
{error && <Notice tone="error">{error}</Notice>}
|
||||
<Field label="Email address" name="email" type="email" autoComplete="email" required autoFocus />
|
||||
<Button type="submit" busy={busy} className="w-full">Send the link</Button>
|
||||
</form>
|
||||
)}
|
||||
{uid && <p className="mt-4 text-sm"><a href={`/signin?uid=${encodeURIComponent(uid)}`} className="text-brand underline">Back to sign in</a></p>}
|
||||
</Card>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Forgot } from "./Forgot";
|
||||
|
||||
export const metadata = { title: "Forgot your password" };
|
||||
|
||||
export default async function Page({ searchParams }: { searchParams: Promise<{ uid?: string }> }) {
|
||||
const { uid } = await searchParams;
|
||||
return <Forgot uid={uid ?? null} />;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
/* Defaults until the church profile's colour is set (layout.tsx overrides them per request). */
|
||||
:root {
|
||||
--brand: 31 78 121;
|
||||
--brand-dark: 21 55 85;
|
||||
}
|
||||
|
||||
body {
|
||||
@apply bg-gray-50 text-gray-900 antialiased;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import "./globals.css";
|
||||
import { BrandingProvider } from "@/components/BrandingProvider";
|
||||
import { loadBranding, rgbVars } from "@/lib/branding";
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const b = await loadBranding();
|
||||
// Sign-in pages never belong in search results (ROADMAP-v3 §11).
|
||||
return { title: { default: `Sign in · ${b.name}`, template: `%s · ${b.name}` }, robots: { index: false, follow: false } };
|
||||
}
|
||||
|
||||
export default async function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
const nonce = (await headers()).get("x-nonce") ?? undefined;
|
||||
const b = await loadBranding();
|
||||
const vars = rgbVars(b.colours.primary);
|
||||
return (
|
||||
<html lang="en-ZA">
|
||||
<head>
|
||||
<style nonce={nonce}>{`:root{--brand:${vars.brand};--brand-dark:${vars.dark}}`}</style>
|
||||
</head>
|
||||
<body>
|
||||
<BrandingProvider value={{ name: b.name, shortName: b.shortName, logoUrl: b.logoUrl, signupEnabled: b.signupEnabled, setupNeeded: b.setupNeeded }}>
|
||||
{children}
|
||||
</BrandingProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { redirect } from "next/navigation";
|
||||
|
||||
// Opening Accounts directly shows the account page (signing in first if needed).
|
||||
export default function Home() {
|
||||
redirect("/account");
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Card, Heading, Shell } from "@crosscode/ui";
|
||||
import { loadBranding } from "@/lib/branding";
|
||||
|
||||
export const metadata = { title: "Privacy notice" };
|
||||
|
||||
const api = (process.env.ACCOUNTS_API_URL || "http://127.0.0.1:5200").replace(/\/+$/, "");
|
||||
|
||||
export default async function PrivacyPage() {
|
||||
const branding = await loadBranding();
|
||||
const n = await fetch(`${api}/api/v2/notice`, { cache: "no-store" }).then((r) => r.json()).catch(() => null) as { title: string; body: string } | null;
|
||||
return (
|
||||
<Shell branding={branding}>
|
||||
<Card>
|
||||
<Heading>{n?.title ?? "Privacy notice"}</Heading>
|
||||
<div className="whitespace-pre-line text-sm leading-6 text-gray-700">{n?.body ?? "The privacy notice couldn't be loaded. Please try again."}</div>
|
||||
</Card>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
import { call, selfSignIn } from "@/lib/api";
|
||||
|
||||
export function Reset({ token }: { token: string | null }) {
|
||||
const branding = useBranding();
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
return (
|
||||
<Shell branding={branding}>
|
||||
<Card>
|
||||
<Heading sub="At least 8 characters.">Choose a new password</Heading>
|
||||
{error && <Notice tone="error">{error}</Notice>}
|
||||
<form onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
setBusy(true);
|
||||
const r = await call<{ uid: string | null }>("POST", "/password/reset", { token, password: new FormData(e.currentTarget).get("password") });
|
||||
setBusy(false);
|
||||
if (!r.ok) return setError(r.error.message);
|
||||
// Back to the sign-in it started from (and on to that site), or to the account page.
|
||||
window.location.assign(r.data.uid ? `/signin?uid=${encodeURIComponent(r.data.uid)}` : selfSignIn("/account"));
|
||||
}}>
|
||||
<Field label="New password" name="password" type="password" autoComplete="new-password" required minLength={8} autoFocus />
|
||||
<Button type="submit" busy={busy} className="w-full">Save and sign in</Button>
|
||||
</form>
|
||||
</Card>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { Reset } from "./Reset";
|
||||
|
||||
export const metadata = { title: "Choose a new password" };
|
||||
|
||||
export default async function Page({ searchParams }: { searchParams: Promise<{ token?: string }> }) {
|
||||
const { token } = await searchParams;
|
||||
return <Reset token={token ?? null} />;
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import type { MetadataRoute } from "next";
|
||||
|
||||
// Accounts is never indexed (ROADMAP-v3 §11).
|
||||
export default function robots(): MetadataRoute.Robots {
|
||||
return { rules: [{ userAgent: "*", disallow: "/" }] };
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import { Button, Card, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
import { call, type ApiError } from "@/lib/api";
|
||||
import { useExternalEffect } from "@/lib/hooks";
|
||||
|
||||
type Status = { needed: boolean; hubConnected: boolean; adminEmail: string | null };
|
||||
|
||||
/** First run: the church's name, the first admin and the licence key (docs/ACCOUNTS-1.0-PLAN.md §8). */
|
||||
export function Setup() {
|
||||
const branding = useBranding();
|
||||
const [status, setStatus] = useState<Status | null>(null);
|
||||
const [error, setError] = useState<ApiError | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
useExternalEffect(() => {
|
||||
let alive = true;
|
||||
call<Status>("GET", "/setup").then((r) => { if (alive && r.ok) setStatus(r.data); });
|
||||
return () => { alive = false; };
|
||||
}, []);
|
||||
|
||||
const f = (n: string) => error?.fields?.[n] ?? null;
|
||||
return (
|
||||
<Shell branding={branding}>
|
||||
<Card>
|
||||
<Heading sub="Your church's sign-in for its website, app and Cross Events.">Set up Accounts</Heading>
|
||||
{!status ? <p className="text-gray-600">Loading…</p> : !status.needed ? (
|
||||
<Notice tone="info">Accounts is already set up. <a href="/account" className="underline">Sign in</a></Notice>
|
||||
) : (
|
||||
<form onSubmit={async (e) => {
|
||||
e.preventDefault();
|
||||
const d = new FormData(e.currentTarget);
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const r = await call<{ next: string }>("POST", "/setup", { churchName: d.get("churchName"), name: d.get("name"), email: d.get("email"), password: d.get("password"), licenceKey: d.get("licenceKey") || undefined });
|
||||
setBusy(false);
|
||||
if (r.ok) window.location.assign(r.data.next); else setError(r.error);
|
||||
}}>
|
||||
{error && !error.fields && <Notice tone="error">{error.message}</Notice>}
|
||||
<Field label="The church's name" name="churchName" required error={f("churchName")} />
|
||||
<Field label="Your name" name="name" required autoComplete="name" error={f("name")} />
|
||||
<Field label="Your email address" name="email" type="email" required autoComplete="email" defaultValue={status.adminEmail ?? ""} error={f("email")} />
|
||||
<Field label="Password" name="password" type="password" required minLength={8} autoComplete="new-password" error={f("password")} hint="At least 8 characters. You'll also set up two-step sign-in." />
|
||||
{!status.hubConnected && <Field label="Licence key" name="licenceKey" required placeholder="CCA-XXXX-XXXX-XXXX-XXXX" error={f("licenceKey")} hint="From your provider." />}
|
||||
<Button type="submit" busy={busy} className="w-full">Set up and sign in</Button>
|
||||
</form>
|
||||
)}
|
||||
</Card>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { Setup } from "./Setup";
|
||||
|
||||
export const metadata = { title: "Set up Accounts" };
|
||||
|
||||
export default function SetupPage() {
|
||||
return <Setup />;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
"use client";
|
||||
|
||||
import { Card, Heading, Shell } from "@crosscode/ui";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
import { selfSignIn } from "@/lib/api";
|
||||
|
||||
export default function SignedOutPage() {
|
||||
const branding = useBranding();
|
||||
return (
|
||||
<Shell branding={branding}>
|
||||
<Card>
|
||||
<Heading sub={`You've been signed out of all of ${branding.name}'s sites.`}>You're signed out</Heading>
|
||||
<a href={selfSignIn("/account")} className="text-brand underline">Sign in again</a>
|
||||
</Card>
|
||||
</Shell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import QRCode from "qrcode";
|
||||
import { Button, Card, Checkbox, Field, Heading, Notice, Shell } from "@crosscode/ui";
|
||||
import { useBranding } from "@/components/BrandingProvider";
|
||||
import { call, type ApiError } from "@/lib/api";
|
||||
import { useExternalEffect } from "@/lib/hooks";
|
||||
|
||||
type State = {
|
||||
uid: string;
|
||||
stage: "password" | "verify_email" | "two_factor" | "setup_two_factor" | "notice" | "news" | "done";
|
||||
product: string;
|
||||
signupEnabled: boolean;
|
||||
loginHint?: string | null;
|
||||
name?: string;
|
||||
email?: string;
|
||||
sentTo?: string;
|
||||
method?: "totp" | "email" | "whatsapp";
|
||||
methods?: string[];
|
||||
why?: "admin" | "product";
|
||||
notice?: { version: number; title: string; body: string };
|
||||
updated?: boolean;
|
||||
redirectTo?: string;
|
||||
recoveryCodes?: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* One sign-in, step by step (docs/ACCOUNTS-1.0-PLAN.md §5). The backend says which step comes next;
|
||||
* when it's done, the browser goes back to the product it came from.
|
||||
*/
|
||||
export function SignIn({ uid }: { uid: string }) {
|
||||
const branding = useBranding();
|
||||
const [state, setState] = useState<State | null>(null);
|
||||
const [error, setError] = useState<ApiError | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [mode, setMode] = useState<"signin" | "signup">("signin");
|
||||
const [codes, setCodes] = useState<{ codes: string[]; next: string } | null>(null);
|
||||
|
||||
const apply = (s: State) => {
|
||||
if (s.stage === "done" && s.redirectTo) {
|
||||
if (s.recoveryCodes?.length) setCodes({ codes: s.recoveryCodes, next: s.redirectTo });
|
||||
else window.location.assign(s.redirectTo);
|
||||
return;
|
||||
}
|
||||
setState(s);
|
||||
};
|
||||
|
||||
useExternalEffect(() => {
|
||||
let alive = true;
|
||||
call<State>("GET", `/interaction/${encodeURIComponent(uid)}`).then((r) => {
|
||||
if (!alive) return;
|
||||
if (r.ok) apply(r.data);
|
||||
else setError(r.error);
|
||||
});
|
||||
return () => { alive = false; };
|
||||
}, [uid]);
|
||||
|
||||
const submit = async (path: string, body: unknown) => {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const r = await call<State>("POST", `/interaction/${encodeURIComponent(uid)}${path}`, body);
|
||||
setBusy(false);
|
||||
if (r.ok) apply(r.data);
|
||||
else setError(r.error);
|
||||
return r;
|
||||
};
|
||||
|
||||
const frame = (children: React.ReactNode) => <Shell branding={branding}><Card>{children}</Card></Shell>;
|
||||
|
||||
if (codes) {
|
||||
return frame(<RecoveryCodes codes={codes.codes} onDone={() => window.location.assign(codes.next)} />);
|
||||
}
|
||||
if (!state) {
|
||||
return frame(error ? (
|
||||
<>
|
||||
<Heading>We couldn't continue</Heading>
|
||||
<Notice tone="error">{error.message}</Notice>
|
||||
</>
|
||||
) : <p className="text-gray-600">Loading…</p>);
|
||||
}
|
||||
|
||||
const err = error ? <Notice tone="error">{error.message}</Notice> : null;
|
||||
const fieldError = (name: string) => error?.fields?.[name] ?? null;
|
||||
|
||||
switch (state.stage) {
|
||||
case "password":
|
||||
return frame(mode === "signin"
|
||||
? <PasswordStep state={state} busy={busy} err={err} onSubmit={(b) => submit("/password", b)} onSignUp={() => { setError(null); setMode("signup"); }} />
|
||||
: <SignUpStep busy={busy} err={err} fieldError={fieldError} onSubmit={(b) => submit("/signup", b)} onBack={() => { setError(null); setMode("signin"); }} />);
|
||||
case "verify_email":
|
||||
return frame(<CodeStep title="Check your email" sub={<>We sent a 6-digit code to <strong>{state.sentTo}</strong>. Enter it to confirm your email address.</>} busy={busy} err={err} onSubmit={(code) => submit("/verify-email", { code })} onResend={() => submit("/resend", {})} />);
|
||||
case "two_factor":
|
||||
return frame(<TwoFactorStep state={state} busy={busy} err={err} onSubmit={(b) => submit("/two-factor", b)} onResend={() => submit("/resend", {})} />);
|
||||
case "setup_two_factor":
|
||||
return frame(<SetupStep uid={uid} state={state} busy={busy} err={err} setError={setError} onConfirm={(b) => submit("/two-factor/setup/confirm", b)} />);
|
||||
case "notice":
|
||||
return frame(<NoticeStep state={state} busy={busy} err={err} onAccept={() => submit("/notice", { version: state.notice!.version })} />);
|
||||
case "news":
|
||||
return frame(<NewsStep busy={busy} err={err} onSubmit={(b) => submit("/news", b)} />);
|
||||
default:
|
||||
return frame(<p className="text-gray-600">Taking you back…</p>);
|
||||
}
|
||||
}
|
||||
|
||||
function PasswordStep({ state, busy, err, onSubmit, onSignUp }: { state: State; busy: boolean; err: React.ReactNode; onSubmit: (b: object) => void; onSignUp: () => void }) {
|
||||
const branding = useBranding();
|
||||
return (
|
||||
<form onSubmit={(e) => { e.preventDefault(); const f = new FormData(e.currentTarget); onSubmit({ email: f.get("email"), password: f.get("password"), remember: f.get("remember") === "on" }); }}>
|
||||
<Heading sub={`to continue to ${state.product}`}>Sign in to {branding.name}</Heading>
|
||||
{err}
|
||||
<Field label="Email address" name="email" type="email" autoComplete="username" required defaultValue={state.loginHint ?? ""} />
|
||||
<Field label="Password" name="password" type="password" autoComplete="current-password" required />
|
||||
<Checkbox name="remember" label="Keep me signed in on this device" defaultChecked />
|
||||
<Button type="submit" busy={busy} className="w-full">Sign in</Button>
|
||||
<div className="mt-4 flex flex-wrap justify-between gap-2 text-sm">
|
||||
<a href={`/forgot?uid=${encodeURIComponent(state.uid)}`} className="text-brand underline">Forgot your password?</a>
|
||||
{state.signupEnabled && <button type="button" onClick={onSignUp} className="text-brand underline">Create an account</button>}
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function SignUpStep({ busy, err, fieldError, onSubmit, onBack }: { busy: boolean; err: React.ReactNode; fieldError: (n: string) => string | null; onSubmit: (b: object) => void; onBack: () => void }) {
|
||||
const branding = useBranding();
|
||||
const [phone, setPhone] = useState("");
|
||||
return (
|
||||
<form onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const f = new FormData(e.currentTarget);
|
||||
onSubmit({ name: f.get("name"), email: f.get("email"), phone: f.get("phone") || undefined, password: f.get("password"), acceptNotice: f.get("acceptNotice") === "on", newsEmail: f.get("newsEmail") === "on", newsWhatsApp: f.get("newsWhatsApp") === "on", remember: true });
|
||||
}}>
|
||||
<Heading sub={`One account for all of ${branding.name}'s sites and apps.`}>Create your account</Heading>
|
||||
{err}
|
||||
<Field label="Your name" name="name" autoComplete="name" required error={fieldError("name")} />
|
||||
<Field label="Email address" name="email" type="email" autoComplete="email" required error={fieldError("email")} />
|
||||
<Field label="Mobile number (optional)" name="phone" type="tel" autoComplete="tel" value={phone} onChange={(e) => setPhone(e.target.value)} error={fieldError("phone")} hint="For WhatsApp messages, if you'd like them." />
|
||||
<Field label="Password" name="password" type="password" autoComplete="new-password" required minLength={8} error={fieldError("password")} hint="At least 8 characters." />
|
||||
<Checkbox name="newsEmail" label="Send me church news by email" />
|
||||
{phone && <Checkbox name="newsWhatsApp" label="Send me church news on WhatsApp" />}
|
||||
<Checkbox name="acceptNotice" required label={<>I've read the <a href="/privacy" target="_blank" className="text-brand underline">privacy notice</a></>} hint={fieldError("acceptNotice") ?? undefined} />
|
||||
<Button type="submit" busy={busy} className="w-full">Create account</Button>
|
||||
<p className="mt-4 text-sm"><button type="button" onClick={onBack} className="text-brand underline">I already have an account</button></p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function CodeStep({ title, sub, busy, err, onSubmit, onResend }: { title: string; sub: React.ReactNode; busy: boolean; err: React.ReactNode; onSubmit: (code: string) => void; onResend?: () => void }) {
|
||||
return (
|
||||
<form onSubmit={(e) => { e.preventDefault(); onSubmit(String(new FormData(e.currentTarget).get("code") ?? "")); }}>
|
||||
<Heading sub={sub}>{title}</Heading>
|
||||
{err}
|
||||
<Field label="Code" name="code" inputMode="numeric" autoComplete="one-time-code" pattern="[0-9 ]{6,7}" required autoFocus />
|
||||
<Button type="submit" busy={busy} className="w-full">Continue</Button>
|
||||
{onResend && <p className="mt-4 text-sm"><button type="button" onClick={onResend} className="text-brand underline">Send a new code</button></p>}
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function TwoFactorStep({ state, busy, err, onSubmit, onResend }: { state: State; busy: boolean; err: React.ReactNode; onSubmit: (b: object) => void; onResend: () => void }) {
|
||||
const [recovery, setRecovery] = useState(false);
|
||||
if (recovery) {
|
||||
return (
|
||||
<form onSubmit={(e) => { e.preventDefault(); onSubmit({ recoveryCode: new FormData(e.currentTarget).get("recoveryCode") }); }}>
|
||||
<Heading sub="One of the recovery codes you saved when you turned on two-step sign-in. Each works once.">Use a recovery code</Heading>
|
||||
{err}
|
||||
<Field label="Recovery code" name="recoveryCode" autoComplete="off" required autoFocus />
|
||||
<Button type="submit" busy={busy} className="w-full">Continue</Button>
|
||||
<p className="mt-4 text-sm"><button type="button" onClick={() => setRecovery(false)} className="text-brand underline">Use a code instead</button></p>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
const sub = state.method === "totp" ? "Enter the 6-digit code from your authenticator app." : <>We sent a 6-digit code to <strong>{state.sentTo}</strong>.</>;
|
||||
return (
|
||||
<>
|
||||
<CodeStep title="Second step" sub={sub} busy={busy} err={err} onSubmit={(code) => onSubmit({ code })} onResend={state.method === "totp" ? undefined : onResend} />
|
||||
<p className="mt-2 text-sm"><button type="button" onClick={() => setRecovery(true)} className="text-brand underline">Use a recovery code</button></p>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function SetupStep({ uid, state, busy, err, setError, onConfirm }: { uid: string; state: State; busy: boolean; err: React.ReactNode; setError: (e: ApiError | null) => void; onConfirm: (b: object) => void }) {
|
||||
const [started, setStarted] = useState<{ method: string; secret?: string; otpauthUrl?: string; sentTo?: string } | null>(null);
|
||||
const [qr, setQr] = useState<string | null>(null);
|
||||
const start = async (method: string) => {
|
||||
setError(null);
|
||||
const r = await call<{ method: string; secret?: string; otpauthUrl?: string; sentTo?: string }>("POST", `/interaction/${encodeURIComponent(uid)}/two-factor/setup`, { method });
|
||||
if (!r.ok) return setError(r.error);
|
||||
setStarted(r.data);
|
||||
if (r.data.otpauthUrl) setQr(await QRCode.toDataURL(r.data.otpauthUrl, { margin: 1, width: 200 }));
|
||||
};
|
||||
const why = state.why === "admin" ? "Admins must use a second step when they sign in." : `${state.product} asks for a second step when you sign in.`;
|
||||
if (!started) {
|
||||
const labels: Record<string, [string, string]> = {
|
||||
totp: ["An authenticator app", "Google Authenticator, Microsoft Authenticator, 1Password… Most secure, works without signal."],
|
||||
email: ["A code by email", `Sent to ${state.email}.`],
|
||||
whatsapp: ["A code on WhatsApp", "Sent to your mobile number."],
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<Heading sub={why}>Set up two-step sign-in</Heading>
|
||||
{err}
|
||||
<div className="space-y-2">
|
||||
{(state.methods ?? []).map((m) => (
|
||||
<button key={m} type="button" onClick={() => start(m)} className="w-full rounded-lg border p-3 text-left hover:border-brand">
|
||||
<span className="block font-medium">{labels[m]?.[0] ?? m}</span>
|
||||
<span className="block text-sm text-gray-600">{labels[m]?.[1]}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<form onSubmit={(e) => { e.preventDefault(); onConfirm({ method: started.method, code: new FormData(e.currentTarget).get("code") }); }}>
|
||||
<Heading sub={started.method === "totp" ? "Scan this with your authenticator app, then enter the code it shows." : <>We sent a code to <strong>{started.sentTo}</strong>.</>}>
|
||||
{started.method === "totp" ? "Scan the QR code" : "Enter the code"}
|
||||
</Heading>
|
||||
{err}
|
||||
{qr && <img src={qr} alt="QR code for your authenticator app" className="mx-auto mb-3 h-48 w-48" />}
|
||||
{started.secret && <p className="mb-4 break-all text-center font-mono text-sm text-gray-600">Or type this key: {started.secret}</p>}
|
||||
<Field label="Code" name="code" inputMode="numeric" autoComplete="one-time-code" required autoFocus />
|
||||
<Button type="submit" busy={busy} className="w-full">Turn on</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
function RecoveryCodes({ codes, onDone }: { codes: string[]; onDone: () => void }) {
|
||||
const text = codes.join("\n");
|
||||
return (
|
||||
<>
|
||||
<Heading sub="If you lose your phone, one of these lets you sign in. Each works once. Keep them somewhere safe: we can't show them again.">Save your recovery codes</Heading>
|
||||
<pre className="mb-4 rounded-lg bg-gray-50 p-4 text-center font-mono text-sm leading-7">{text}</pre>
|
||||
<div className="mb-4 flex gap-2">
|
||||
<Button type="button" variant="secondary" onClick={() => navigator.clipboard?.writeText(text)}>Copy</Button>
|
||||
<a className="rounded-lg border px-4 py-2.5 text-sm" download="recovery-codes.txt" href={`data:text/plain;charset=utf-8,${encodeURIComponent(text)}`}>Download</a>
|
||||
</div>
|
||||
<Button type="button" className="w-full" onClick={onDone}>I've saved them</Button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function NoticeStep({ state, busy, err, onAccept }: { state: State; busy: boolean; err: React.ReactNode; onAccept: () => void }) {
|
||||
return (
|
||||
<>
|
||||
<Heading sub={state.updated ? "Our privacy notice has changed. Please read it before you carry on." : "Please read our privacy notice before you carry on."}>{state.notice!.title}</Heading>
|
||||
{err}
|
||||
<div className="mb-4 max-h-80 overflow-y-auto whitespace-pre-line rounded-lg border bg-gray-50 p-4 text-sm text-gray-700">{state.notice!.body}</div>
|
||||
<Button type="button" busy={busy} className="w-full" onClick={onAccept}>I've read it</Button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function NewsStep({ busy, err, onSubmit }: { busy: boolean; err: React.ReactNode; onSubmit: (b: object) => void }) {
|
||||
const branding = useBranding();
|
||||
return (
|
||||
<form onSubmit={(e) => { e.preventDefault(); const f = new FormData(e.currentTarget); onSubmit({ email: f.get("email") === "on", whatsapp: f.get("whatsapp") === "on" }); }}>
|
||||
<Heading sub="You can change this at any time on your account page.">Would you like news from {branding.name}?</Heading>
|
||||
{err}
|
||||
<Checkbox name="email" label="Yes, by email" />
|
||||
<Checkbox name="whatsapp" label="Yes, on WhatsApp" hint="If your mobile number is on your account." />
|
||||
<Button type="submit" busy={busy} className="w-full">Continue</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { SignIn } from "./SignIn";
|
||||
|
||||
export const metadata = { title: "Sign in" };
|
||||
|
||||
// /signin?uid=… is a sign-in a product started; without one, sign in to the account page.
|
||||
export default async function SignInPage({ searchParams }: { searchParams: Promise<{ uid?: string }> }) {
|
||||
const { uid } = await searchParams;
|
||||
if (!uid || !/^[A-Za-z0-9_-]{10,64}$/.test(uid)) redirect("/api/self/signin?returnTo=%2Faccount");
|
||||
return <SignIn uid={uid} />;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import React, { createContext, useContext } from "react";
|
||||
|
||||
export type ClientBranding = { name: string; shortName: string | null; logoUrl: string | null; signupEnabled: boolean; setupNeeded: boolean };
|
||||
|
||||
const Ctx = createContext<ClientBranding>({ name: "Sign in", shortName: null, logoUrl: null, signupEnabled: true, setupNeeded: false });
|
||||
|
||||
export function BrandingProvider({ value, children }: { value: ClientBranding; children: React.ReactNode }) {
|
||||
return <Ctx.Provider value={value}>{children}</Ctx.Provider>;
|
||||
}
|
||||
|
||||
export const useBranding = () => useContext(Ctx);
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* Calls to the backend from the browser (same address, under /api). Errors come back as
|
||||
* { error: { code, message, fields? } }; `call` returns them instead of throwing.
|
||||
*/
|
||||
export type ApiError = { code: string; message: string; fields?: Record<string, string> };
|
||||
export type ApiResult<T> = { ok: true; status: number; data: T } | { ok: false; status: number; error: ApiError };
|
||||
|
||||
export async function call<T = Record<string, unknown>>(method: "GET" | "POST" | "PUT" | "DELETE", path: string, body?: unknown): Promise<ApiResult<T>> {
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(`/api/v2${path}`, {
|
||||
method,
|
||||
credentials: "same-origin",
|
||||
headers: body !== undefined ? { "Content-Type": "application/json" } : undefined,
|
||||
body: body !== undefined ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
} catch {
|
||||
return { ok: false, status: 0, error: { code: "OFFLINE", message: "We couldn't reach the server. Check your connection and try again." } };
|
||||
}
|
||||
const json = (await res.json().catch(() => ({}))) as { error?: ApiError };
|
||||
if (!res.ok) return { ok: false, status: res.status, error: json.error ?? { code: "ERROR", message: "Something went wrong. Please try again." } };
|
||||
return { ok: true, status: res.status, data: json as T };
|
||||
}
|
||||
|
||||
/** Where to sign in to Accounts' own pages, coming back to `returnTo`. */
|
||||
export const selfSignIn = (returnTo: string, extra = "") => `/api/self/signin?returnTo=${encodeURIComponent(returnTo)}${extra}`;
|
||||
@@ -0,0 +1,30 @@
|
||||
/** The church's branding from the backend, for the server-rendered frame of every page. */
|
||||
export type BrandingData = {
|
||||
name: string;
|
||||
shortName: string | null;
|
||||
logoUrl: string | null;
|
||||
colours: { primary: string; accent: string | null };
|
||||
signupEnabled: boolean;
|
||||
setupNeeded: boolean;
|
||||
};
|
||||
|
||||
const api = (process.env.ACCOUNTS_API_URL || "http://127.0.0.1:5200").replace(/\/+$/, "");
|
||||
|
||||
export async function loadBranding(): Promise<BrandingData> {
|
||||
try {
|
||||
const res = await fetch(`${api}/api/v2/branding`, { cache: "no-store" });
|
||||
if (res.ok) return (await res.json()) as BrandingData;
|
||||
} catch {
|
||||
// The backend is starting or down: plain defaults, the page still works.
|
||||
}
|
||||
return { name: "Sign in", shortName: null, logoUrl: null, colours: { primary: "#1f4e79", accent: null }, signupEnabled: true, setupNeeded: false };
|
||||
}
|
||||
|
||||
/** "#1f4e79" → "31 78 121" (Tailwind's rgb(var(--brand) / alpha)), and a darker shade for hover. */
|
||||
export function rgbVars(hex: string): { brand: string; dark: string } {
|
||||
const m = /^#([0-9a-f]{6})$/i.exec(hex) ?? ["", "1f4e79"];
|
||||
const n = parseInt(m[1]!, 16);
|
||||
const [r, g, b] = [(n >> 16) & 255, (n >> 8) & 255, n & 255];
|
||||
const d = (x: number) => Math.round(x * 0.8);
|
||||
return { brand: `${r} ${g} ${b}`, dark: `${d(r)} ${d(g)} ${d(b)}` };
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { useEffect, type DependencyList } from "react";
|
||||
|
||||
/**
|
||||
* `useEffect` for loading from the API and setting state from it (as Cross Events' lib/hooks.ts):
|
||||
* the React Compiler lint can't tell that apart from state derived from other state.
|
||||
*/
|
||||
export function useExternalEffect(run: () => void | (() => void) | Promise<unknown>, deps: DependencyList) {
|
||||
useEffect(() => {
|
||||
const out = run();
|
||||
return typeof out === "function" ? out : undefined;
|
||||
// The caller's deps, checked at the call site by exhaustive-deps (additionalHooks).
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, deps);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { NextResponse, type NextRequest } from "next/server";
|
||||
|
||||
/**
|
||||
* A strict Content-Security-Policy with a fresh nonce per page (docs/ACCOUNTS-1.0-PLAN.md §10):
|
||||
* no inline scripts or styles except Next's own and the church's colours, both carrying the nonce.
|
||||
* Sign-in pages never load anything from another site.
|
||||
*/
|
||||
export function proxy(request: NextRequest) {
|
||||
const nonce = Buffer.from(crypto.randomUUID()).toString("base64");
|
||||
const dev = process.env.NODE_ENV === "development";
|
||||
const csp = [
|
||||
"default-src 'self'",
|
||||
`script-src 'self' 'nonce-${nonce}' 'strict-dynamic'${dev ? " 'unsafe-eval'" : ""}`,
|
||||
`style-src 'self' 'nonce-${nonce}'`,
|
||||
"img-src 'self' https: data:",
|
||||
"font-src 'self'",
|
||||
"connect-src 'self'",
|
||||
"object-src 'none'",
|
||||
"base-uri 'self'",
|
||||
"form-action 'self'",
|
||||
"frame-ancestors 'none'",
|
||||
].join("; ");
|
||||
const headers = new Headers(request.headers);
|
||||
headers.set("x-nonce", nonce);
|
||||
headers.set("Content-Security-Policy", csp);
|
||||
const res = NextResponse.next({ request: { headers } });
|
||||
res.headers.set("Content-Security-Policy", csp);
|
||||
return res;
|
||||
}
|
||||
|
||||
export const config = {
|
||||
matcher: [{ source: "/((?!api|_next/static|_next/image|favicon.ico).*)", missing: [{ type: "header", key: "next-router-prefetch" }] }],
|
||||
};
|
||||
@@ -0,0 +1,13 @@
|
||||
/** @type {import('tailwindcss').Config} */
|
||||
// The church's colour is a CSS variable set per request in layout.tsx (from the church profile).
|
||||
module.exports = {
|
||||
content: ["./src/**/*.{ts,tsx}", "../../../packages/ui/src/**/*.{ts,tsx}"],
|
||||
theme: {
|
||||
extend: {
|
||||
colors: {
|
||||
brand: { DEFAULT: "rgb(var(--brand) / <alpha-value>)", dark: "rgb(var(--brand-dark) / <alpha-value>)" },
|
||||
},
|
||||
},
|
||||
},
|
||||
plugins: [],
|
||||
};
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"lib": ["dom", "dom.iterable", "esnext"],
|
||||
"allowJs": false,
|
||||
"skipLibCheck": true,
|
||||
"strict": true,
|
||||
"noEmit": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "bundler",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"jsx": "react-jsx",
|
||||
"incremental": true,
|
||||
"plugins": [{ "name": "next" }],
|
||||
"paths": { "@/*": ["./src/*"] }
|
||||
},
|
||||
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts", ".next/dev/types/**/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
@@ -109,6 +109,17 @@ What Accounts holds (ROADMAP §3 "What lives where"):
|
||||
- The `crosscode.identity/1` method name is `totp`; Events 2.3 calls it `authenticator`. The 3.0
|
||||
migration maps it.
|
||||
|
||||
**Roles stay in each product** (ROADMAP §3; asked by Joshua 2026-11-18). Accounts knows who someone
|
||||
is, never what they may do in a product: its own `member` / `admin` are only about Accounts (who
|
||||
manages sign-in settings, people and the church profile). Cross Events keeps its `User` table with
|
||||
its four roles (`admin`, `supervisor`, `staff`, `user`), campus scopes and all its data; in 3.0 only
|
||||
the user's id becomes the account's `sub`. When someone signs in to Events through Accounts, Events
|
||||
finds its own user by `sub` and applies that role, as today; someone new to Events arrives as
|
||||
`user` and an Events admin promotes them there. The ID token carries no roles, so no product can
|
||||
give anyone a role in another. An Events admin isn't an Accounts admin (or the other way round)
|
||||
unless someone makes them one; the 3.0 migration asks which Events admins should also manage
|
||||
Accounts. Events still requires 2FA for its staff roles by sending `acr_values=mfa`.
|
||||
|
||||
## 3. OpenID Connect
|
||||
|
||||
- **`oidc-provider`** (panva, 9.x) on the backend, **`openid-client`** (6.x) in each product
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
# @crosscode/ui
|
||||
|
||||
Placeholder. Shared UI (church branding from `crosscode.church/1`, layout, forms, the sign-in
|
||||
pages' look) for Accounts, the Church Website and the Church App. Filled in during the Website
|
||||
phase (ROADMAP-v3 §9, phase 4).
|
||||
Shared UI for the products a church's members see: the branded shell, cards, buttons, form fields
|
||||
and notices. First used by Accounts' sign-in and account pages (phase 3); the Church Website and
|
||||
App build on it (phases 4 and 6).
|
||||
|
||||
- Plain React + Tailwind, no runtime dependencies. Apps compile the source
|
||||
(`transpilePackages: ["@crosscode/ui"]` in `next.config.ts`) and add
|
||||
`packages/ui/src/**/*.{ts,tsx}` to their Tailwind `content`.
|
||||
- The church's colour comes from the CSS variables `--brand` and `--brand-dark` (`r g b`), which
|
||||
each app sets from `crosscode.church/1` (Tailwind colour `brand`).
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
{
|
||||
"name": "@crosscode/ui",
|
||||
"version": "0.0.0",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Placeholder: shared UI for the Website, App and Accounts, filled in during the Website phase (ROADMAP-v3 §9, phase 4)"
|
||||
"description": "Shared UI for the church's sign-in pages, Website and App: the branded shell, forms and buttons (Tailwind; apps compile the source with transpilePackages)",
|
||||
"main": "src/index.tsx",
|
||||
"types": "src/index.tsx",
|
||||
"peerDependencies": {
|
||||
"react": ">=19"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* @crosscode/ui — the branded shell, cards, buttons, fields and notices shared by Accounts, the
|
||||
* Church Website and the Church App. Colours come from `--brand` (see README).
|
||||
*/
|
||||
import React from "react";
|
||||
|
||||
const cx = (...c: (string | false | null | undefined)[]) => c.filter(Boolean).join(" ");
|
||||
|
||||
export type Branding = { name: string; shortName?: string | null; logoUrl?: string | null };
|
||||
|
||||
/** The page frame: the church's logo and name, then the content in a centred column. */
|
||||
export function Shell({ branding, children, wide = false, aside }: { branding: Branding; children: React.ReactNode; wide?: boolean; aside?: React.ReactNode }) {
|
||||
return (
|
||||
<div className="min-h-screen flex flex-col">
|
||||
<header className="bg-white border-b">
|
||||
<div className={cx("mx-auto flex items-center gap-3 px-4 py-3", wide ? "max-w-5xl" : "max-w-md")}>
|
||||
{branding.logoUrl ? <img src={branding.logoUrl} alt="" className="h-9 w-auto rounded" /> : <span className="h-9 w-9 rounded-lg bg-brand" aria-hidden />}
|
||||
<span className="font-semibold text-gray-900">{branding.name}</span>
|
||||
{aside && <div className="ml-auto">{aside}</div>}
|
||||
</div>
|
||||
</header>
|
||||
<main className={cx("mx-auto w-full flex-1 px-4 py-8", wide ? "max-w-5xl" : "max-w-md")}>{children}</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Card({ children, className }: { children: React.ReactNode; className?: string }) {
|
||||
return <div className={cx("rounded-2xl border bg-white p-6 shadow-sm", className)}>{children}</div>;
|
||||
}
|
||||
|
||||
export function Heading({ children, sub }: { children: React.ReactNode; sub?: React.ReactNode }) {
|
||||
return (
|
||||
<div className="mb-5">
|
||||
<h1 className="text-xl font-semibold text-gray-900">{children}</h1>
|
||||
{sub && <p className="mt-1 text-sm text-gray-600">{sub}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type ButtonProps = React.ButtonHTMLAttributes<HTMLButtonElement> & { variant?: "primary" | "secondary" | "danger" | "link"; busy?: boolean };
|
||||
|
||||
export function Button({ variant = "primary", busy, className, children, disabled, ...rest }: ButtonProps) {
|
||||
const styles = {
|
||||
primary: "bg-brand text-white hover:bg-brand-dark",
|
||||
secondary: "border bg-white text-gray-800 hover:bg-gray-50",
|
||||
danger: "bg-red-600 text-white hover:bg-red-700",
|
||||
link: "text-brand underline px-0 py-0",
|
||||
}[variant];
|
||||
return (
|
||||
<button {...rest} disabled={disabled || busy} className={cx("rounded-lg px-4 py-2.5 text-sm font-medium transition disabled:opacity-50", styles, className)}>
|
||||
{busy ? "Please wait…" : children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
type FieldProps = React.InputHTMLAttributes<HTMLInputElement> & { label: string; error?: string | null; hint?: React.ReactNode };
|
||||
|
||||
export function Field({ label, error, hint, id, className, ...rest }: FieldProps) {
|
||||
const fieldId = id ?? `f-${label.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`;
|
||||
return (
|
||||
<div className={cx("mb-4", className)}>
|
||||
<label htmlFor={fieldId} className="mb-1 block text-sm font-medium text-gray-800">{label}</label>
|
||||
<input
|
||||
id={fieldId}
|
||||
aria-invalid={!!error}
|
||||
aria-describedby={error ? `${fieldId}-error` : undefined}
|
||||
className={cx("w-full rounded-lg border px-3 py-2.5 text-base focus:outline-none focus:ring-2 focus:ring-brand/50", error ? "border-red-500" : "border-gray-300")}
|
||||
{...rest}
|
||||
/>
|
||||
{hint && !error && <p className="mt-1 text-xs text-gray-500">{hint}</p>}
|
||||
{error && <p id={`${fieldId}-error`} className="mt-1 text-sm text-red-700">{error}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function Checkbox({ label, hint, ...rest }: React.InputHTMLAttributes<HTMLInputElement> & { label: React.ReactNode; hint?: React.ReactNode }) {
|
||||
return (
|
||||
<label className="mb-3 flex items-start gap-3 text-sm">
|
||||
<input type="checkbox" className="mt-0.5 h-4 w-4 accent-[rgb(var(--brand))]" {...rest} />
|
||||
<span>
|
||||
<span className="text-gray-900">{label}</span>
|
||||
{hint && <span className="block text-gray-500">{hint}</span>}
|
||||
</span>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
export function Notice({ tone = "info", children }: { tone?: "info" | "error" | "success" | "warning"; children: React.ReactNode }) {
|
||||
const styles = { info: "bg-blue-50 text-blue-900 border-blue-200", error: "bg-red-50 text-red-800 border-red-200", success: "bg-green-50 text-green-800 border-green-200", warning: "bg-amber-50 text-amber-900 border-amber-200" }[tone];
|
||||
return <div role={tone === "error" ? "alert" : "status"} className={cx("mb-4 rounded-lg border px-4 py-3 text-sm", styles)}>{children}</div>;
|
||||
}
|
||||
Reference in New Issue
Block a user