diff --git a/CHANGELOG.md b/CHANGELOG.md index f9dd196..1c4c258 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,19 @@ Each package and app has its own section and its own tags (`contracts@1.0.0`, `accounts@1.0.0`, …). +## events@3.3.0, accounts@1.3.0, contracts@1.11.0 - 2026-11-20 + +Accounts looks like Cross Events and backs itself up; fixes in Events' sign-out and branding uploads. + +- **Contracts 1.11.0:** `people.removeDemo` in `crosscode.identity-request/1` (and its reply): + new demo data in a product removes the old demo people's accounts. Only `@example.com` addresses + (`DEMO_EMAIL_DOMAIN`), never an Accounts admin. +- **Accounts 1.3.0:** the account and admin pages in Cross Events' layout (top bar, sidebar of + sections with their own addresses, dark footer); quick links to the church's sites; nightly + database backups with an admin Backups page; a fuller built-in privacy notice; its own favicon. +- **Events 3.3.0:** signing out also signs out of Accounts; uploaded logos and favicons are served + from the folder they're saved in; new demo data replaces the old demo people in Accounts. + ## events@3.2.0, contracts@1.10.0 - 2026-11-19 Emergency updates can run as soon as possible (Hub 2.7.0); the Hub asks again when an event is on. diff --git a/apps/accounts/CHANGELOG.md b/apps/accounts/CHANGELOG.md index acb4acf..d45a8fc 100644 --- a/apps/accounts/CHANGELOG.md +++ b/apps/accounts/CHANGELOG.md @@ -1,5 +1,45 @@ # Changelog — Accounts +## [1.3.0] - 2026-11-20 + +Needs contracts 1.11.0 (`people.removeDemo`). Works with every Cross Events 3.x. + +### Added + +- **Backups** (Admin → Backups, `src/backups/backups.ts`): a gzipped `pg_dump` every night at + 02:00 (job `backup`) and on "Back up now", into `backend/backups/` with the names the + `crosscode` script already gives its pre-deploy dumps (`accounts-YYYYMMDD-HHMMSS.sql.gz`), so + both show in one list. Keeps the newest 14 by default (`backup_retain_count`), nightly can be + turned off (`backup_nightly`), downloads are admin-only and audited, a failed dump leaves no file + and shows why (`backup_last_error`). The heartbeat's `lastBackupAt` is the newest backup. + Needs `pg_dump` (the PostgreSQL client) on the server, as the crosscode script does. +- **Quick links to the church's sites** on the account page (`GET /api/v2/me/apps`): each + connected product; Events opens its dashboard through its own sign-in (no second sign-in). +- `people.removeDemo` (contracts 1.11.0): a product's old demo people (`@example.com`, known + through that product, not admins) are signed out everywhere and anonymised; the reply says which + were kept and why. +- A favicon (`app/icon.svg`), the same for every church. + +### Changed + +- **The account and admin pages look like Cross Events' dashboard:** the church's logo and name in + a top bar, a sidebar with the person, their role and the sections, panels with icon tiles, and a + dark footer. Each section has its own address: `/account` (overview), `/account/details`, + `/security`, `/privacy`, `/activity`; `/admin` (people), `/admin/deletions`, `/church`, + `/linked`, `/signin`, `/messages`, `/notice`, `/backups`, `/licence`, `/audit`. The + "your data is ready" email's link (`/account/privacy`) now opens the right section. Sign-in pages + keep their centred card. +- **The built-in privacy notice** is rewritten in sections, as Cross Events' policy: what's kept, + how it's used, who sees it (the church's sites, admins, email and WhatsApp providers, aggregate + totals to Cross Code), where and how long (including backups), cookies, POPIA rights, children, + changes and contact. A line starting "## " is a heading and "• " a bullet, on the privacy page, + the sign-in step and the admin's preview. Churches still on the built-in notice see the new text + as version 1 (it describes the same practice more fully); Admin → Privacy notice can start a new + version from it, which asks everyone to read it again. + +### Fixed + +- `backend/.gitignore` ignores `/backups/` (the dumps the crosscode script makes). ## [1.2.0] - 2026-11-19 Found after a church moved Cross Events' sign-in here without email set up in Accounts: every diff --git a/apps/accounts/WHATS-NEW.md b/apps/accounts/WHATS-NEW.md index a45972f..62065c3 100644 --- a/apps/accounts/WHATS-NEW.md +++ b/apps/accounts/WHATS-NEW.md @@ -3,6 +3,16 @@ What each version changes for the church, in plain language (read by the Hub like Cross Events' WHATS-NEW.md; a section shows once its version is tagged). +## 1.3.0 + +- Your account and the admin pages have a new look, like Cross Events: a menu down the side, and + each part on its own page. +- Quick links on your account page take you straight to the church's sites, already signed in. +- Admins: the sign-in database is backed up every night, and backups can be made and downloaded + under Admin → Backups. +- A clearer privacy notice that says exactly what your church account keeps and why. +- Accounts has its own icon in the browser tab. + ## 1.2.0 - **Fix:** when the church's email isn't working, signing in tells people so (and to let the office diff --git a/apps/accounts/backend/.gitignore b/apps/accounts/backend/.gitignore index 72d0c56..d983511 100644 --- a/apps/accounts/backend/.gitignore +++ b/apps/accounts/backend/.gitignore @@ -4,3 +4,4 @@ src/generated/ .env uploads/ exports/ +/backups/ diff --git a/apps/accounts/backend/package.json b/apps/accounts/backend/package.json index 6107890..006ae04 100644 --- a/apps/accounts/backend/package.json +++ b/apps/accounts/backend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/accounts-backend", - "version": "1.2.0", + "version": "1.3.0", "description": "Cross Code Accounts: the church's sign-in (OpenID Connect provider), account pages API and admin API", "private": true, "type": "module", diff --git a/apps/accounts/backend/src/admin/routes.ts b/apps/accounts/backend/src/admin/routes.ts index a21f604..f69ad92 100644 --- a/apps/accounts/backend/src/admin/routes.ts +++ b/apps/accounts/backend/src/admin/routes.ts @@ -1,12 +1,14 @@ /** * Accounts' admin (`/api/v2/admin/…`, docs/ACCOUNTS-1.0-PLAN.md §8): people, sign-in settings, - * linked products, the church profile, privacy notices and deletions, email and WhatsApp, the + * linked products, the church profile, privacy notices and deletions, email and WhatsApp, backups, * licence and the audit log. Admins only, signed in with 2FA; viewing a person is access-logged. */ +import fs from 'node:fs'; import express, { type Request, type Response } from 'express'; import type Provider from 'oidc-provider'; import type { Ctx } from '../context.js'; -import { ApiError, handle, limit } from '../http.js'; +import { ApiError, handle, limit, sendError } from '../http.js'; +import { backupPath, listBackups, retainCount, rotate, runBackup } from '../backups/backups.js'; import { accessLog, audit, clientIp, loginEvent } from '../lib/audit.js'; import { ADMIN_SETTINGS, SECRET_SETTINGS } from '../lib/settings.js'; import { currentSession } from '../oidc/sessions.js'; @@ -16,7 +18,7 @@ import { church, updateProfile } from '../church/profile.js'; import { connectTo, disconnectFrom } from '../links/connect.js'; import { linkedProducts } from '../links/store.js'; import { approveDeletion, cancelDeletion } from '../privacy/deletion.js'; -import { currentNotice, publish } from '../privacy/notice.js'; +import { builtInNotice, currentNotice, publish } from '../privacy/notice.js'; import { licenceStatus } from '../hub/licence.js'; import { connect as connectHub } from '../hub/client.js'; import { productName } from '../oidc/clients.js'; @@ -140,7 +142,8 @@ export function adminRouter(ctx: Ctx, provider: Provider) { r.get('/notices', handle(async (req, res) => { await admin(req, res); const list = await ctx.db.privacyNotice.findMany({ orderBy: { version: 'desc' } }); - return { current: await currentNotice(ctx), items: list }; + // 1.3.0: the built-in text too, so an admin can start a new version from it. + return { current: await currentNotice(ctx), builtIn: await builtInNotice(ctx), items: list }; })); r.post('/notices', handle(async (req, res) => { @@ -245,6 +248,57 @@ export function adminRouter(ctx: Ctx, provider: Provider) { return disconnectFrom(ctx, String(req.params.installId), me, req); })); + // ─── Backups (1.3.0) ─────────────────────────────────────────────────────── + + r.get('/backups', handle(async (req, res) => { + await admin(req, res); + const items = await listBackups(ctx); + return { + items: items.map((b) => ({ filename: b.filename, size: b.size, createdAt: b.createdAt })), + nightly: await ctx.settings.bool('backup_nightly', true), + retain: await retainCount(ctx), + lastError: await ctx.settings.get('backup_last_error'), + }; + })); + + r.post('/backups/run', limit(10, 60), handle(async (req, res) => { + const me = await admin(req, res); + let b; + try { + b = await runBackup(ctx); + } catch (e) { + throw new ApiError(502, 'BACKUP_FAILED', `The backup didn't work: ${(e as Error).message}`); + } + await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'backup_made', targetType: 'backup', targetId: b.filename, ip: clientIp(req) }); + return { filename: b.filename, size: b.size, createdAt: b.createdAt }; + })); + + r.put('/backups/settings', handle(async (req, res) => { + const me = await admin(req, res); + const retain = Number(req.body?.retain); + if (!Number.isInteger(retain) || retain < 1 || retain > 365) throw new ApiError(400, 'VALIDATION', 'Keep between 1 and 365 backups.', { retain: 'Between 1 and 365' }); + await ctx.settings.setMany({ backup_retain_count: String(retain), backup_nightly: req.body?.nightly === false ? 'false' : 'true' }); + const deleted = await rotate(ctx); + await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'backup_settings_changed', targetType: 'setting', targetId: 'backup_retain_count', metadata: { retain, nightly: req.body?.nightly !== false, deleted }, ip: clientIp(req) }); + return { retain, nightly: req.body?.nightly !== false, deleted }; + })); + + // A download holds everyone's data: admins only, audited, never cached. + r.get('/backups/:file/download', async (req, res) => { + try { + const me = await admin(req, res); + const file = backupPath(ctx, String(req.params.file)); + if (!file) throw new ApiError(404, 'NOT_FOUND', 'That backup isn\'t there any more.'); + await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'backup_downloaded', targetType: 'backup', targetId: String(req.params.file), ip: clientIp(req) }); + res.setHeader('Content-Type', 'application/gzip'); + res.setHeader('Cache-Control', 'no-store'); + res.setHeader('Content-Disposition', `attachment; filename="${String(req.params.file)}"`); + fs.createReadStream(file).pipe(res); + } catch (e) { + sendError(res, e); + } + }); + // ─── Licence, audit ──────────────────────────────────────────────────────── r.get('/licence', handle(async (req, res) => { diff --git a/apps/accounts/backend/src/backups/backups.ts b/apps/accounts/backend/src/backups/backups.ts new file mode 100644 index 0000000..353fe15 --- /dev/null +++ b/apps/accounts/backend/src/backups/backups.ts @@ -0,0 +1,129 @@ +/** + * Database backups (1.3.0, as Cross Events' Settings → Backups): a gzipped `pg_dump` into + * backend/backups/ every night at 02:00 and whenever an admin asks, kept on this server only. + * The `crosscode` script makes the same files before every deploy and uninstall + * (scripts/products/accounts.sh), so the admin's list shows both, newest first. + * + * Settings: `backup_nightly` (default on), `backup_retain_count` (default 14), and what the last + * run did (`backup_last_error`). Needs the `pg_dump` program on the server (Postgres client). + */ +import { spawn } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; +import type { Readable } from 'node:stream'; +import { pipeline } from 'node:stream/promises'; +import { fileURLToPath } from 'node:url'; +import zlib from 'node:zlib'; +import type { Ctx } from '../context.js'; + +/** backend/backups, from src/ and dist/ alike (never relative to where the process started). */ +export const DEFAULT_BACKUP_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'backups'); + +/** The names this module and the crosscode script give a backup: accounts-YYYYMMDD-HHMMSS.sql.gz. */ +export const BACKUP_FILE = /^accounts-\d{8}-\d{6}\.sql\.gz$/; +export const DEFAULT_RETAIN = 14; +const MAX_RETAIN = 365; + +export type Backup = { filename: string; size: number; createdAt: Date }; + +/** Something that writes a plain-SQL dump of the database to a stream (tests pass their own). */ +export type Dumper = (databaseUrl: string) => { stdout: Readable; done: Promise }; + +const dir = (ctx: Ctx) => ctx.config.backupDir ?? DEFAULT_BACKUP_DIR; + +/** `pg_dump`, plain SQL, without owners or privileges (restores into any database user). */ +export const pgDump: Dumper = (databaseUrl) => { + const child = spawn('pg_dump', ['--no-owner', '--no-privileges', databaseUrl], { stdio: ['ignore', 'pipe', 'pipe'] }); + let stderr = ''; + child.stderr.on('data', (d) => { stderr += String(d); }); + const done = new Promise((resolve, reject) => { + child.on('error', (e) => reject(new Error(`pg_dump couldn't start (${e.message}). Install the PostgreSQL client on this server.`))); + child.on('close', (code) => (code === 0 ? resolve() : reject(new Error(`pg_dump stopped (exit ${code}): ${stderr.trim().slice(0, 400)}`)))); + }); + return { stdout: child.stdout, done }; +}; + +const pad = (n: number) => String(n).padStart(2, '0'); +/** accounts-20261120-020000.sql.gz in the server's local time, as the crosscode script names them. */ +export function backupName(at: Date): string { + return `accounts-${at.getFullYear()}${pad(at.getMonth() + 1)}${pad(at.getDate())}-${pad(at.getHours())}${pad(at.getMinutes())}${pad(at.getSeconds())}.sql.gz`; +} + +export async function retainCount(ctx: Ctx): Promise { + const n = Number(await ctx.settings.get('backup_retain_count')); + return Number.isInteger(n) && n >= 1 ? Math.min(n, MAX_RETAIN) : DEFAULT_RETAIN; +} + +/** Every backup in the folder, newest first. */ +export async function listBackups(ctx: Ctx): Promise { + let names: string[]; + try { + names = await fs.promises.readdir(dir(ctx)); + } catch { + return []; + } + const items = await Promise.all(names.filter((n) => BACKUP_FILE.test(n)).map(async (filename) => { + const st = await fs.promises.stat(path.join(dir(ctx), filename)); + return { filename, size: st.size, createdAt: st.mtime }; + })); + return items.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime() || b.filename.localeCompare(a.filename)); +} + +/** The newest backup's time, for the Hub heartbeat. */ +export async function lastBackupAt(ctx: Ctx): Promise { + return (await listBackups(ctx))[0]?.createdAt ?? null; +} + +/** The full path of a backup to download, or null if there's no such backup (or a bad name). */ +export function backupPath(ctx: Ctx, filename: string): string | null { + if (!BACKUP_FILE.test(filename)) return null; + const p = path.join(dir(ctx), filename); + return fs.existsSync(p) ? p : null; +} + +/** Deletes the oldest backups beyond the number kept. */ +export async function rotate(ctx: Ctx): Promise { + const old = (await listBackups(ctx)).slice(await retainCount(ctx)); + await Promise.all(old.map((b) => fs.promises.unlink(path.join(dir(ctx), b.filename)).catch(() => {}))); + return old.length; +} + +/** + * Makes a backup now. A dump that fails part-way leaves no file behind (a truncated one would + * look like a real backup). Records the outcome for the admin page. + */ +export async function runBackup(ctx: Ctx, dumper: Dumper = pgDump): Promise { + const url = ctx.config.databaseUrl; + try { + if (!url) throw new Error('DATABASE_URL isn\'t set, so there\'s no database to back up.'); + await fs.promises.mkdir(dir(ctx), { recursive: true, mode: 0o700 }); + // Two in the same second (the button pressed twice): the next free second's name. + const at = ctx.now().getTime(); + let filename = backupName(new Date(at)); + for (let s = 1; fs.existsSync(path.join(dir(ctx), filename)); s++) filename = backupName(new Date(at + s * 1000)); + const file = path.join(dir(ctx), filename); + const { stdout, done } = dumper(url); + // Both must finish: pg_dump exiting cleanly, and the file written. Wait for both either way, + // so a failed one's file is deleted after the last write, not before it. + const [dumped, written] = await Promise.allSettled([done, pipeline(stdout, zlib.createGzip(), fs.createWriteStream(file, { mode: 0o600 }))]); + const failed = [dumped, written].find((r): r is PromiseRejectedResult => r.status === 'rejected'); + if (failed) { + await fs.promises.unlink(file).catch(() => {}); + throw failed.reason; + } + await rotate(ctx); + await ctx.settings.set('backup_last_error', null); + const st = await fs.promises.stat(file); + return { filename, size: st.size, createdAt: st.mtime }; + } catch (e) { + await ctx.settings.set('backup_last_error', `${ctx.now().toISOString()} ${(e as Error).message}`.slice(0, 600)); + throw e; + } +} + +/** The nightly `backup` job: skipped when an admin has turned nightly backups off. */ +export async function runBackupJob(ctx: Ctx) { + if (!(await ctx.settings.bool('backup_nightly', true))) return { skipped: true }; + const b = await runBackup(ctx); + return { filename: b.filename, size: b.size }; +} diff --git a/apps/accounts/backend/src/hub/client.ts b/apps/accounts/backend/src/hub/client.ts index 450181b..d78a354 100644 --- a/apps/accounts/backend/src/hub/client.ts +++ b/apps/accounts/backend/src/hub/client.ts @@ -10,6 +10,7 @@ import type { Ctx } from '../context.js'; import { hubPublicKey, verifyToken } from './licence.js'; import { keyPair, saveLinkedProducts } from '../links/store.js'; import { appVersion } from '../lib/version.js'; +import { lastBackupAt } from '../backups/backups.js'; export const PROTOCOL_VERSION = 2; const TIMEOUT_MS = 15000; @@ -55,7 +56,7 @@ export async function health(ctx: Ctx) { uptimeSeconds: Math.round((Date.now() - STARTED_AT) / 1000), db, jobs: { mode: ctx.config.jobsEnabled ? 'queue' : 'off', failedLast24h: 0 }, - lastBackupAt: null, + lastBackupAt: (await lastBackupAt(ctx).catch(() => null))?.toISOString() ?? null, disk: null, errorsLast24h: null, pendingMigrations: 0, diff --git a/apps/accounts/backend/src/jobs.ts b/apps/accounts/backend/src/jobs.ts index b0f6e56..cf6bb83 100644 --- a/apps/accounts/backend/src/jobs.ts +++ b/apps/accounts/backend/src/jobs.ts @@ -4,6 +4,7 @@ */ import PgBoss from 'pg-boss'; import type { Ctx } from './context.js'; +import { runBackupJob } from './backups/backups.js'; import { heartbeat } from './hub/client.js'; import { runDue } from './links/deliveries.js'; import { forgetOldRequests } from './links/requests.js'; @@ -17,6 +18,8 @@ export const JOBS: Job[] = [ { name: 'deliveries', cron: '* * * * *', everyMs: 60e3, run: (ctx) => runDue(ctx) }, { name: 'exports', cron: '*/5 * * * *', everyMs: 5 * 60e3, run: (ctx) => runExportsJob(ctx) }, { name: 'deletions', cron: '*/15 * * * *', everyMs: 15 * 60e3, run: (ctx) => runDeletionJob(ctx) }, + // 1.3.0: a database backup every night (Settings → Backups), as Cross Events. + { name: 'backup', cron: '0 2 * * *', everyMs: 24 * 3600e3, run: (ctx) => runBackupJob(ctx) }, { name: 'hub-heartbeat', cron: '*/15 * * * *', everyMs: 15 * 60e3, run: (ctx) => heartbeat(ctx) }, { name: 'cleanup', cron: '17 * * * *', everyMs: 3600e3, diff --git a/apps/accounts/backend/src/lib/config.ts b/apps/accounts/backend/src/lib/config.ts index 920606f..312c163 100644 --- a/apps/accounts/backend/src/lib/config.ts +++ b/apps/accounts/backend/src/lib/config.ts @@ -25,6 +25,10 @@ export type Config = { /** Local testing only: linked products on http or private addresses. */ allowPrivateLinks: boolean; jobsEnabled: boolean; + /** 1.3.0: for the backups' pg_dump (DATABASE_URL, as Prisma uses). */ + databaseUrl: string | null; + /** 1.3.0: where backups go; default backend/backups (tests use their own folder). */ + backupDir: string | null; }; const bool = (v: string | undefined, def: boolean) => (v === undefined || v === '' ? def : String(v).toLowerCase() === 'true'); @@ -72,5 +76,7 @@ export function loadConfig(env: Record = process.env wawp: env.WAWP_ACCESS_TOKEN && env.WAWP_INSTANCE_ID ? { accessToken: env.WAWP_ACCESS_TOKEN, instanceId: env.WAWP_INSTANCE_ID } : null, allowPrivateLinks: bool(env.LINKS_ALLOW_PRIVATE, false), jobsEnabled: bool(env.JOBS_ENABLED, true), + databaseUrl: env.DATABASE_URL?.trim() || null, + backupDir: null, }; } diff --git a/apps/accounts/backend/src/links/requests.ts b/apps/accounts/backend/src/links/requests.ts index 6e9cf43..261e19c 100644 --- a/apps/accounts/backend/src/links/requests.ts +++ b/apps/accounts/backend/src/links/requests.ts @@ -15,7 +15,7 @@ import crypto from 'node:crypto'; import express, { type Request, type Response } from 'express'; import type Provider from 'oidc-provider'; import { - ACCOUNTS_REQUEST_PATH, IDENTITY_REQUEST_SCHEMA, identityRequestSchema, + ACCOUNTS_REQUEST_PATH, DEMO_EMAIL_DOMAIN, IDENTITY_REQUEST_SCHEMA, identityRequestSchema, type ChurchLook, type IdentityRequest, type ImportPerson, type ImportResult, } from '@crosscode/contracts'; import { LINK_HEADERS, openLinkValue, verify } from '@crosscode/contracts/signing'; @@ -29,6 +29,10 @@ import { BUILT_IN_VERSION } from '../privacy/notice.js'; import { emailProblem, normaliseEmail, profileChanged, setNewsConsent } from '../accounts/service.js'; import { turnOff } from '../accounts/twoFactor.js'; import { signOutEverywhere } from '../oidc/sessions.js'; +import { anonymise } from '../privacy/deletion.js'; + +/** A demo person's address (contracts DEMO_EMAIL_DOMAIN, reserved: no real person has one). */ +export const isDemoEmail = (email: string) => email.toLowerCase().endsWith(`@${DEMO_EMAIL_DOMAIN}`); export class RequestError extends Error { constructor(message: string, public code: string, public status = 400) { @@ -284,6 +288,25 @@ async function handle(ctx: Ctx, provider: Provider, link: ProductLink, secret: s await logRequest(ctx, link, r, r.active ? 'account_reactivated_by_product' : 'account_deactivated_by_product', a.id, req); return reply({ ok: true as const }); } + case 'people.removeDemo': { + // 1.3.0: a product's new demo data replaces the old; the old demo people's accounts go. + const kept: { sub: string; reason: 'not_demo' | 'admin' | 'unknown' }[] = []; + let removed = 0; + const known = new Set((await ctx.db.productPerson.findMany({ where: { linkId: link.installId, accountId: { in: r.subs } }, select: { accountId: true } })).map((p) => p.accountId)); + const accounts = new Map((await ctx.db.account.findMany({ where: { id: { in: [...known] } } })).map((a) => [a.id, a])); + for (const sub of new Set(r.subs)) { + const a = accounts.get(sub); + if (!a || a.status === 'deleted') { kept.push({ sub, reason: 'unknown' }); continue; } + if (!isDemoEmail(a.email)) { kept.push({ sub, reason: 'not_demo' }); continue; } + if (a.role === 'admin') { kept.push({ sub, reason: 'admin' }); continue; } + await signOutEverywhere(ctx, provider, a.id); + await anonymise(ctx, a.id); + await ctx.db.productPerson.deleteMany({ where: { accountId: a.id } }); + removed++; + } + await logRequest(ctx, link, r, 'demo_people_removed_by_product', null, req, { removed, kept: kept.length }); + return reply({ removed, kept }); + } case 'church.branding': { const changed = await applyLook(ctx, r.church, r.overwrite); await logRequest(ctx, link, r, 'church_look_from_product', null, req, { changed, overwrite: r.overwrite }); diff --git a/apps/accounts/backend/src/me/routes.ts b/apps/accounts/backend/src/me/routes.ts index 3479f3e..3164021 100644 --- a/apps/accounts/backend/src/me/routes.ts +++ b/apps/accounts/backend/src/me/routes.ts @@ -16,6 +16,13 @@ import { currentNotice } from '../privacy/notice.js'; import { requestExport } from '../privacy/export.js'; import { requestDeletion } from '../privacy/deletion.js'; import { hashToken, randomToken } from '../lib/crypto.js'; +import { linkedProducts } from '../links/store.js'; + +/** 1.3.0: the quick links on the account page. Events' own sign-in, already signed in here, lands on the dashboard. */ +const APP_NAMES: Record = { events: 'Events', website: 'Website', app: 'Church app' }; +const APP_BLURBS: Record = { events: 'Your bookings, tickets and serving', website: 'The church\'s website', app: 'The church app on your phone' }; +const OPEN_PATHS: Record = { events: '/api/auth/signin?returnTo=%2Fdashboard' }; +const appName = (product: string) => APP_NAMES[product] ?? product; export function meView(a: SignedIn['account'], extra: { recoveryCodesLeft: number; noticeVersion: number }) { return { @@ -44,6 +51,18 @@ export function meRouter(ctx: Ctx, provider: Provider) { r.get('/me', handle(async (req, res) => view(await signedIn(req, res)))); + // 1.3.0: the church's sites and apps that sign in here, for the account page's quick links. + r.get('/me/apps', handle(async (req, res) => { + await signedIn(req, res); + const [links, listed] = await Promise.all([ctx.db.productLink.findMany({ orderBy: { connectedAt: 'asc' } }), linkedProducts(ctx)]); + return { + items: links.map((l) => { + const url = (listed.find((x) => x.installId === l.installId)?.url ?? l.url).replace(/\/+$/, ''); + return { id: l.installId, product: l.product, name: appName(l.product), description: APP_BLURBS[l.product] ?? null, url: `${url}${OPEN_PATHS[l.product] ?? '/'}` }; + }), + }; + })); + r.put('/me', handle(async (req, res) => { const s = await signedIn(req, res); const name = req.body?.name !== undefined ? String(req.body.name).trim().replace(/\s+/g, ' ') : s.account.name; diff --git a/apps/accounts/backend/src/privacy/notice.ts b/apps/accounts/backend/src/privacy/notice.ts index e359c23..e5e4183 100644 --- a/apps/accounts/backend/src/privacy/notice.ts +++ b/apps/accounts/backend/src/privacy/notice.ts @@ -8,18 +8,79 @@ import { church } from '../church/profile.js'; export const BUILT_IN_VERSION = 1; +/** + * The built-in notice (1.3.0: in sections, as Cross Events' privacy policy, and saying what + * Accounts actually does). Plain text: a line starting "## " is a heading, "• " a bullet. Filled + * in from the church profile, so it follows the church's name and contact details. + */ export async function builtInNotice(ctx: Ctx) { const c = await church(ctx); - const contact = c.contact.email ? ` You can reach us at ${c.contact.email}.` : ''; + const org = c.name; + const contact = [c.contact.email && `• Email: ${c.contact.email}`, c.contact.phone && `• Phone: ${c.contact.phone}`].filter(Boolean) as string[]; + const keepBackups = (await ctx.settings.get('backup_retain_count')) || '14'; return { version: BUILT_IN_VERSION, - title: `How ${c.name} looks after your information`, + title: `How ${org} looks after your information`, body: [ - `${c.name} keeps your name, email address and (if you give it) phone number so you can sign in to the church's websites and apps, and so we can contact you about what you've signed up for.`, - 'We only send you news if you say yes, and you can change that at any time on your account page.', - 'You can download everything we hold about you, or ask us to delete your account, from your account page. We keep a record of sign-ins to protect your account.', - `We don't sell or share your information. The services that store it for us are bound to keep it safe.${contact}`, - ].join('\n\n'), + '## In short', + `• Your church account is how you sign in to ${org}'s websites and apps. It holds your name, email address and, if you give it, your mobile number.`, + '• Your password is never stored, only a scrambled form of it that can\'t be turned back. Two-step sign-in codes and recovery codes are protected the same way.', + '• It\'s kept on the church\'s own server, not shared with other churches, and never sold.', + '• The church\'s sites only get your name and contact details, when you sign in to them, and when you change them here.', + '• News comes only if you say yes, and you can change that at any time.', + '• On your account page you can download everything held about you, see your sign-ins, and delete your account.', + '', + '## 1. Who we are', + `${org} ("we", "us") is responsible for your personal information under the Protection of Personal Information Act (POPIA). This notice is about your church account: the sign-in shared by ${org}'s websites and apps. Each site may hold more about you for what you do there (for example the events site's bookings and tickets), and explains that in its own privacy notice.`, + '', + '## 2. What we keep', + '• Your details: name, email address (and whether you\'ve confirmed it), and your mobile number if you add it.', + '• Signing in: your password as a one-way hash, which two-step sign-in method you use, your authenticator app\'s key (encrypted), and your recovery codes (hashed). Codes sent by email or WhatsApp last a few minutes and are never kept in readable form.', + '• Security records: when you sign in, fail to, change your password, or turn two-step sign-in on or off, with the time, the IP address, the device type and which site it was for. These let you spot sign-ins you don\'t recognise and let us look into misuse.', + '• Your choices: whether you want news by email or WhatsApp, which version of this notice you accepted, and when you made each choice.', + '• Which of the church\'s sites you use: so a change to your name or email reaches them, and a deletion is passed on.', + '• If you\'re an admin: what you change in the admin pages, in an audit log. When an admin opens someone\'s details, that\'s recorded too.', + '', + '## 3. How we use it', + `• To sign you in, once, to all of ${org}'s sites and apps, and to sign you out of all of them when you sign out or ask to.`, + '• To send what signing in needs: email confirmation links, password reset links, sign-in codes, and security notices.', + '• To send church news, only if you said yes.', + '• To keep your account safe: locking it after too many wrong passwords, and asking admins for a second step.', + '', + '## 4. Who can see it', + `• The church's sites and apps you sign in to get your name, email address and mobile number (and whether they're confirmed), and nothing else from here. Each is listed by the church under Linked products, and only ${org}'s own sites can be linked.`, + `• ${org}'s Accounts admins can see your details and recent sign-ins to help you (for example to unlock your account). They can't see your password or codes.`, + '• Email is sent through the church\'s email provider, and WhatsApp messages through WAWP (wawp.net); they get only the message and where it goes.', + '• The software (Cross Code Accounts) is licensed from Cross Code. Every 15 minutes it sends Cross Code\'s licence server totals, such as how many accounts there are and how many use two-step sign-in, and technical health information. Never names, contact details or anything else about a person.', + '• Nobody else, unless South African law requires it. We don\'t sell or rent your information.', + '', + '## 5. Where it\'s kept, and for how long', + `• On ${org}'s server, in its own database, separate from every other church.`, + `• Your account and its sign-in history are kept while you have the account. A copy of your data that you ask to download is kept for 7 days. Sign-in codes stop working after a few minutes, and links to set or reset a password after at most 7 days.`, + `• The database is backed up every night onto the same server; the last ${keepBackups} backups are kept, then deleted. Backups are only used to put things back after a fault.`, + '• When your account is deleted, your name, contact details, password, codes and sign-in history are removed straight away, and are gone from the backups once those backups are deleted in turn.', + '', + '## 6. Cookies', + `Signing in uses a few cookies that are strictly necessary: they keep you signed in (for as long as "Keep me signed in" lasts, if you tick it) and protect each sign-in step. There are no tracking, advertising or analytics cookies, and these pages load nothing from other websites apart from the church's own logo.`, + '', + '## 7. Your rights', + 'Under POPIA you may see the information we hold about you, have it corrected or deleted, withdraw consent (for example to news), object to direct marketing, and complain to the Information Regulator. On your account page you can:', + '• change your details and your news choices;', + '• download a copy of everything the church\'s sites hold about you;', + '• see your recent sign-ins, and sign out everywhere;', + `• delete your account. You're signed out at once; an admin confirms it, then each of the church's sites deletes what it holds (a site may wait until an event you're booked for is over).`, + 'We answer requests within 30 days. The Information Regulator: www.inforeg.org.za, enquiries@inforeg.org.za.', + '', + '## 8. Children', + 'Anyone under 18 should have a parent\'s or guardian\'s permission to make a church account.', + '', + '## 9. Changes to this notice', + 'If this notice changes, you\'re asked to read the new version the next time you sign in.', + '', + '## 10. Contact us', + contact.length ? `To ask about your information or use your rights, contact ${org}:` : `To ask about your information or use your rights, contact ${org}'s office.`, + ...contact, + ].join('\n'), publishedAt: null as Date | null, }; } diff --git a/apps/accounts/backend/tests/backups.test.ts b/apps/accounts/backend/tests/backups.test.ts new file mode 100644 index 0000000..f70f9f2 --- /dev/null +++ b/apps/accounts/backend/tests/backups.test.ts @@ -0,0 +1,122 @@ +// 1.3.0: database backups (Settings → Backups, as Cross Events) and the account page's quick links +// to the church's sites. +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { Readable } from 'node:stream'; +import zlib from 'node:zlib'; +import { after, before, describe, test } from 'node:test'; +import { Browser, startHarness, type Harness } from './support/harness.js'; +import { BACKUP_FILE, backupName, backupPath, listBackups, runBackup, type Dumper } from '../src/backups/backups.js'; +import { codeAt } from '../src/lib/totp.js'; + +let h: Harness; +let dir: string; +before(async () => { + h = await startHarness(); + dir = fs.mkdtempSync(path.join(os.tmpdir(), 'accounts-backups-')); + h.ctx.config.backupDir = dir; + h.ctx.config.databaseUrl = 'postgresql://test@127.0.0.1/accounts_test'; +}); +after(async () => { await h.close(); fs.rmSync(dir, { recursive: true, force: true }); }); + +const dumpOf = (sql: string): Dumper => () => ({ stdout: Readable.from([sql]), done: Promise.resolve() }); +const failing: Dumper = () => ({ stdout: Readable.from(['-- half a dump']), done: Promise.reject(new Error('pg_dump stopped (exit 1): connection refused')) }); + +async function adminPage() { + await h.makeAccount({ email: 'backups.admin@hope.test', password: 'Correct-horse-8', role: 'admin' }); + const browser = new Browser(); + const { url } = await browser.follow(`${h.publicUrl}/api/self/signin?returnTo=/admin`, (u) => u.pathname === '/signin'); + const uid = url.searchParams.get('uid')!; + await h.api(browser, 'POST', `/api/v2/interaction/${uid}/password`, { email: 'backups.admin@hope.test', password: 'Correct-horse-8' }); + const setup = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/two-factor/setup`, { method: 'totp' }); + const done = await h.api(browser, 'POST', `/api/v2/interaction/${uid}/two-factor/setup/confirm`, { method: 'totp', code: codeAt(String(setup.body.secret), Math.floor(Date.now() / 30000)) }); + await browser.follow(done.body.redirectTo as string, (u) => u.pathname === '/admin' || u.pathname === '/account'); + return browser; +} + +describe('backups', () => { + test('a backup is the gzipped dump, named as the crosscode script names them', async () => { + const b = await runBackup(h.ctx, dumpOf('CREATE TABLE "Account" ();\n')); + assert.match(b.filename, BACKUP_FILE); + assert.equal(zlib.gunzipSync(fs.readFileSync(path.join(dir, b.filename))).toString(), 'CREATE TABLE "Account" ();\n'); + assert.equal(backupName(new Date(2026, 10, 20, 2, 0, 5)), 'accounts-20261120-020005.sql.gz'); + // A second one in the same second gets its own name. + const again = await runBackup(h.ctx, dumpOf('-- again\n')); + assert.notEqual(again.filename, b.filename); + }); + + test('a dump that fails part-way leaves no file, and says why', async () => { + const before = (await listBackups(h.ctx)).length; + await assert.rejects(runBackup(h.ctx, failing), /connection refused/); + assert.equal((await listBackups(h.ctx)).length, before); + assert.match(String(await h.ctx.settings.get('backup_last_error')), /connection refused/); + await runBackup(h.ctx, dumpOf('-- fine\n')); + assert.equal(await h.ctx.settings.get('backup_last_error'), null); + }); + + test('only the newest are kept; downloads only by a backup\'s own name', async () => { + await h.ctx.settings.set('backup_retain_count', '2'); + await runBackup(h.ctx, dumpOf('-- newest\n')); + const left = await listBackups(h.ctx); + assert.equal(left.length, 2); + assert.ok(backupPath(h.ctx, left[0]!.filename)); + assert.equal(backupPath(h.ctx, '../.env'), null); + assert.equal(backupPath(h.ctx, 'accounts-20200101-000000.sql.gz'), null); + await h.ctx.settings.set('backup_retain_count', null); + }); + + test('admins see, change and download them; members can\'t', async () => { + await h.makeAccount({ email: 'backups.member@hope.test', password: 'Correct-horse-9' }); + const member = new Browser(); + const { url } = await member.follow(`${h.publicUrl}/api/self/signin?returnTo=/account`, (u) => u.pathname === '/signin'); + const step = await h.api(member, 'POST', `/api/v2/interaction/${url.searchParams.get('uid')}/password`, { email: 'backups.member@hope.test', password: 'Correct-horse-9' }); + await member.follow(step.body.redirectTo as string, (u) => u.pathname === '/account'); + assert.equal((await h.api(member, 'GET', '/api/v2/admin/backups')).status, 403); + + const admin = await adminPage(); + const list = await h.api(admin, 'GET', '/api/v2/admin/backups'); + assert.equal(list.status, 200, JSON.stringify(list.body)); + const items = list.body.items as { filename: string }[]; + assert.equal(list.body.nightly, true); + assert.equal(list.body.retain, 14); + const file = await admin.request(`${h.publicUrl}/api/v2/admin/backups/${items[0]!.filename}/download`); + assert.equal(file.status, 200); + assert.equal(file.headers.get('cache-control'), 'no-store'); + assert.ok(zlib.gunzipSync(Buffer.from(await file.arrayBuffer())).length > 0); + assert.equal((await admin.request(`${h.publicUrl}/api/v2/admin/backups/nope.sql.gz/download`)).status, 404); + assert.equal(await h.db.auditLog.count({ where: { action: 'backup_downloaded' } }), 1); + + const bad = await h.api(admin, 'PUT', '/api/v2/admin/backups/settings', { retain: 0, nightly: true }); + assert.equal(bad.status, 400); + const saved = await h.api(admin, 'PUT', '/api/v2/admin/backups/settings', { retain: 30, nightly: false }); + assert.deepEqual(saved.body, { retain: 30, nightly: false, deleted: 0 }); + assert.equal(await h.ctx.settings.bool('backup_nightly', true), false); + }); + + test('the nightly backup is skipped while it\'s turned off', async () => { + const { runBackupJob } = await import('../src/backups/backups.js'); + await h.ctx.settings.set('backup_nightly', 'false'); + assert.deepEqual(await runBackupJob(h.ctx), { skipped: true }); + await h.ctx.settings.set('backup_nightly', null); + }); +}); + +describe('quick links to the church\'s sites', () => { + test('the account page lists each connected site, Events opening its dashboard', async () => { + const browser = new Browser(); + const { url } = await browser.follow(`${h.publicUrl}/api/self/signin?returnTo=/account`, (u) => u.pathname === '/signin'); + const step = await h.api(browser, 'POST', `/api/v2/interaction/${url.searchParams.get('uid')}/password`, { email: 'backups.member@hope.test', password: 'Correct-horse-9' }); + await browser.follow(step.body.redirectTo as string, (u) => u.pathname === '/account'); + const apps = await h.api(browser, 'GET', '/api/v2/me/apps'); + assert.equal(apps.status, 200, JSON.stringify(apps.body)); + const links = await h.db.productLink.findMany(); + assert.equal((apps.body.items as unknown[]).length, links.length); + for (const item of apps.body.items as { product: string; url: string; name: string }[]) { + assert.ok(item.url.startsWith('http')); + if (item.product === 'events') assert.match(item.url, /\/api\/auth\/signin\?returnTo=%2Fdashboard$/); + } + assert.equal((await h.api(new Browser(), 'GET', '/api/v2/me/apps')).status, 401); + }); +}); diff --git a/apps/accounts/backend/tests/requests.test.ts b/apps/accounts/backend/tests/requests.test.ts index 9d5def0..4ff5468 100644 --- a/apps/accounts/backend/tests/requests.test.ts +++ b/apps/accounts/backend/tests/requests.test.ts @@ -177,6 +177,28 @@ describe('people.* from a product', () => { assert.equal((await h.db.account.findUnique({ where: { id: sub } }))!.status, 'deactivated'); }); + test('people.removeDemo removes only the product\'s demo people, never an admin or a real address', async () => { + const ensure = (name: string, email: string) => ask({ type: 'people.ensure', name, email, phone: null, returnUrl: 'https://events.hope.test/' }).then((r) => r.body.sub as string); + const demo = await ensure('Old Demo', 'old.demo@example.com'); + const real = await ensure('Real Person', 'real.person@hope.test'); + const demoAdmin = await ensure('Demo Admin', 'demo.admin@example.com'); + await h.db.account.update({ where: { id: demoAdmin }, data: { role: 'admin' } }); + const stranger = (await h.makeAccount({ email: 'not.known@example.com' })).id; + + const res = await ask({ type: 'people.removeDemo', subs: [demo, real, demoAdmin, stranger] }); + assert.equal(res.status, 200, JSON.stringify(res.body)); + assert.equal(res.body.removed, 1); + assert.deepEqual(res.body.kept, [{ sub: real, reason: 'not_demo' }, { sub: demoAdmin, reason: 'admin' }, { sub: stranger, reason: 'unknown' }]); + const gone = (await h.db.account.findUnique({ where: { id: demo } }))!; + assert.equal(gone.status, 'deleted'); + assert.notEqual(gone.email, 'old.demo@example.com', 'the address is free for the next demo'); + assert.equal((await h.db.account.findUnique({ where: { id: real } }))!.status, 'active'); + assert.equal((await h.db.account.findUnique({ where: { id: stranger } }))!.status, 'active'); + // The next demo can have the same person again, as a new account. + const again = await ask({ type: 'people.ensure', name: 'Old Demo', email: 'old.demo@example.com', phone: null, returnUrl: 'https://events.hope.test/' }); + assert.equal(again.body.created, true); + }); + test('a retry with the same request id gets the same answer; a bad signature is refused', async () => { const requestId = crypto.randomUUID(); const body = { type: 'people.ensure', name: 'Retry', email: 'retry@hope.test', phone: null, returnUrl: 'https://events.hope.test/' }; diff --git a/apps/accounts/e2e/signin.spec.ts b/apps/accounts/e2e/signin.spec.ts index a7fcb02..84fa69d 100644 --- a/apps/accounts/e2e/signin.spec.ts +++ b/apps/accounts/e2e/signin.spec.ts @@ -76,13 +76,17 @@ test("a product asking for two-step sign-in: set up with an app, recovery codes, await expect(page.locator("#amr")).toHaveText("pwd otp mfa"); }); -test("the account page: signs in first, then saves details", async ({ page }) => { +test("the account page: signs in first, links to the church's sites, then saves details", async ({ page }) => { await page.goto("/account"); await expect(page.getByRole("heading", { name: "Sign in to Hope Family Church" })).toBeVisible(); await page.getByLabel("Email address").fill("new@hope.test"); await page.getByLabel("Password").fill("Correct-horse-2"); await page.getByRole("button", { name: "Sign in" }).click(); - await expect(page.getByRole("heading", { name: "Your account" })).toBeVisible(); + await expect(page.getByRole("heading", { name: "Hi, New" })).toBeVisible(); + // 1.3.0: a quick link to each site that signs in here (the test product is a website). + await expect(page.getByRole("link", { name: /Website/ })).toHaveAttribute("href", "http://localhost:5211/"); + await page.getByRole("navigation", { name: "Your account" }).getByRole("link", { name: "Your details" }).click(); + await expect(page).toHaveURL(/\/account\/details$/); await page.getByLabel("Name").fill("New Person-Smith"); await page.getByRole("button", { name: "Save", exact: true }).click(); await expect(page.getByRole("status")).toContainText("Your details are saved"); @@ -98,6 +102,10 @@ test("admin: needs two-step sign-in, then lists people", async ({ page }) => { await page.getByLabel("Code").fill(await helper(page, `/test/totp?secret=${key}`)); await page.getByRole("button", { name: "Turn on" }).click(); await page.getByRole("button", { name: "I've saved them" }).click(); - await expect(page.getByRole("heading", { name: "Accounts admin" })).toBeVisible(); + await expect(page.getByRole("heading", { name: "People", level: 1 })).toBeVisible(); await expect(page.getByText("thandi@hope.test")).toBeVisible(); + // 1.3.0: every admin section has its own address, down the side; Backups is one. + await page.getByRole("navigation", { name: "Admin" }).getByRole("link", { name: "Backups" }).click(); + await expect(page.getByRole("heading", { name: "Database backups" })).toBeVisible(); + await expect(page.getByRole("button", { name: "Back up now" })).toBeVisible(); }); diff --git a/apps/accounts/frontend/package.json b/apps/accounts/frontend/package.json index 9f96a82..c90c7c3 100644 --- a/apps/accounts/frontend/package.json +++ b/apps/accounts/frontend/package.json @@ -1,6 +1,6 @@ { "name": "@crosscode/accounts-frontend", - "version": "1.2.0", + "version": "1.3.0", "private": true, "description": "Cross Code Accounts: the church's sign-in pages, the account page and admin", "scripts": { diff --git a/apps/accounts/frontend/src/app/account/Account.tsx b/apps/accounts/frontend/src/app/account/Account.tsx index 8cc7733..e0fbf78 100644 --- a/apps/accounts/frontend/src/app/account/Account.tsx +++ b/apps/accounts/frontend/src/app/account/Account.tsx @@ -1,9 +1,13 @@ "use client"; +import Link from "next/link"; import React, { useCallback, useState } from "react"; import QRCode from "qrcode"; -import { Button, Card, Checkbox, Field, Heading, Notice, Shell } from "@crosscode/ui"; +import { Activity as ActivityIcon, ArrowUpRight, Calendar, CheckCircle2, Globe, Lock, Mail, ShieldAlert, ShieldCheck, Smartphone, User, type LucideIcon } from "lucide-react"; +import { Button, Checkbox, Field, Notice } from "@crosscode/ui"; import { useBranding } from "@/components/BrandingProvider"; +import { AppShell, PageTitle, ShellLoading } from "@/components/AppShell"; +import { Card, Heading } from "@/components/Panel"; import { call, selfSignIn } from "@/lib/api"; import { useExternalEffect } from "@/lib/hooks"; @@ -23,37 +27,124 @@ const EVENT: Record = { }; 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() { +export type AccountSection = "overview" | "details" | "security" | "privacy" | "activity"; + +const SECTIONS: Record string }> = { + overview: { path: "/account", title: "Your account", sub: (c) => `One account for all of ${c}'s sites and apps.` }, + details: { path: "/account/details", title: "Your details", sub: (c) => `Your name and contact details, shared with ${c}'s sites when you sign in.` }, + security: { path: "/account/security", title: "Signing in", sub: () => "Your password, two-step sign-in and recovery codes." }, + privacy: { path: "/account/privacy", title: "Privacy", sub: () => "Your news choices, a copy of your data, and deleting your account." }, + activity: { path: "/account/activity", title: "Activity", sub: () => "Recent sign-ins and changes to your account." }, +}; + +/** + * The account page (docs/ACCOUNTS-1.0-PLAN.md §8): everything about one's own account. 1.3.0: in + * sections down the side (as Cross Events' dashboard), with quick links to the church's sites. + */ +export function Account({ section = "overview" }: { section?: AccountSection }) { const branding = useBranding(); const [me, setMe] = useState(null); const [msg, setMsg] = useState<{ tone: "success" | "error"; text: string } | null>(null); + const s = SECTIONS[section] ?? SECTIONS.overview; const load = useCallback(async () => { const r = await call("GET", "/me"); - if (r.status === 401) return window.location.assign(selfSignIn("/account")); + if (r.status === 401) return window.location.assign(selfSignIn(s.path)); if (r.ok) setMe(r.data); - }, []); + }, [s.path]); 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

Loading…

; + if (!me) return ; - const signOut = Sign out; + const first = me.name.split(" ")[0] || me.name; return ( - {me.role === "admin" && Admin}{signOut}}> -

Your account

-

One account for all of {branding.name}'s sites and apps.

+ + {section === "overview" ? `Hi, ${first}` : s.title} {msg && {msg.text}} -
- - - - + {section === "overview" && } + {section === "details" &&
} + {section === "security" &&
} + {section === "privacy" &&
} + {section === "activity" &&
} + + ); +} + +// ─── Overview: the church's sites, and how the account stands ──────────────── + +type App = { id: string; product: string; name: string; description: string | null; url: string }; +const APP_ICONS: Record = { events: Calendar, website: Globe, app: Smartphone }; + +function Overview({ me }: { me: Me }) { + const branding = useBranding(); + const [apps, setApps] = useState(null); + useExternalEffect(() => { + let alive = true; + call<{ items: App[] }>("GET", "/me/apps").then((r) => { if (alive) setApps(r.ok ? r.data.items : []); }); + return () => { alive = false; }; + }, []); + + const checks: { ok: boolean; label: string; detail: string; href: string; icon: LucideIcon }[] = [ + { ok: !!me.twoFactor, label: me.twoFactor ? "Two-step sign-in is on" : "Two-step sign-in is off", detail: me.twoFactor ? `With ${METHOD[me.twoFactor]}${me.recoveryCodesLeft < 3 ? `, ${me.recoveryCodesLeft} recovery codes left` : ""}` : "Turn it on so a password alone can't open your account", href: "/account/security", icon: me.twoFactor ? ShieldCheck : ShieldAlert }, + { ok: me.emailVerified, label: me.emailVerified ? "Email address confirmed" : "Email address not confirmed", detail: me.email, href: "/account/details", icon: Mail }, + { ok: true, label: "Last sign-in", detail: when(me.lastSignInAt), href: "/account/activity", icon: ActivityIcon }, + ]; + + return ( +
+
+

Go to

+ {apps === null &&

Loading…

} + {apps && !apps.length && ( +

{branding.name}'s sites and apps will show here once they sign people in with this account.

+ )} + {apps && apps.length > 0 && ( +
+ {apps.map((a) => { + const Icon = APP_ICONS[a.product] ?? Globe; + return ( + + + + {a.name} + {a.description && {a.description}} + {a.url.replace(/^https?:\/\//, "").replace(/\/.*$/, "")} + + + + ); + })} +
+ )} +
+ +
+

Your account

+
+ {checks.map((c) => { + const Icon = c.icon; + return ( + + + + {c.label} + {c.detail} + + + ); + })} +
+
+ +
+ Change your details + Download your data + {me.noticeVersionAccepted >= me.noticeVersion && You've read the latest privacy notice}
- +
); } @@ -64,7 +155,7 @@ function Profile({ me, onDone, onFail }: Props) { const [changingEmail, setChangingEmail] = useState(false); return ( - Your details + } sub="Change them here and the church's sites get them too.">Your details
{ e.preventDefault(); const f = new FormData(e.currentTarget); @@ -111,7 +202,7 @@ function Security({ me, onDone, onFail }: Props) { return ( - Signing in + }>Signing in

Two-step sign-in: {me.twoFactor ? on, with {METHOD[me.twoFactor]} : off} {me.twoFactor && · {me.recoveryCodesLeft} recovery codes left} @@ -193,7 +284,7 @@ function Privacy({ me, onDone, onFail }: Props) { return ( - Privacy + }>Privacy { const f = new FormData(e.currentTarget); const r = await call("PUT", "/me/news", { email: f.get("email") === "on", whatsapp: f.get("whatsapp") === "on" }); @@ -249,7 +340,7 @@ function Activity({ onDone }: { onDone: (t: string) => void }) { }, []); return ( - Recent activity + } sub="If you see something you don't recognise, change your password and sign out everywhere.">Recent activity

    {items.map((e, i) => (
  • diff --git a/apps/accounts/frontend/src/app/account/[section]/page.tsx b/apps/accounts/frontend/src/app/account/[section]/page.tsx new file mode 100644 index 0000000..37bf3f1 --- /dev/null +++ b/apps/accounts/frontend/src/app/account/[section]/page.tsx @@ -0,0 +1,16 @@ +import { notFound } from "next/navigation"; +import { Account, type AccountSection } from "../Account"; + +const TITLES: Record = { details: "Your details", security: "Signing in", privacy: "Privacy", activity: "Activity" }; + +export async function generateMetadata({ params }: { params: Promise<{ section: string }> }) { + const { section } = await params; + return { title: TITLES[section] ?? "Your account" }; +} + +/** One section of the account page (1.3.0): /account/details, /security, /privacy, /activity. */ +export default async function AccountSectionPage({ params }: { params: Promise<{ section: string }> }) { + const { section } = await params; + if (!(section in TITLES)) notFound(); + return ; +} diff --git a/apps/accounts/frontend/src/app/account/confirm-email/ConfirmEmail.tsx b/apps/accounts/frontend/src/app/account/confirm-email/ConfirmEmail.tsx index 9789885..8c622cf 100644 --- a/apps/accounts/frontend/src/app/account/confirm-email/ConfirmEmail.tsx +++ b/apps/accounts/frontend/src/app/account/confirm-email/ConfirmEmail.tsx @@ -1,5 +1,6 @@ "use client"; +import Link from "next/link"; import { useState } from "react"; import { Card, Heading, Notice, Shell } from "@crosscode/ui"; import { useBranding } from "@/components/BrandingProvider"; @@ -23,7 +24,7 @@ export function ConfirmEmail({ token }: { token: string }) { Your email address {state ? {state.text} :

    Confirming…

    } - Back to your account + Back to your account
    ); diff --git a/apps/accounts/frontend/src/app/admin/Admin.tsx b/apps/accounts/frontend/src/app/admin/Admin.tsx index 8fd3845..187d266 100644 --- a/apps/accounts/frontend/src/app/admin/Admin.tsx +++ b/apps/accounts/frontend/src/app/admin/Admin.tsx @@ -1,63 +1,70 @@ "use client"; +import Link from "next/link"; import React, { useCallback, useState } from "react"; -import { Button, Card, Checkbox, Field, Heading, Notice, Shell } from "@crosscode/ui"; -import { useBranding } from "@/components/BrandingProvider"; +import { DatabaseBackup, Download } from "lucide-react"; +import { Button, Checkbox, Field, Notice } from "@crosscode/ui"; +import { AppShell, PageTitle, ShellLoading, type ShellUser } from "@/components/AppShell"; +import { NoticeText } from "@/components/NoticeText"; +import { Card, Heading } from "@/components/Panel"; import { call, selfSignIn } from "@/lib/api"; import { useExternalEffect } from "@/lib/hooks"; +import { ADMIN_SECTIONS, type AdminSection } from "@/lib/sections"; -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("people"); +/** + * Accounts' admin (docs/ACCOUNTS-1.0-PLAN.md §8). Admins only, signed in with their second step. + * 1.3.0: one section per address, down the side (as Cross Events' settings), and Backups. + */ +export function Admin({ section = "people" }: { section?: AdminSection }) { + const s = ADMIN_SECTIONS[section] ?? ADMIN_SECTIONS.people; + const [me, setMe] = useState(null); const [allowed, setAllowed] = useState(null); const [msg, setMsg] = useState<{ tone: "success" | "error"; text: string } | null>(null); useExternalEffect(() => { let alive = true; - call("GET", "/admin/licence").then((r) => { + Promise.all([call("GET", "/me"), call("GET", "/admin/licence")]).then(([who, 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")); + if (who.status === 401 || r.status === 401) return window.location.assign(selfSignIn(s.path)); + if (!r.ok && r.error.code === "MFA_REQUIRED") return window.location.assign(selfSignIn(s.path, "&acr=mfa")); + if (who.ok) setMe(who.data); setAllowed(r.ok); }); return () => { alive = false; }; - }, []); + }, [s.path]); const flash: Flash = (tone, text) => setMsg({ tone, text }); - if (allowed === null) return

    Loading…

    ; - if (!allowed) return Only Accounts admins can open this page.Your account; + if (allowed === null || !me) return ; + if (!allowed) { + return ( + +
    Only Accounts admins can open this page.Your account
    +
    + ); + } return ( - Your account}> -

    Accounts admin

    - + + {s.title} {msg && {msg.text}} - {tab === "people" && } - {tab === "deletions" && } - {tab === "church" && } - {tab === "linked" && } - {tab === "signin" && } - {tab === "messages" && } - {tab === "notice" && } - {tab === "licence" && } - {tab === "audit" && } -
    + {section === "people" && } +
    + {section === "deletions" && } + {section === "church" && } + {section === "linked" && } + {section === "signin" && } + {section === "messages" && } + {section === "notice" && } + {section === "backups" && } + {section === "licence" && } + {section === "audit" && } +
    + ); } @@ -292,30 +299,48 @@ function Settings({ flash, keys }: { flash: Flash; keys: string[] }) { // ─── Privacy notice, licence, audit ─────────────────────────────────────────── +type NoticeVersion = { version: number; title: string; body: string }; + function NoticeTab({ flash }: { flash: Flash }) { - const [current, setCurrent] = useState<{ version: number; title: string; body: string } | null>(null); + const [data, setData] = useState<{ current: NoticeVersion; builtIn: NoticeVersion | null } | null>(null); + const [draft, setDraft] = useState<{ 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); + const r = await call<{ current: NoticeVersion; builtIn?: NoticeVersion }>("GET", "/admin/notices"); + if (r.ok) { setData({ current: r.data.current, builtIn: r.data.builtIn ?? null }); setDraft({ title: r.data.current.title, body: r.data.current.body }); } }, []); useExternalEffect(() => { void load(); }, [load]); - if (!current) return

    Loading…

    ; + if (!data || !draft) return

    Loading…

    ; + const { current, builtIn } = data; + const isBuiltIn = current.version === 1; return ( - - Privacy notice - { - 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); - }}> - - -