Files
crosscode-platform/apps/accounts/backend/src/setup/routes.ts
T
joshuaandClaude Opus 5.5 069b66fd30 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>
2026-11-18 13:33:49 +02:00

71 lines
3.5 KiB
TypeScript

/**
* First run (`/setup`): the church's name, the first admin and (unless the Hub installed it with
* HUB_LICENCE_KEY) the licence key. Only while there's no admin. On a Hub install the first admin
* must use the email address the Hub was given (HUB_ADMIN_EMAIL), so nobody else can take it.
*/
import express from 'express';
import type { Ctx } from '../context.js';
import { ApiError, handle, limit } from '../http.js';
import { audit, clientIp, loginEvent } from '../lib/audit.js';
import { hashPassword, passwordProblem } from '../lib/passwords.js';
import { emailProblem, normaliseEmail } from '../accounts/service.js';
import { updateProfile } from '../church/profile.js';
import { connect as connectHub } from '../hub/client.js';
import { currentNotice } from '../privacy/notice.js';
export async function setupNeeded(ctx: Ctx): Promise<boolean> {
return (await ctx.db.account.count({ where: { role: 'admin', status: 'active' } })) === 0;
}
export function setupRouter(ctx: Ctx) {
const r = express.Router();
r.get('/setup', handle(async () => ({
needed: await setupNeeded(ctx),
hubConnected: !!(await ctx.settings.get('hub_install_id')),
adminEmail: ctx.config.hubAdminEmail,
})));
r.post('/setup', limit(10, 60), handle(async (req) => {
if (!(await setupNeeded(ctx))) throw new ApiError(409, 'DONE', 'Accounts is already set up. Sign in instead.');
const b = req.body ?? {};
const fields: Record<string, string> = {};
const churchName = String(b.churchName ?? '').trim();
const name = String(b.name ?? '').trim();
const email = normaliseEmail(b.email);
if (churchName.length < 2) fields.churchName = 'Enter the church\'s name.';
if (name.length < 2) fields.name = 'Enter your name.';
const ep = emailProblem(email);
if (ep) fields.email = ep;
else if (ctx.config.hubAdminEmail && email !== normaliseEmail(ctx.config.hubAdminEmail)) fields.email = 'Use the email address your provider set up this site for.';
const pp = passwordProblem(b.password);
if (pp) fields.password = pp;
const hubConnected = !!(await ctx.settings.get('hub_install_id'));
if (!hubConnected && !String(b.licenceKey ?? '').trim()) fields.licenceKey = 'Enter the licence key from your provider (CCA-…).';
if (Object.keys(fields).length) throw new ApiError(400, 'VALIDATION', 'Some details need fixing.', fields);
if (!hubConnected) {
try {
await connectHub(ctx, String(b.licenceKey), { name, email });
} catch (e) {
const msg = (e as Error).message;
throw new ApiError(400, 'LICENCE', msg, { licenceKey: msg });
}
}
await updateProfile(ctx, { name: churchName });
const parts = name.split(/\s+/);
const notice = await currentNotice(ctx);
const a = await ctx.db.account.upsert({
where: { email },
create: { name, givenName: parts[0] ?? null, familyName: parts.slice(1).join(' ') || null, email, role: 'admin', passwordHash: await hashPassword(String(b.password)), noticeVersionAccepted: notice.version, newsAskedAt: ctx.now() },
update: { role: 'admin', status: 'active', passwordHash: await hashPassword(String(b.password)) },
});
await loginEvent(ctx, a.id, 'account_created', req);
await audit(ctx, { actorId: a.id, actorRole: 'admin', action: 'setup_completed', targetType: 'account', targetId: a.id, ip: clientIp(req) });
// Signing in sets up 2FA (admins must have it) and verifies the email address.
return { done: true, next: '/api/self/signin?returnTo=/admin' };
}));
return r;
}