Accounts 1.0.0 backend: OIDC provider, sign-in steps, account and admin API

oidc-provider 9.13.3 with PKCE, ES256, crosscode.identity/1 claims and
back-channel logout; clients are the linked products (Connect). Sign-in
steps (password, sign-up, email check, 2FA and its setup, privacy notice,
news question, password reset) survive to the product. Account page and
admin API, church profile, export and deletion fan-out, Hub v2 client,
jobs. End-to-end tests with a test product on openid-client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 13:33:49 +02:00
co-authored by Claude Opus 5.5
parent 45c6539bf1
commit 069b66fd30
51 changed files with 4863 additions and 9 deletions
+260
View File
@@ -0,0 +1,260 @@
/**
* 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
* licence and the audit log. Admins only, signed in with 2FA; viewing a person is access-logged.
*/
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 { 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 { 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';
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' } });
return { current: await currentNotice(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 } });
await ctx.messenger.email({ to: a.email, subject: 'Test email from Accounts', text: 'Email from Accounts works.' });
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);
}));
// ─── 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;
}