Files
crosscode-platform/apps/accounts/backend/src/admin/routes.ts
T
joshuaandClaude Opus 5.5 bbcafe61b9 Events 3.4.0, Accounts 1.4.0, contracts 1.12.0, agent 1.3.0: jobs from the dashboard, styled Accounts emails, .env from the Hub
- Events and Accounts: Background jobs are switched on or off and rescheduled from the admin;
  the choice is kept in the database (job_overrides), wins over the .env and applies at once.
  Accounts gets an Admin -> Background jobs page and per-job env flags, as Events.
- Accounts: every email styled as Cross Events' (church colour, logo, button, footer), same
  plain text (src/lib/emails.ts).
- Contracts 1.12.0: env-read / env-set agent jobs, envReadResultSchema, isSecretEnvName.
- crosscode script: `crosscode env <church> <product>` reads the .env (secrets hidden) and, with
  --set/--unset/--restart, changes one file, rebuilds the frontend when its file changed, reloads,
  and puts the file back if the site doesn't answer (lib/envedit.cjs, tests/envedit.bats).
- Agent 1.3.0: runs env-read and env-set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:14:02 +02:00

364 lines
19 KiB
TypeScript

/**
* 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, 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, 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';
import { signOutEverywhere } from '../oidc/sessions.js';
import { recoveryCodesLeft, turnOff } from '../accounts/twoFactor.js';
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 { 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';
import { JobError, jobStatus, runNow, setOverride } from '../jobs.js';
import { testEmail } from '../lib/emails.js';
const PAGE = 50;
export function adminRouter(ctx: Ctx, provider: Provider) {
const r = express.Router();
const admin = async (req: Request, res: Response) => {
const s = await currentSession(ctx, provider, req, res);
if (!s) throw new ApiError(401, 'UNAUTHENTICATED', 'Please sign in.');
if (s.account.role !== 'admin') throw new ApiError(403, 'FORBIDDEN', 'Only Accounts admins can do that.');
if ((await ctx.settings.bool('two_factor_required_for_admins', true)) && !s.amr.includes('mfa')) throw new ApiError(403, 'MFA_REQUIRED', 'Sign in again with your second step to use admin.');
return { id: s.account.id, role: 'admin' };
};
// ─── People ────────────────────────────────────────────────────────────────
r.get('/people', handle(async (req, res) => {
await admin(req, res);
const q = String(req.query.q ?? '').trim();
const page = Math.max(1, Number(req.query.page) || 1);
const where = {
status: { not: 'deleted' as const },
...(q ? { OR: [{ name: { contains: q, mode: 'insensitive' as const } }, { email: { contains: q.toLowerCase() } }] } : {}),
};
const [items, total] = await Promise.all([
ctx.db.account.findMany({ where, orderBy: { name: 'asc' }, skip: (page - 1) * PAGE, take: PAGE }),
ctx.db.account.count({ where }),
]);
return {
items: items.map((a) => ({ id: a.id, name: a.name, email: a.email, role: a.role, status: a.status, twoFactor: a.twoFactorMethod, lastSignInAt: a.lastSignInAt })),
total, page, pages: Math.max(1, Math.ceil(total / PAGE)),
};
}));
r.get('/people/:id', handle(async (req, res) => {
const me = await admin(req, res);
const a = await ctx.db.account.findUnique({ where: { id: String(req.params.id) } });
if (!a || a.status === 'deleted') throw new ApiError(404, 'NOT_FOUND', 'That person wasn\'t found.');
await accessLog(ctx, me.id, a.id, 'view', req);
const [signIns, deletion, consents] = await Promise.all([
ctx.db.loginEvent.findMany({ where: { accountId: a.id }, orderBy: { createdAt: 'desc' }, take: 20 }),
ctx.db.deletionRequest.findFirst({ where: { accountId: a.id }, orderBy: { requestedAt: 'desc' } }),
ctx.db.consentChange.findMany({ where: { accountId: a.id }, orderBy: { createdAt: 'desc' }, take: 20 }),
]);
return {
id: a.id, name: a.name, email: a.email, emailVerified: a.emailVerified, phone: a.phone, role: a.role, status: a.status,
twoFactor: a.twoFactorMethod, recoveryCodesLeft: await recoveryCodesLeft(ctx, a.id), news: { email: a.newsEmail, whatsapp: a.newsWhatsApp },
noticeVersionAccepted: a.noticeVersionAccepted, createdAt: a.createdAt, lastSignInAt: a.lastSignInAt, lockedUntil: a.lockedUntil,
signIns: signIns.map((e) => ({ type: e.type, at: e.createdAt, ip: e.ip })),
consents: consents.map((c) => ({ channel: c.channel, granted: c.granted, source: c.source, at: c.createdAt })),
deletion: deletion ? { id: deletion.id, status: deletion.status, requestedAt: deletion.requestedAt, products: deletion.products } : null,
};
}));
r.post('/people/:id/reset-two-factor', handle(async (req, res) => {
const me = await admin(req, res);
const id = String(req.params.id);
if (id === me.id) throw new ApiError(400, 'SELF', 'Change your own two-factor sign-in on your account page.');
await turnOff(ctx, id);
await signOutEverywhere(ctx, provider, id);
await loginEvent(ctx, id, 'two_factor_off', req, { detail: { by: 'admin' } });
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'two_factor_reset', targetType: 'account', targetId: id, ip: clientIp(req) });
return { reset: true };
}));
r.post('/people/:id/unlock', handle(async (req, res) => {
const me = await admin(req, res);
await ctx.db.account.update({ where: { id: String(req.params.id) }, data: { lockedUntil: null, failedSignIns: 0 } });
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'account_unlocked', targetType: 'account', targetId: String(req.params.id), ip: clientIp(req) });
return { unlocked: true };
}));
r.put('/people/:id/role', handle(async (req, res) => {
const me = await admin(req, res);
const role = req.body?.role === 'admin' ? 'admin' : 'member';
const id = String(req.params.id);
if (id === me.id && role !== 'admin') throw new ApiError(400, 'SELF', 'Ask another admin to change your role.');
await ctx.db.account.update({ where: { id }, data: { role } });
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'role_changed', targetType: 'account', targetId: id, metadata: { role }, ip: clientIp(req) });
return { role };
}));
r.put('/people/:id/status', handle(async (req, res) => {
const me = await admin(req, res);
const id = String(req.params.id);
if (id === me.id) throw new ApiError(400, 'SELF', 'You can\'t deactivate your own account here.');
const active = req.body?.active === true;
await ctx.db.account.update({ where: { id }, data: active ? { status: 'active', deactivatedAt: null } : { status: 'deactivated', deactivatedAt: ctx.now() } });
if (!active) await signOutEverywhere(ctx, provider, id);
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: active ? 'account_reactivated' : 'account_deactivated', targetType: 'account', targetId: id, ip: clientIp(req) });
return { active };
}));
// ─── Deletion requests ─────────────────────────────────────────────────────
r.get('/deletions', handle(async (req, res) => {
await admin(req, res);
const list = await ctx.db.deletionRequest.findMany({ where: { status: { in: ['waiting_approval', 'approved'] } }, orderBy: { requestedAt: 'asc' } });
const people = await ctx.db.account.findMany({ where: { id: { in: list.map((d) => d.accountId) } } });
const byId = new Map(people.map((p) => [p.id, p]));
return { items: list.map((d) => ({ id: d.id, status: d.status, requestedAt: d.requestedAt, approvedAt: d.approvedAt, products: d.products, person: { id: d.accountId, name: byId.get(d.accountId)?.name ?? '', email: byId.get(d.accountId)?.email ?? '' } })) };
}));
r.post('/deletions/:id/approve', handle(async (req, res) => {
const me = await admin(req, res);
if (!(await approveDeletion(ctx, String(req.params.id), me, req))) throw new ApiError(409, 'NOT_WAITING', 'That request isn\'t waiting for approval.');
return { approved: true };
}));
r.post('/deletions/:id/cancel', handle(async (req, res) => {
const me = await admin(req, res);
if (!(await cancelDeletion(ctx, String(req.params.id), me, req))) throw new ApiError(409, 'NOT_WAITING', 'That request isn\'t waiting for approval.');
return { cancelled: true };
}));
// ─── Privacy notice ────────────────────────────────────────────────────────
r.get('/notices', handle(async (req, res) => {
await admin(req, res);
const list = await ctx.db.privacyNotice.findMany({ orderBy: { version: 'desc' } });
// 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) => {
const me = await admin(req, res);
const title = String(req.body?.title ?? '').trim();
const body = String(req.body?.body ?? '').trim();
if (!title || body.length < 50) throw new ApiError(400, 'VALIDATION', 'Give the notice a title and its full text.');
const n = await publish(ctx, { title, body }, me.id);
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'notice_published', targetType: 'notice', targetId: String(n.version), ip: clientIp(req) });
return n;
}));
// ─── Church profile ────────────────────────────────────────────────────────
r.get('/church', handle(async (req, res) => {
await admin(req, res);
return church(ctx);
}));
r.put('/church', handle(async (req, res) => {
const me = await admin(req, res);
const c = await updateProfile(ctx, req.body ?? {});
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'church_profile_changed', targetType: 'setting', targetId: 'church_profile', ip: clientIp(req) });
return c;
}));
// ─── Settings (sign-in, email, WhatsApp) ────────────────────────────────────
r.get('/settings', handle(async (req, res) => {
await admin(req, res);
const out: Record<string, string | boolean | null> = {};
for (const key of ADMIN_SETTINGS) {
const v = await ctx.settings.get(key);
out[key] = SECRET_SETTINGS.has(key) ? !!v : v;
}
return out;
}));
r.put('/settings', handle(async (req, res) => {
const me = await admin(req, res);
const changed: string[] = [];
for (const [key, value] of Object.entries(req.body ?? {})) {
if (!ADMIN_SETTINGS.has(key)) continue;
// A secret left empty keeps what's there.
if (SECRET_SETTINGS.has(key) && (value === '' || value === true)) continue;
await ctx.settings.set(key, value === null || value === undefined ? null : String(value));
changed.push(key);
}
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'settings_changed', targetType: 'setting', metadata: { keys: changed }, ip: clientIp(req) });
return { changed };
}));
r.post('/settings/test-email', limit(5), handle(async (req, res) => {
const me = await admin(req, res);
const a = await ctx.db.account.findUniqueOrThrow({ where: { id: me.id } });
try {
await ctx.messenger.email({ to: a.email, ...(await testEmail(ctx)) });
} catch (e) {
throw new ApiError(502, 'NOT_SENT', `The test email couldn't be sent: ${(e as Error).message}`);
}
return { sent: true };
}));
// 1.2.0: as the test email, for WhatsApp (WAWP), to the admin's own phone.
r.post('/settings/test-whatsapp', limit(5), handle(async (req, res) => {
const me = await admin(req, res);
const a = await ctx.db.account.findUniqueOrThrow({ where: { id: me.id } });
if (!a.phone) throw new ApiError(400, 'NO_PHONE', 'Add your mobile number on your account page first.');
try {
await ctx.messenger.whatsapp({ to: a.phone, text: 'WhatsApp from Accounts works.' });
} catch (e) {
throw new ApiError(502, 'NOT_SENT', `The test message couldn't be sent: ${(e as Error).message}`);
}
return { sent: true };
}));
// ─── Linked products ───────────────────────────────────────────────────────
r.get('/linked-products', handle(async (req, res) => {
await admin(req, res);
const [listed, links] = await Promise.all([linkedProducts(ctx), ctx.db.productLink.findMany()]);
const ids = [...new Set([...listed.map((l) => l.installId), ...links.map((l) => l.installId)])];
return {
hubConnected: !!(await ctx.settings.get('hub_install_id')),
items: ids.map((id) => {
const hubRow = listed.find((l) => l.installId === id);
const link = links.find((l) => l.installId === id);
const product = hubRow?.product ?? link!.product;
return { installId: id, product, name: productName(product), url: hubRow?.url ?? link!.url, listed: !!hubRow, connectedAt: link?.connectedAt ?? null, signsInHere: !!link };
}),
};
}));
r.post('/linked-products/:installId/connect', handle(async (req, res) => {
const me = await admin(req, res);
await connectTo(ctx, String(req.params.installId), me, req);
return { connected: true };
}));
r.post('/linked-products/:installId/disconnect', handle(async (req, res) => {
const me = await admin(req, res);
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);
}
});
// ─── Background jobs (1.4.0, as Cross Events) ───────────────────────────────
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('/jobs', handle(async (req, res) => {
await admin(req, res);
return jobStatus(ctx);
}));
// Switch a job on or off, or change its schedule: wins over the .env; null goes back to it.
r.put('/jobs/:name', handle(async (req, res) => {
const me = await admin(req, res);
const name = String(req.params.name);
const change = { enabled: req.body?.enabled, cron: req.body?.cron };
const override = await setOverride(ctx, name, change).catch(jobError);
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'job_settings_changed', targetType: 'job', targetId: name, metadata: change, ip: clientIp(req) });
return { name, override };
}));
r.post('/jobs/:name/run', limit(20, 60), handle(async (req, res) => {
const me = await admin(req, res);
const name = String(req.params.name);
const out = await runNow(ctx, name).catch(jobError);
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'job_run_manual', targetType: 'job', targetId: name, metadata: { queued: out.queued }, ip: clientIp(req) });
return out;
}));
// ─── Licence, audit ────────────────────────────────────────────────────────
r.get('/licence', handle(async (req, res) => {
await admin(req, res);
const s = await licenceStatus(ctx);
return { connected: s.connected, state: s.state, customer: s.claims?.customer ?? null, endsAt: s.endsAt, daysLeft: s.daysLeft, lastHeartbeatAt: await ctx.settings.get('hub_last_heartbeat_at'), lastError: await ctx.settings.get('hub_last_error') };
}));
r.post('/licence', limit(5), handle(async (req, res) => {
const me = await admin(req, res);
const a = await ctx.db.account.findUniqueOrThrow({ where: { id: me.id } });
await connectHub(ctx, String(req.body?.licenceKey ?? ''), { name: a.name, email: a.email });
await audit(ctx, { actorId: me.id, actorRole: 'admin', action: 'hub_connected', targetType: 'setting', ip: clientIp(req) });
return { connected: true };
}));
r.get('/audit', handle(async (req, res) => {
await admin(req, res);
const items = await ctx.db.auditLog.findMany({ orderBy: { createdAt: 'desc' }, take: 200 });
return { items };
}));
r.get('/deliveries', handle(async (req, res) => {
await admin(req, res);
const items = await ctx.db.delivery.findMany({ where: { status: { not: 'delivered' } }, orderBy: { createdAt: 'desc' }, take: 100 });
return { items: items.map((d) => ({ id: d.id, type: d.type, linkId: d.linkId, status: d.status, attempts: d.attempts, lastError: d.lastError, nextAttemptAt: d.nextAttemptAt })) };
}));
return r;
}