app: the admin's backend: members and roles, jobs, logs, the setup checklist (APP-1.0-PLAN §10)
Members and roles: members searched by name or email with what they hold; roles given and taken by an Owner or Church admin (only an Owner makes or changes an Owner, nobody changes their own), or someone added by email with a role through Accounts' people.ensure. Background jobs: each job's switch and schedule (winning over the .env) and Run now. The audit log and the access log in plain words, 100 at a time. The dashboard's overview adds the setup checklist (the church's details and icon, the wall's rules, prayer coordinators, a first announcement, sharing the App), this week's coverage and gaps, what waits for the prayer team and recent changes, each for the roles it's about; Share the App marks the checklist. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,79 @@
|
|||||||
|
/**
|
||||||
|
* The audit log (who changed what) and the access log (who saw names on the prayer wall and in
|
||||||
|
* prayer requests), APP-1.0-PLAN §10, newest first, 100 at a time (`before` for the next page).
|
||||||
|
* Owner and Church admin only. Names come from the members; the system and Accounts by role.
|
||||||
|
*/
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
|
||||||
|
const ACTIONS: Record<string, string> = {
|
||||||
|
modules_changed: 'Switched modules on or off',
|
||||||
|
member_roles_changed: 'Changed someone\'s roles', member_added: 'Added someone with a role', member_deleted: 'An account was deleted in Accounts', member_signed_out: 'Signed out',
|
||||||
|
first_owner_signed_in: 'Signed in as the first Owner', member_signed_in: 'Signed in',
|
||||||
|
job_settings_changed: 'Changed a background job', job_run: 'Ran a background job',
|
||||||
|
backup_made: 'Made a backup', backup_downloaded: 'Downloaded a backup', backup_settings_changed: 'Changed the backup settings',
|
||||||
|
messaging_fetched: 'Fetched the email and WhatsApp settings', messaging_test_sent: 'Sent a test message',
|
||||||
|
product_link_connected: 'Connected a product', product_link_disconnected: 'Disconnected a product', event_feed_changed: 'Changed the event feed',
|
||||||
|
prayer_wall_changed: 'Changed the prayer wall\'s rules', prayer_booked_for_member: 'Booked a slot for a member', prayer_commitment_cancelled: 'Cancelled a prayer slot',
|
||||||
|
prayer_campaign_created: 'Started a campaign', prayer_campaign_changed: 'Changed a campaign', prayer_campaign_deleted: 'Deleted a campaign',
|
||||||
|
testimony_approved: 'Shared a testimony', testimony_removed: 'Didn\'t share a testimony',
|
||||||
|
prayer_request_approved: 'Approved a prayer request', prayer_request_redacted: 'Edited a prayer request', prayer_request_removed: 'Didn\'t share a prayer request',
|
||||||
|
prayer_request_escalated: 'Escalated a prayer request', prayer_request_replied: 'Replied to a prayer request', request_settings_changed: 'Changed the prayer request settings',
|
||||||
|
announcement_created: 'Wrote an announcement', announcement_changed: 'Changed an announcement', announcement_deleted: 'Deleted an announcement',
|
||||||
|
devotional_created: 'Wrote a devotional', devotional_changed: 'Changed a devotional', devotional_deleted: 'Deleted a devotional',
|
||||||
|
devotionals_imported: 'Imported devotionals', devotionals_source_changed: 'Changed where devotionals come from',
|
||||||
|
event_created: 'Added an event', event_changed: 'Changed an event', event_deleted: 'Deleted an event',
|
||||||
|
media_uploaded: 'Uploaded an image', media_deleted: 'Deleted an image', app_shared: 'Marked the App as shared',
|
||||||
|
};
|
||||||
|
|
||||||
|
const ACCESS: Record<string, string> = {
|
||||||
|
prayer_bookings_viewed: 'Saw who prays when', members_searched: 'Searched members to book for',
|
||||||
|
testimonies_viewed: 'Saw testimonies with names', prayer_requests_viewed: 'Saw prayer requests with their senders',
|
||||||
|
};
|
||||||
|
|
||||||
|
const ACTORS: Record<string, string> = { system: 'The App itself', linked_product: 'A linked product', accounts: 'Accounts' };
|
||||||
|
|
||||||
|
const TAKE = 100;
|
||||||
|
|
||||||
|
function since(before?: string) {
|
||||||
|
const d = before ? new Date(before) : null;
|
||||||
|
return d && Number.isFinite(d.getTime()) ? { createdAt: { lt: d } } : {};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function names(ctx: Ctx, ids: (string | null)[]) {
|
||||||
|
const wanted = [...new Set(ids.filter((x): x is string => !!x))];
|
||||||
|
const rows = wanted.length ? await ctx.db.member.findMany({ where: { id: { in: wanted } }, select: { id: true, name: true } }) : [];
|
||||||
|
return new Map(rows.map((m) => [m.id, m.name]));
|
||||||
|
}
|
||||||
|
|
||||||
|
const detailOf = (meta: Record<string, unknown>) => {
|
||||||
|
const d = [meta.title, meta.label, meta.name, meta.view, meta.product].find((x) => typeof x === 'string');
|
||||||
|
return typeof d === 'string' ? d : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function auditLog(ctx: Ctx, opts: { before?: string; take?: number } = {}) {
|
||||||
|
const rows = await ctx.db.auditLog.findMany({ where: since(opts.before), orderBy: { createdAt: 'desc' }, take: Math.min(TAKE, opts.take ?? TAKE) });
|
||||||
|
const who = await names(ctx, rows.map((r) => r.actorId));
|
||||||
|
return rows.map((r) => ({
|
||||||
|
at: r.createdAt.toISOString(),
|
||||||
|
who: (r.actorId && who.get(r.actorId)) || ACTORS[r.actorRole] || 'Someone',
|
||||||
|
action: ACTIONS[r.action] ?? r.action.replace(/_/g, ' '),
|
||||||
|
detail: detailOf((r.metadata ?? {}) as Record<string, unknown>),
|
||||||
|
ip: r.ip,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function accessLogList(ctx: Ctx, opts: { before?: string } = {}) {
|
||||||
|
const rows = await ctx.db.accessLog.findMany({ where: since(opts.before), orderBy: { createdAt: 'desc' }, take: TAKE });
|
||||||
|
const who = await names(ctx, rows.map((r) => r.actorId));
|
||||||
|
return rows.map((r) => {
|
||||||
|
const meta = (r.metadata ?? {}) as Record<string, unknown>;
|
||||||
|
const count = [meta.people, meta.count, meta.results].find((x) => typeof x === 'number');
|
||||||
|
return {
|
||||||
|
at: r.createdAt.toISOString(),
|
||||||
|
who: who.get(r.actorId) ?? 'Someone',
|
||||||
|
action: ACCESS[r.action] ?? r.action.replace(/_/g, ' '),
|
||||||
|
detail: [r.targetType === 'prayer_day' ? r.targetId : null, typeof meta.view === 'string' ? meta.view : null, typeof count === 'number' ? `${count} shown` : null].filter(Boolean).join(' · ') || null,
|
||||||
|
ip: r.ip,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
/**
|
||||||
|
* Members and roles (APP-1.0-PLAN §10, decision 7). Everyone who signs in is a Member; roles are the
|
||||||
|
* App's own, keyed by the account's `sub` in the church's Accounts, and every one needs a 2FA
|
||||||
|
* sign-in to use what it adds (§2).
|
||||||
|
*
|
||||||
|
* Owner everything, including who is Owner
|
||||||
|
* Church admin everything but Owners (can't make one, or change or take an Owner's roles)
|
||||||
|
* Others can't manage roles
|
||||||
|
*
|
||||||
|
* Someone who hasn't used the App yet is added by email: Accounts makes them an account if they
|
||||||
|
* have none (`people.ensure`, with a "choose your password" email). Nobody changes their own
|
||||||
|
* roles, so the App is never left without an Owner by accident.
|
||||||
|
*/
|
||||||
|
import { z } from 'zod';
|
||||||
|
import type { Ctx } from '../context.js';
|
||||||
|
import type { AppRole, Prisma } from '../generated/prisma/client.js';
|
||||||
|
import { accounts } from '../auth/accounts.js';
|
||||||
|
import { ROLES } from '../auth/sessions.js';
|
||||||
|
import { ApiError, parse } from '../http.js';
|
||||||
|
import { audit } from '../lib/audit.js';
|
||||||
|
|
||||||
|
type Who = { id: string; roles: AppRole[]; ip: string | null };
|
||||||
|
|
||||||
|
const roleList = z.array(z.enum(ROLES as [AppRole, ...AppRole[]])).max(ROLES.length).transform((r) => [...new Set(r)]);
|
||||||
|
|
||||||
|
export const addBody = z.object({
|
||||||
|
name: z.string().trim().min(1).max(200),
|
||||||
|
email: z.email().trim().toLowerCase().max(254),
|
||||||
|
roles: roleList,
|
||||||
|
}).strict();
|
||||||
|
|
||||||
|
export const rolesBody = z.object({ roles: roleList }).strict();
|
||||||
|
|
||||||
|
const PAGE = 50;
|
||||||
|
|
||||||
|
/** May `by` change someone with `current` roles to `next`? Throws why not. */
|
||||||
|
function mayChange(by: Who, current: AppRole[], next: AppRole[]) {
|
||||||
|
const owner = by.roles.includes('owner');
|
||||||
|
if (!owner && !by.roles.includes('church_admin')) throw new ApiError(403, 'FORBIDDEN', 'Only an Owner or Church admin can give roles.');
|
||||||
|
if (!owner && (current.includes('owner') || next.includes('owner'))) throw new ApiError(403, 'OWNERS_ONLY', 'Only an Owner can make someone an Owner, or change an Owner\'s roles.');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Members, with roles first (those with one), then by name; `q` searches names and emails. */
|
||||||
|
export async function listMembers(ctx: Ctx, opts: { q?: string; role?: string; page?: number }) {
|
||||||
|
const q = opts.q?.trim().slice(0, 100);
|
||||||
|
const where: Prisma.MemberWhereInput = {
|
||||||
|
...(q ? { OR: [{ name: { contains: q, mode: 'insensitive' } }, { email: { contains: q, mode: 'insensitive' } }] } : {}),
|
||||||
|
...(opts.role === 'any' ? { roles: { isEmpty: false } } : opts.role && (ROLES as readonly string[]).includes(opts.role) ? { roles: { has: opts.role as AppRole } } : {}),
|
||||||
|
};
|
||||||
|
const page = Math.max(1, Math.floor(opts.page ?? 1));
|
||||||
|
const [total, rows, withRoles] = await Promise.all([
|
||||||
|
ctx.db.member.count({ where }),
|
||||||
|
ctx.db.member.findMany({ where, orderBy: [{ name: 'asc' }], skip: (page - 1) * PAGE, take: PAGE }),
|
||||||
|
ctx.db.member.findMany({ where: { roles: { isEmpty: false } }, select: { roles: true } }),
|
||||||
|
]);
|
||||||
|
return {
|
||||||
|
total, page, pageSize: PAGE,
|
||||||
|
/** How many hold each role (the page's header). */
|
||||||
|
roleCounts: Object.fromEntries(ROLES.map((r) => [r, withRoles.filter((m) => m.roles.includes(r)).length])),
|
||||||
|
members: rows.map((m) => ({
|
||||||
|
id: m.id, name: m.name, email: m.email, roles: m.roles, hasPhone: !!m.phone, whatsappStopped: m.whatsappOptedOut,
|
||||||
|
lastActiveAt: m.lastActiveAt?.toISOString() ?? null, lastSignInAt: m.lastSignInAt?.toISOString() ?? null, since: m.createdAt.toISOString(),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function setRoles(ctx: Ctx, id: string, body: unknown, by: Who) {
|
||||||
|
const { roles } = parse(rolesBody, body);
|
||||||
|
if (id === by.id) throw new ApiError(400, 'SELF', 'You can\'t change your own roles. Ask another Owner or Church admin.');
|
||||||
|
const member = await ctx.db.member.findUnique({ where: { id } });
|
||||||
|
if (!member) throw new ApiError(404, 'NOT_FOUND', 'There\'s no such member.');
|
||||||
|
mayChange(by, member.roles, roles);
|
||||||
|
const sorted = ROLES.filter((r) => roles.includes(r));
|
||||||
|
await ctx.db.member.update({ where: { id }, data: { roles: sorted } });
|
||||||
|
await audit(ctx, { actorId: by.id, actorRole: by.roles.join(','), action: 'member_roles_changed', targetType: 'member', targetId: id, metadata: { from: member.roles, to: sorted }, ip: by.ip });
|
||||||
|
return { id, roles: sorted };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Adds someone by email with roles: their account at Accounts (made if they have none), then here. */
|
||||||
|
export async function addMember(ctx: Ctx, body: unknown, by: Who) {
|
||||||
|
const p = parse(addBody, body);
|
||||||
|
if (!p.roles.length) throw new ApiError(400, 'VALIDATION', 'Choose at least one role: everyone who signs in is a Member already.', { roles: 'Choose a role' });
|
||||||
|
const known = await ctx.db.member.findFirst({ where: { email: p.email } });
|
||||||
|
mayChange(by, known?.roles ?? [], p.roles);
|
||||||
|
const reply = await (await accounts(ctx)).request<{ sub: string; created: boolean; emailSent?: boolean }>({
|
||||||
|
type: 'people.ensure', actor: by.id, name: p.name, email: p.email, phone: null, returnUrl: `${ctx.config.publicUrl}/admin`,
|
||||||
|
});
|
||||||
|
if (reply.sub === by.id) throw new ApiError(400, 'SELF', 'You can\'t change your own roles. Ask another Owner or Church admin.');
|
||||||
|
const existing = await ctx.db.member.findUnique({ where: { id: reply.sub } });
|
||||||
|
if (existing) mayChange(by, existing.roles, p.roles);
|
||||||
|
const roles = ROLES.filter((r) => p.roles.includes(r) || existing?.roles.includes(r));
|
||||||
|
const member = existing
|
||||||
|
? await ctx.db.member.update({ where: { id: existing.id }, data: { roles } })
|
||||||
|
: await ctx.db.member.create({ data: { id: reply.sub, name: p.name, email: p.email, roles } });
|
||||||
|
await audit(ctx, { actorId: by.id, actorRole: by.roles.join(','), action: 'member_added', targetType: 'member', targetId: member.id, metadata: { roles, newAccount: reply.created, before: existing?.roles ?? null }, ip: by.ip });
|
||||||
|
return { id: member.id, roles, newAccount: reply.created, emailSent: reply.emailSent ?? null, alreadyMember: !!existing };
|
||||||
|
}
|
||||||
@@ -1,26 +1,68 @@
|
|||||||
/**
|
/**
|
||||||
* The admin API (APP-1.0-PLAN §10), under /api/v1/admin. Every route needs a role above Member and
|
* The admin API (APP-1.0-PLAN §10), under /api/v1/admin. Every route needs a role above Member and
|
||||||
* a sign-in with 2FA (auth/sessions.ts `requireRole`).
|
* a sign-in with 2FA (auth/sessions.ts `requireRole`). Each module's own admin is in its folder
|
||||||
|
* (prayer/admin.ts, requests/routes.ts, content/routes.ts, messaging/routes.ts).
|
||||||
*
|
*
|
||||||
* GET /overview the dashboard: active members and band, modules, the Hub and Accounts links
|
* GET /overview the dashboard: active members and band, modules, the Hub and Accounts,
|
||||||
|
* the setup checklist, this week's coverage and gaps, what's waiting,
|
||||||
|
* recent changes (each part only for the roles and modules it's about)
|
||||||
* PUT /modules switch modules on or off (Owner, Church admin)
|
* PUT /modules switch modules on or off (Owner, Church admin)
|
||||||
*
|
* GET /members?q=&role=&page= members and their roles (Owner, Church admin)
|
||||||
* The rest comes with each module (§10): House of Prayer, requests, announcements, devotionals,
|
* POST /members { name, email, roles }: someone with a role, by email (people.ensure)
|
||||||
* events, members and roles, settings, audit and access logs.
|
* PUT /members/:id/roles { roles }
|
||||||
|
* GET /jobs, PUT /jobs/:name { enabled?, cron? }, POST /jobs/:name/run Background jobs
|
||||||
|
* GET /audit?before= the audit log; GET /access?before= the access log
|
||||||
|
* GET /share, POST /share the App's link (and the poster), and "shared" for the checklist
|
||||||
*/
|
*/
|
||||||
import express from 'express';
|
import express, { type Request } from 'express';
|
||||||
import { z } from 'zod';
|
import { z } from 'zod';
|
||||||
import { APP_MODULES } from '@crosscode/contracts';
|
import { APP_MODULES } from '@crosscode/contracts';
|
||||||
import type { Ctx } from '../context.js';
|
import type { Ctx } from '../context.js';
|
||||||
import { ApiError, handle, sameOrigin } from '../http.js';
|
import { ApiError, handle, sameOrigin } from '../http.js';
|
||||||
import { audit, clientIp } from '../lib/audit.js';
|
import { audit, clientIp } from '../lib/audit.js';
|
||||||
import { requireRole } from '../auth/sessions.js';
|
import { hasRole, requireRole } from '../auth/sessions.js';
|
||||||
|
import { churchProfile, churchTimezone } from '../church/profile.js';
|
||||||
import { licenceStatus } from '../hub/licence.js';
|
import { licenceStatus } from '../hub/licence.js';
|
||||||
|
import { JobError, jobStatus, runNow, setOverride } from '../jobs.js';
|
||||||
|
import { addDays, localDate } from '../lib/zoned.js';
|
||||||
import { activeMembers } from '../members/activity.js';
|
import { activeMembers } from '../members/activity.js';
|
||||||
import { enabledModules, setModules } from '../modules.js';
|
import { enabledModules, setModules } from '../modules.js';
|
||||||
|
import { wallDay } from '../prayer/service.js';
|
||||||
|
import { wallSettings } from '../prayer/wall.js';
|
||||||
|
import { accessLogList, auditLog } from './logs.js';
|
||||||
|
import { addMember, listMembers, setRoles } from './members.js';
|
||||||
|
|
||||||
const modulesBody = z.object(Object.fromEntries(APP_MODULES.map((m) => [m, z.boolean().optional()]))).strict();
|
const modulesBody = z.object(Object.fromEntries(APP_MODULES.map((m) => [m, z.boolean().optional()]))).strict();
|
||||||
|
|
||||||
|
const who = (req: Request) => ({ id: req.signed!.member.id, roles: req.signed!.member.roles, ip: clientIp(req) });
|
||||||
|
const FULL = ['owner', 'church_admin'] as const;
|
||||||
|
|
||||||
|
/** The setup checklist (§10): what a new App needs before it's announced, for the modules that are on. */
|
||||||
|
async function checklist(ctx: Ctx, modules: string[]) {
|
||||||
|
const [profile, wall, coordinators, announcement, shared] = await Promise.all([
|
||||||
|
churchProfile(ctx),
|
||||||
|
ctx.settings.get('prayer_wall'),
|
||||||
|
ctx.db.member.count({ where: { roles: { has: 'prayer_coordinator' } } }),
|
||||||
|
ctx.db.announcement.findFirst({ where: { publishAt: { not: null } }, select: { id: true } }),
|
||||||
|
ctx.settings.get('app_shared_at'),
|
||||||
|
]);
|
||||||
|
const accounts = profile?.links.accounts ?? null;
|
||||||
|
const items = [
|
||||||
|
{ key: 'church', label: 'Check the church\'s details and icon (in Accounts)', done: !!profile && !!(profile.branding.iconUrl || profile.branding.logoUrl), href: accounts ? `${accounts.replace(/\/+$/, '')}/admin/church` : null },
|
||||||
|
...(modules.includes('house-of-prayer') ? [
|
||||||
|
{ key: 'wall', label: 'Set the prayer wall\'s rules', done: !!wall, href: '/admin/prayer' },
|
||||||
|
] : []),
|
||||||
|
...(modules.includes('house-of-prayer') || modules.includes('prayer-requests') ? [
|
||||||
|
{ key: 'coordinators', label: 'Add prayer coordinators', done: coordinators > 0, href: '/admin/members' },
|
||||||
|
] : []),
|
||||||
|
...(modules.includes('announcements') ? [
|
||||||
|
{ key: 'announcement', label: 'Write a first announcement', done: !!announcement, href: '/admin/announcements' },
|
||||||
|
] : []),
|
||||||
|
{ key: 'share', label: 'Share the App: its link and a poster with a QR code', done: !!shared, href: '/admin/share' },
|
||||||
|
];
|
||||||
|
return { items, done: items.every((i) => i.done) };
|
||||||
|
}
|
||||||
|
|
||||||
export function adminRouter(ctx: Ctx) {
|
export function adminRouter(ctx: Ctx) {
|
||||||
const r = express.Router();
|
const r = express.Router();
|
||||||
r.use(sameOrigin(ctx.config.publicUrl, ctx.config.production));
|
r.use(sameOrigin(ctx.config.publicUrl, ctx.config.production));
|
||||||
@@ -29,24 +71,54 @@ export function adminRouter(ctx: Ctx) {
|
|||||||
res.set('Cache-Control', 'no-store');
|
res.set('Cache-Control', 'no-store');
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
|
const full = requireRole(ctx, FULL);
|
||||||
|
const jobError = (e: unknown): never => {
|
||||||
|
if (e instanceof JobError) throw new ApiError(e.status, e.status === 404 ? 'NOT_FOUND' : e.status === 400 ? 'VALIDATION' : 'JOB_FAILED', e.message);
|
||||||
|
throw e;
|
||||||
|
};
|
||||||
|
|
||||||
r.get('/overview', requireRole(ctx), handle(async () => {
|
r.get('/overview', requireRole(ctx), handle(async (req) => {
|
||||||
const [members, modules, licence, accounts, lastHeartbeatAt] = await Promise.all([
|
const roles = req.signed!.activeRoles;
|
||||||
|
const [members, modules, licence, accounts, lastHeartbeatAt, tz] = await Promise.all([
|
||||||
activeMembers(ctx),
|
activeMembers(ctx),
|
||||||
enabledModules(ctx),
|
enabledModules(ctx),
|
||||||
licenceStatus(ctx),
|
licenceStatus(ctx),
|
||||||
ctx.db.productLink.findFirst({ where: { product: 'accounts' } }),
|
ctx.db.productLink.findFirst({ where: { product: 'accounts' } }),
|
||||||
ctx.settings.get('hub_last_heartbeat_at'),
|
ctx.settings.get('hub_last_heartbeat_at'),
|
||||||
|
churchTimezone(ctx),
|
||||||
]);
|
]);
|
||||||
|
const isFull = hasRole(roles, FULL);
|
||||||
|
const prayerTeam = hasRole(roles, ['prayer_coordinator']);
|
||||||
|
let week = null;
|
||||||
|
if (modules.includes('house-of-prayer') && (isFull || prayerTeam)) {
|
||||||
|
const wall = await wallSettings(ctx);
|
||||||
|
const today = localDate(ctx.now(), tz);
|
||||||
|
const days = [];
|
||||||
|
for (let i = 0; i < 7; i++) {
|
||||||
|
const d = await wallDay(ctx, addDays(today, i), wall, tz);
|
||||||
|
days.push({ date: d.date, covered: d.covered, total: d.total, gaps: d.slots.filter((s) => !s.covered).map((s) => s.minute) });
|
||||||
|
}
|
||||||
|
week = { slotMinutes: wall.slotMinutes, days };
|
||||||
|
}
|
||||||
|
const waiting = {
|
||||||
|
requests: modules.includes('prayer-requests') && (isFull || prayerTeam) ? await ctx.db.prayerRequest.count({ where: { moderation: 'pending', closedAt: null, escalatedAt: null } }) : null,
|
||||||
|
escalated: modules.includes('prayer-requests') && hasRole(roles, ['pastoral_care']) ? await ctx.db.prayerRequest.count({ where: { escalatedAt: { not: null }, closedAt: null } }) : null,
|
||||||
|
testimonies: modules.includes('house-of-prayer') && (isFull || prayerTeam) ? await ctx.db.testimony.count({ where: { status: 'pending' } }) : null,
|
||||||
|
};
|
||||||
return {
|
return {
|
||||||
activeMembers90d: members,
|
activeMembers90d: members,
|
||||||
modules,
|
modules,
|
||||||
hub: { connected: licence.connected, state: licence.state, endsAt: licence.endsAt, daysLeft: licence.daysLeft, lastHeartbeatAt },
|
hub: { connected: licence.connected, state: licence.state, endsAt: licence.endsAt, daysLeft: licence.daysLeft, lastHeartbeatAt },
|
||||||
accounts: accounts ? { url: accounts.url, connectedAt: accounts.connectedAt } : null,
|
accounts: accounts ? { url: accounts.url, connectedAt: accounts.connectedAt } : null,
|
||||||
|
timezone: tz,
|
||||||
|
checklist: isFull ? await checklist(ctx, modules) : null,
|
||||||
|
week,
|
||||||
|
waiting,
|
||||||
|
recent: isFull ? (await auditLog(ctx, { take: 30 })).filter((e) => !/^Signed (in|out)/.test(e.action)).slice(0, 6) : [],
|
||||||
};
|
};
|
||||||
}));
|
}));
|
||||||
|
|
||||||
r.put('/modules', requireRole(ctx, ['owner', 'church_admin']), handle(async (req) => {
|
r.put('/modules', full, handle(async (req) => {
|
||||||
const parsed = modulesBody.safeParse(req.body);
|
const parsed = modulesBody.safeParse(req.body);
|
||||||
if (!parsed.success) throw new ApiError(400, 'VALIDATION', `Send the modules to switch as { "<module>": true | false }: ${APP_MODULES.join(', ')}.`);
|
if (!parsed.success) throw new ApiError(400, 'VALIDATION', `Send the modules to switch as { "<module>": true | false }: ${APP_MODULES.join(', ')}.`);
|
||||||
const change = Object.fromEntries(Object.entries(parsed.data).filter(([, v]) => typeof v === 'boolean')) as Record<string, boolean>;
|
const change = Object.fromEntries(Object.entries(parsed.data).filter(([, v]) => typeof v === 'boolean')) as Record<string, boolean>;
|
||||||
@@ -55,5 +127,46 @@ export function adminRouter(ctx: Ctx) {
|
|||||||
return { modules };
|
return { modules };
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
// ─── Members and roles ───
|
||||||
|
r.get('/members', full, handle((req) => listMembers(ctx, {
|
||||||
|
q: typeof req.query.q === 'string' ? req.query.q : undefined,
|
||||||
|
role: typeof req.query.role === 'string' ? req.query.role : undefined,
|
||||||
|
page: Number(req.query.page) || 1,
|
||||||
|
})));
|
||||||
|
r.post('/members', full, handle((req) => addMember(ctx, req.body, who(req))));
|
||||||
|
r.put('/members/:id/roles', full, handle((req) => setRoles(ctx, String(req.params.id), req.body, who(req))));
|
||||||
|
|
||||||
|
// ─── Background jobs (Settings → Background jobs) ───
|
||||||
|
r.get('/jobs', full, handle(() => jobStatus(ctx)));
|
||||||
|
r.put('/jobs/:name', full, handle(async (req) => {
|
||||||
|
const name = String(req.params.name);
|
||||||
|
const out = await setOverride(ctx, name, { enabled: req.body?.enabled, cron: req.body?.cron }).catch(jobError);
|
||||||
|
await audit(ctx, { actorId: req.signed!.member.id, actorRole: req.signed!.member.roles.join(','), action: 'job_settings_changed', targetType: 'job', targetId: name, metadata: { ...out, label: name }, ip: clientIp(req) });
|
||||||
|
return { name, override: out };
|
||||||
|
}));
|
||||||
|
r.post('/jobs/:name/run', full, handle(async (req) => {
|
||||||
|
const name = String(req.params.name);
|
||||||
|
const out = await runNow(ctx, name).catch(jobError);
|
||||||
|
await audit(ctx, { actorId: req.signed!.member.id, actorRole: req.signed!.member.roles.join(','), action: 'job_run', targetType: 'job', targetId: name, metadata: { queued: out.queued, label: name }, ip: clientIp(req) });
|
||||||
|
return out;
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ─── Audit and access logs ───
|
||||||
|
const before = (req: Request) => (typeof req.query.before === 'string' ? req.query.before : undefined);
|
||||||
|
r.get('/audit', full, handle(async (req) => ({ entries: await auditLog(ctx, { before: before(req) }) })));
|
||||||
|
r.get('/access', full, handle(async (req) => ({ entries: await accessLogList(ctx, { before: before(req) }) })));
|
||||||
|
|
||||||
|
// ─── Share the App ───
|
||||||
|
r.get('/share', full, handle(async () => {
|
||||||
|
const profile = await churchProfile(ctx);
|
||||||
|
return { url: ctx.config.publicUrl, name: profile?.name ?? null, sharedAt: await ctx.settings.get('app_shared_at') };
|
||||||
|
}));
|
||||||
|
r.post('/share', full, handle(async (req) => {
|
||||||
|
const at = ctx.now().toISOString();
|
||||||
|
await ctx.settings.set('app_shared_at', at);
|
||||||
|
await audit(ctx, { actorId: req.signed!.member.id, actorRole: req.signed!.member.roles.join(','), action: 'app_shared', targetType: 'settings', targetId: 'share', ip: clientIp(req) });
|
||||||
|
return { sharedAt: at };
|
||||||
|
}));
|
||||||
|
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,119 @@
|
|||||||
|
import { describe, it } from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import request from 'supertest';
|
||||||
|
import { cookieHeader, harness, MEMBER, PASTOR, signInAs, type Harness } from './support/harness.js';
|
||||||
|
|
||||||
|
const ADMIN = '22222222-2222-4222-8222-222222222222';
|
||||||
|
const COORD = '55555555-5555-4555-8555-555555555555';
|
||||||
|
const ORIGIN = 'https://app.hope.test';
|
||||||
|
|
||||||
|
async function setup() {
|
||||||
|
const h = await harness() as Harness;
|
||||||
|
const as = (cookies: Record<string, string>) => ({
|
||||||
|
get: (path: string) => request(h.app).get(path).set('Cookie', cookieHeader(cookies)),
|
||||||
|
post: (path: string, body: object = {}) => request(h.app).post(path).set('Cookie', cookieHeader(cookies)).set('Origin', ORIGIN).send(body),
|
||||||
|
put: (path: string, body: object) => request(h.app).put(path).set('Cookie', cookieHeader(cookies)).set('Origin', ORIGIN).send(body),
|
||||||
|
});
|
||||||
|
const owner = as(await signInAs(h, { sub: PASTOR, name: 'Pastor Sam', email: 'pastor@hope.test', roles: ['owner'] }, true));
|
||||||
|
const admin = as(await signInAs(h, { sub: ADMIN, name: 'Nomsa Admin', email: 'nomsa@hope.test', roles: ['church_admin'] }, true));
|
||||||
|
const coord = as(await signInAs(h, { sub: COORD, name: 'Lerato Dlamini', email: 'lerato@hope.test', roles: ['prayer_coordinator'] }, true));
|
||||||
|
const member = as(await signInAs(h, { sub: MEMBER, name: 'Thandi Mokoena', email: 'thandi@hope.test' }));
|
||||||
|
return { h, owner, admin, coord, member };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('members and roles (§10)', () => {
|
||||||
|
it('lists members with their roles, searched by name or email, for an Owner or Church admin only', async () => {
|
||||||
|
const { owner, coord } = await setup();
|
||||||
|
assert.equal((await coord.get('/api/v1/admin/members')).status, 403);
|
||||||
|
const all = await owner.get('/api/v1/admin/members');
|
||||||
|
assert.equal(all.status, 200);
|
||||||
|
assert.equal(all.body.total, 4);
|
||||||
|
assert.equal(all.body.roleCounts.prayer_coordinator, 1);
|
||||||
|
const found = await owner.get('/api/v1/admin/members?q=THANDI');
|
||||||
|
assert.deepEqual(found.body.members.map((m: { name: string }) => m.name), ['Thandi Mokoena']);
|
||||||
|
const withRoles = await owner.get('/api/v1/admin/members?role=any');
|
||||||
|
assert.equal(withRoles.body.total, 3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('gives and takes roles: only an Owner makes an Owner, nobody changes their own', async () => {
|
||||||
|
const { h, owner, admin } = await setup();
|
||||||
|
assert.equal((await admin.put(`/api/v1/admin/members/${MEMBER}/roles`, { roles: ['prayer_coordinator', 'devotional_writer'] })).status, 200);
|
||||||
|
assert.deepEqual((await h.db.member.findUnique({ where: { id: MEMBER } }))!.roles, ['devotional_writer', 'prayer_coordinator']);
|
||||||
|
assert.equal((await admin.put(`/api/v1/admin/members/${MEMBER}/roles`, { roles: ['owner'] })).body.error.code, 'OWNERS_ONLY');
|
||||||
|
assert.equal((await admin.put(`/api/v1/admin/members/${PASTOR}/roles`, { roles: [] })).body.error.code, 'OWNERS_ONLY');
|
||||||
|
assert.equal((await owner.put(`/api/v1/admin/members/${PASTOR}/roles`, { roles: [] })).body.error.code, 'SELF');
|
||||||
|
assert.equal((await owner.put(`/api/v1/admin/members/${MEMBER}/roles`, { roles: ['owner'] })).status, 200);
|
||||||
|
assert.equal((await owner.put(`/api/v1/admin/members/${MEMBER}/roles`, { roles: ['pope'] })).status, 400);
|
||||||
|
const log = [...h.db.tables.get('auditLog')!.values()].filter((r) => r.action === 'member_roles_changed');
|
||||||
|
assert.equal(log.length, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('adds someone by email through Accounts, with their roles', async () => {
|
||||||
|
const { h, admin } = await setup();
|
||||||
|
const res = await admin.post('/api/v1/admin/members', { name: 'Johan Pretorius', email: 'Johan@Hope.test', roles: ['prayer_coordinator'] });
|
||||||
|
assert.equal(res.status, 200);
|
||||||
|
assert.equal(res.body.newAccount, true);
|
||||||
|
const ensure = h.fake.requests.find((r) => r.type === 'people.ensure')!;
|
||||||
|
assert.equal(ensure.email, 'johan@hope.test');
|
||||||
|
assert.equal(ensure.actor, ADMIN);
|
||||||
|
const m = await h.db.member.findUnique({ where: { id: res.body.id } });
|
||||||
|
assert.deepEqual(m!.roles, ['prayer_coordinator']);
|
||||||
|
// Again with another role: added to what they have.
|
||||||
|
const again = await admin.post('/api/v1/admin/members', { name: 'Johan Pretorius', email: 'johan@hope.test', roles: ['content_admin'] });
|
||||||
|
assert.equal(again.body.alreadyMember, true);
|
||||||
|
assert.deepEqual(again.body.roles, ['content_admin', 'prayer_coordinator']);
|
||||||
|
assert.equal((await admin.post('/api/v1/admin/members', { name: 'X', email: 'x@hope.test', roles: [] })).status, 400);
|
||||||
|
assert.equal((await admin.post('/api/v1/admin/members', { name: 'X', email: 'x@hope.test', roles: ['owner'] })).body.error.code, 'OWNERS_ONLY');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('the dashboard (§10)', () => {
|
||||||
|
it('has the setup checklist for an Owner, ticked as things get done', async () => {
|
||||||
|
const { owner, coord } = await setup();
|
||||||
|
const o = await owner.get('/api/v1/admin/overview');
|
||||||
|
assert.equal(o.status, 200);
|
||||||
|
const done = (body: { checklist: { items: { key: string; done: boolean }[] } }) => Object.fromEntries(body.checklist.items.map((i) => [i.key, i.done]));
|
||||||
|
assert.deepEqual(done(o.body), { church: false, wall: false, coordinators: true, announcement: false, share: false });
|
||||||
|
assert.equal(o.body.week.days.length, 7);
|
||||||
|
assert.equal(o.body.waiting.requests, 0);
|
||||||
|
assert.equal((await owner.post('/api/v1/admin/share')).status, 200);
|
||||||
|
assert.equal(done((await owner.get('/api/v1/admin/overview')).body).share, true);
|
||||||
|
// A coordinator: the week and the queue, not the checklist or the recent changes.
|
||||||
|
const c = await coord.get('/api/v1/admin/overview');
|
||||||
|
assert.equal(c.body.checklist, null);
|
||||||
|
assert.ok(c.body.week);
|
||||||
|
assert.deepEqual(c.body.recent, []);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('background jobs and the logs (§10)', () => {
|
||||||
|
it('lists the jobs, switches one off and runs one now', async () => {
|
||||||
|
const { h, owner, coord } = await setup();
|
||||||
|
assert.equal((await coord.get('/api/v1/admin/jobs')).status, 403);
|
||||||
|
const list = await owner.get('/api/v1/admin/jobs');
|
||||||
|
assert.ok(list.body.jobs.some((j: { name: string }) => j.name === 'messages-send'));
|
||||||
|
const off = await owner.put('/api/v1/admin/jobs/devotional-sends', { enabled: false });
|
||||||
|
assert.equal(off.body.override.enabled, false);
|
||||||
|
assert.equal((await owner.put('/api/v1/admin/jobs/devotional-sends', { cron: 'every minute' })).status, 400);
|
||||||
|
assert.equal((await owner.put('/api/v1/admin/jobs/nope', { enabled: false })).status, 404);
|
||||||
|
const run = await owner.post('/api/v1/admin/jobs/announcement-sends/run');
|
||||||
|
assert.equal(run.status, 200);
|
||||||
|
assert.equal(run.body.queued, false);
|
||||||
|
await owner.put('/api/v1/admin/jobs/devotional-sends', { enabled: null });
|
||||||
|
const log = [...h.db.tables.get('auditLog')!.values()].map((r) => r.action);
|
||||||
|
assert.ok(log.includes('job_settings_changed') && log.includes('job_run'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows the audit log and the access log with names, to an Owner or Church admin', async () => {
|
||||||
|
const { owner, coord } = await setup();
|
||||||
|
await owner.put(`/api/v1/admin/members/${MEMBER}/roles`, { roles: ['content_admin'] });
|
||||||
|
await coord.get('/api/v1/admin/prayer/bookings?date=2026-12-02');
|
||||||
|
const audit = await owner.get('/api/v1/admin/audit');
|
||||||
|
assert.equal(audit.body.entries[0].action, 'Changed someone\'s roles');
|
||||||
|
assert.equal(audit.body.entries[0].who, 'Pastor Sam');
|
||||||
|
const access = await owner.get('/api/v1/admin/access');
|
||||||
|
assert.equal(access.body.entries[0].who, 'Lerato Dlamini');
|
||||||
|
assert.equal(access.body.entries[0].action, 'Saw who prays when');
|
||||||
|
assert.equal((await coord.get('/api/v1/admin/access')).status, 403);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
* tested against Accounts' provider in apps/accounts/backend/tests/authClient.test.ts), linked to a
|
* tested against Accounts' provider in apps/accounts/backend/tests/authClient.test.ts), linked to a
|
||||||
* church's Accounts and registered with the Hub, and a clock the tests can move.
|
* church's Accounts and registered with the Hub, and a clock the tests can move.
|
||||||
*/
|
*/
|
||||||
|
import crypto from 'node:crypto';
|
||||||
import { IDENTITY_REQUEST_SCHEMA, type IdentityClaims } from '@crosscode/contracts';
|
import { IDENTITY_REQUEST_SCHEMA, type IdentityClaims } from '@crosscode/contracts';
|
||||||
import { sealLinkValue } from '@crosscode/contracts/signing';
|
import { sealLinkValue } from '@crosscode/contracts/signing';
|
||||||
import type { AuthClientModule } from '../../src/auth/accounts.js';
|
import type { AuthClientModule } from '../../src/auth/accounts.js';
|
||||||
@@ -27,6 +28,8 @@ export type FakeAccounts = {
|
|||||||
/** Requests the App sent Accounts (`crosscode.identity-request/1`). */
|
/** Requests the App sent Accounts (`crosscode.identity-request/1`). */
|
||||||
requests: Record<string, unknown>[];
|
requests: Record<string, unknown>[];
|
||||||
/** What `messaging.get` answers: the church's settings in the clear (sealed on the way), or an error. */
|
/** What `messaging.get` answers: the church's settings in the clear (sealed on the way), or an error. */
|
||||||
|
/** Accounts' accounts by email, for people.ensure. */
|
||||||
|
accountsByEmail: Map<string, string>;
|
||||||
messaging: { email: (Omit<Smtp, 'pass'> & { pass: string | null }) | null; whatsapp: Wawp | null } | Error;
|
messaging: { email: (Omit<Smtp, 'pass'> & { pass: string | null }) | null; whatsapp: Wawp | null } | Error;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -107,6 +110,14 @@ function fakeAuthClient(fake: FakeAccounts): AuthClientModule {
|
|||||||
updatedAt: '2026-11-30T10:00:00.000Z',
|
updatedAt: '2026-11-30T10:00:00.000Z',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
if (input.type === 'people.ensure') {
|
||||||
|
// The same account for the same email, as Accounts does; new ones get a fresh id.
|
||||||
|
const email = String(input.email);
|
||||||
|
const known = fake.accountsByEmail.get(email);
|
||||||
|
const sub = known ?? crypto.randomUUID();
|
||||||
|
fake.accountsByEmail.set(email, sub);
|
||||||
|
return { schema: IDENTITY_REQUEST_SCHEMA, sub, created: !known, emailSent: !known };
|
||||||
|
}
|
||||||
return { schema: IDENTITY_REQUEST_SCHEMA, ok: true };
|
return { schema: IDENTITY_REQUEST_SCHEMA, ok: true };
|
||||||
},
|
},
|
||||||
verifyAccountsCall: (raw: Buffer, headers: Record<string, unknown>) => {
|
verifyAccountsCall: (raw: Buffer, headers: Record<string, unknown>) => {
|
||||||
@@ -126,7 +137,7 @@ export function testClock(start = '2026-12-01T06:00:00Z') {
|
|||||||
export async function harness(opts: { linked?: boolean; env?: Record<string, string> } = {}) {
|
export async function harness(opts: { linked?: boolean; env?: Record<string, string> } = {}) {
|
||||||
const db = memoryDb();
|
const db = memoryDb();
|
||||||
const clock = testClock();
|
const clock = testClock();
|
||||||
const fake: FakeAccounts = { next: { sub: PASTOR }, started: [], requests: [], messaging: { email: CHURCH_SMTP, whatsapp: CHURCH_WAWP } };
|
const fake: FakeAccounts = { next: { sub: PASTOR }, started: [], requests: [], accountsByEmail: new Map(), messaging: { email: CHURCH_SMTP, whatsapp: CHURCH_WAWP } };
|
||||||
const transport = new MemoryTransport();
|
const transport = new MemoryTransport();
|
||||||
const config = loadConfig({ APP_URL: SITE, HUB_ADMIN_EMAIL: ADMIN_EMAIL.toUpperCase(), ...opts.env });
|
const config = loadConfig({ APP_URL: SITE, HUB_ADMIN_EMAIL: ADMIN_EMAIL.toUpperCase(), ...opts.env });
|
||||||
const ctx = createCtx(config, db as unknown as Db, { authClient: async () => fakeAuthClient(fake), now: clock.now, transport });
|
const ctx = createCtx(config, db as unknown as Db, { authClient: async () => fakeAuthClient(fake), now: clock.now, transport });
|
||||||
|
|||||||
Reference in New Issue
Block a user