Files
crosscode-platform/apps/events/backend/src/v2/resources/signIn.ts
T
joshuaandClaude Opus 5.5 70c471666b Accounts sign-in looks like the church's site; Events sends its logo and colours
- @crosscode/ui: Shell with the church's colour wash, logo (or its initial)
  and name, footer; Card edged in the church's colour; Heading with an
  icon tile. Icons on every sign-in step.
- contracts 1.9.0: churchLookSchema (logo, accent colour) in import.begin;
  church.branding request. Accounts fills (move) or replaces (button) the
  church profile's name, logo and colours.
- Events 3.1.0: src/accounts/look.ts (logo as a full address), sent with a
  move; Settings -> Sign-in "Use this site's logo and colours".
Tests: Accounts 55, contracts 218, Events 774, test:accounts 16.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 21:50:02 +02:00

315 lines
15 KiB
TypeScript

import { z } from 'zod';
import { defineRoute } from '../route';
import { ApiError, notFound } from '../errors';
import { single } from '../paging';
import { authMode } from '../../accounts/mode';
import { check, move, MoveError, status, undo } from '../../accounts/move';
import { accounts, accountsLink, AccountsUnavailable } from '../../accounts/client';
import { accountsMessaging, eventsMessaging, sendToAccounts } from '../../accounts/messaging';
import { churchLook } from '../../accounts/look';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../../config/db');
const { logAdminAction } = require('../../utils/adminAudit') as { logAdminAction(entry: object): Promise<void> };
const { getClientIp } = require('../../utils/requestUtils') as { getClientIp(req: unknown): string | null };
/* eslint-enable @typescript-eslint/no-require-imports */
/**
* Settings → Sign-in (3.0.0, docs/EVENTS-3.0-PLAN.md §5): where people sign in, the move to the
* church's Accounts (check, move, undo), and what an admin can do to someone's account from here
* once sign-in goes through Accounts (§6). And, for every page, where to send someone to sign in.
*/
function asApiError(e: unknown): never {
if (e instanceof MoveError) {
const code = e.status === 503 || e.status === 502 ? 'UNAVAILABLE' : 'CONFLICT';
throw new ApiError(code, e.message);
}
if (e instanceof AccountsUnavailable) throw new ApiError('UNAVAILABLE', e.message);
const err = e as { code?: string; message?: string; status?: number };
if (err?.code && typeof err.status === 'number') {
if (err.code === 'UNKNOWN_PERSON') throw new ApiError('NOT_FOUND', 'Accounts doesn\'t know this person through Cross Events yet. They need to sign in once first.');
if (err.code === 'NOT_ALLOWED') throw new ApiError('FORBIDDEN', err.message ?? 'Accounts didn\'t allow that.');
throw new ApiError('UNAVAILABLE', `Accounts didn't accept that: ${err.message}`);
}
throw e;
}
const person = z.object({ name: z.string(), email: z.string() });
const statusSchema = z.object({
mode: z.enum(['local', 'accounts']).describe('local: Cross Events\' own sign-in; accounts: through the church\'s Accounts'),
accountsConnected: z.boolean(),
accountsUrl: z.string().nullable(),
movedAt: z.string().nullable(),
undoUntil: z.string().nullable().describe('Undo is possible until then (14 days after the move)'),
secretsCleared: z.boolean().describe('The old passwords have been removed (Undo is no longer possible)'),
running: z.boolean(),
report: z.unknown().nullable(),
});
export const signInMode = defineRoute({
method: 'get',
path: '/auth/mode',
tag: 'Accounts',
summary: 'Where people sign in',
description: '`accounts`: send people to `GET /api/auth/signin?returnTo=<this page>` (the church\'s Accounts). `local`: Cross Events\' own sign-in.',
access: 'public',
response: single(z.object({
mode: z.enum(['local', 'accounts']),
signInUrl: z.string(),
accountUrl: z.string().nullable().describe('With `accounts`: the church account page (profile, password, two-step sign-in, privacy)'),
})),
async handler() {
const mode = await authMode();
const link = mode === 'accounts' ? await accountsLink() : null;
return { data: { mode, signInUrl: '/api/auth/signin', accountUrl: link ? `${link.url.replace(/\/+$/, '')}/api/self/signin?returnTo=/account` : null } };
},
});
export const signInStatus = defineRoute({
method: 'get',
path: '/settings/sign-in',
tag: 'Accounts',
summary: 'Sign-in: where it is and the move to Accounts',
access: 'admin',
response: single(statusSchema),
async handler() {
return { data: await status() };
},
});
export const signInCheck = defineRoute({
method: 'post',
path: '/settings/sign-in/check',
tag: 'Accounts',
summary: 'Check the move to Accounts (nothing changes)',
description: 'Who would move, who already has an account (they\'re linked to it), who is skipped (guests, deleted) and anything that would stop the move.',
access: 'admin',
response: single(z.object({
accountsVersion: z.string(),
toMove: z.number().int(),
wouldCreate: z.number().int(),
wouldLink: z.array(person),
refused: z.array(person.extend({ reason: z.string() })),
skipped: z.number().int(),
admins: z.array(person.extend({ id: z.string() })),
noticeConflict: z.object({ accountsVersions: z.array(z.number()), eventsVersions: z.array(z.number()) }).nullable(),
withTwoFactor: z.number().int(),
messaging: z.object({ email: z.boolean(), whatsapp: z.boolean(), whatsappTwoFactor: z.number().int() }).describe('3.1.0: what Accounts can send; the move needs email'),
})),
async handler() {
return { data: await check().catch(asApiError) };
},
});
export const signInMove = defineRoute({
method: 'post',
path: '/settings/sign-in/move',
tag: 'Accounts',
summary: 'Move sign-in to Accounts',
description: 'Copies everyone into the church\'s Accounts with their passwords and authenticator apps, checks the count, then switches. Nothing switches if anything fails, and it can be run again. Undo for 14 days.',
access: 'admin',
body: z.object({
adminIds: z.array(z.uuid()).max(500).describe('Events admins who also become Accounts admins'),
keepAccountsNotices: z.boolean().optional().describe('When Accounts has its own privacy notice: keep it (everyone accepts it at their next sign-in) instead of Events\''),
}),
response: single(statusSchema),
async handler({ body, user, req }) {
const me = await prisma.user.findUnique({ where: { id: user!.id }, select: { name: true } });
await move({ actor: { id: user!.id, role: user!.role, name: me?.name }, adminIds: body.adminIds, keepAccountsNotices: body.keepAccountsNotices, ip: getClientIp(req) }).catch(asApiError);
return { data: await status() };
},
});
export const signInUndo = defineRoute({
method: 'post',
path: '/settings/sign-in/undo',
tag: 'Accounts',
summary: 'Undo the move (back to Cross Events\' own sign-in)',
description: 'Within 14 days of the move. People sign in with the password they had at the move; changes made in Accounts since then don\'t come back here.',
access: 'admin',
response: single(statusSchema),
async handler({ user, req }) {
return { data: await undo({ id: user!.id, role: user!.role }, getClientIp(req)).catch(asApiError) };
},
});
// ─── Email and WhatsApp for Accounts (3.1.0) ────────────────────────────────
const messagingOverview = z.object({
events: z.object({
email: z.object({ host: z.string(), port: z.number().int(), secure: z.boolean(), user: z.string(), from: z.string(), hasPass: z.boolean() }).nullable(),
whatsapp: z.object({ instanceId: z.string(), hasToken: z.boolean() }).nullable(),
}).describe("This site's own settings, to copy (never the password or token)"),
accounts: z.object({
email: z.object({ ready: z.boolean(), host: z.string().nullable(), from: z.string().nullable() }),
whatsapp: z.object({ ready: z.boolean(), instanceId: z.string().nullable() }),
}).nullable().describe("What the church's Accounts can send (null: it can't be reached)"),
accountsError: z.string().nullable(),
});
export const signInMessaging = defineRoute({
method: 'get',
path: '/settings/sign-in/messaging',
tag: 'Accounts',
summary: "Email and WhatsApp: this site's, and what Accounts can send",
access: 'admin',
response: single(messagingOverview),
async handler() {
const events = await eventsMessaging();
try {
return { data: { events, accounts: await accountsMessaging(), accountsError: null } };
} catch (e) {
return { data: { events, accounts: null, accountsError: (e as Error).message } };
}
},
});
/** 082 123 4567 → +27821234567 (as Accounts keeps phone numbers). */
const toE164 = (raw: string) => {
const d = raw.replace(/\D/g, '');
if (raw.trim().startsWith('+')) return `+${d}`;
return d.startsWith('0') && d.length === 10 ? `+27${d.slice(1)}` : `+${d}`;
};
const messagingBody = z.object({
email: z.object({
host: z.string().trim().min(1).max(253),
port: z.number().int().min(1).max(65535),
secure: z.boolean(),
user: z.string().max(254),
from: z.string().trim().min(3).max(320),
pass: z.string().max(500).nullable().optional().describe("Blank: this site's own password"),
to: z.email().describe('Where the test email goes'),
}).optional(),
whatsapp: z.object({
instanceId: z.string().trim().min(1).max(200),
accessToken: z.string().max(500).nullable().optional().describe("Blank: this site's own token"),
to: z.string().trim().min(8).max(30).describe('The phone the test message goes to'),
}).optional(),
});
const messagingResult = z.object({ ok: z.boolean(), error: z.string().nullable(), saved: z.boolean() }).nullable();
const messagingAnswer = single(z.object({ email: messagingResult, whatsapp: messagingResult, status: z.object({ email: z.object({ ready: z.boolean(), host: z.string().nullable(), from: z.string().nullable() }), whatsapp: z.object({ ready: z.boolean(), instanceId: z.string().nullable() }) }) }));
async function messagingFor(body: z.infer<typeof messagingBody>, user: { id: string; role: string }, req: unknown, save: boolean) {
if (!body.email && !body.whatsapp) throw new ApiError('VALIDATION_FAILED', 'Give email or WhatsApp settings.');
const actor = (await prisma.user.findUnique({ where: { id: user.id }, select: { accountId: true } }))?.accountId ?? null;
const input = { ...(body.email ? { email: body.email } : {}), ...(body.whatsapp ? { whatsapp: { ...body.whatsapp, to: toE164(body.whatsapp.to) } } : {}) };
const out = await sendToAccounts(input, { save, actor }).catch(asApiError);
if (save) {
await logAdminAction({ actorId: user.id, actorRole: user.role, action: 'account_changed_in_accounts', targetType: 'setting', targetId: 'accounts_messaging', metadata: { email: out.email && { ok: out.email.ok, saved: out.email.saved, host: body.email?.host }, whatsapp: out.whatsapp && { ok: out.whatsapp.ok, saved: out.whatsapp.saved } }, ip: getClientIp(req) });
}
return { data: out };
}
export const signInMessagingTest = defineRoute({
method: 'post',
path: '/settings/sign-in/messaging/test',
tag: 'Accounts',
summary: 'Test email / WhatsApp settings through Accounts (nothing saved)',
description: "Accounts sends a test email to `email.to` and a WhatsApp message to `whatsapp.to` with the settings given. A blank password or token uses this site's own.",
access: 'admin',
body: messagingBody,
response: messagingAnswer,
async handler({ body, user, req }) {
return messagingFor(body, user!, req, false);
},
});
export const signInMessagingSave = defineRoute({
method: 'post',
path: '/settings/sign-in/messaging',
tag: 'Accounts',
summary: 'Save email / WhatsApp settings in Accounts (after a test)',
description: 'Accounts tests each part as /test does, and saves it only if its test worked.',
access: 'admin',
body: messagingBody,
response: messagingAnswer,
async handler({ body, user, req }) {
return messagingFor(body, user!, req, true);
},
});
export const signInLook = defineRoute({
method: 'post',
path: '/settings/sign-in/look',
tag: 'Accounts',
summary: "Use this site's logo and colours on the church's sign-in pages",
description: "Sends this site's name, logo and colours to the church's Accounts, replacing what its sign-in pages had.",
access: 'admin',
response: single(z.object({ name: z.string().nullable(), logoUrl: z.string().nullable(), primaryColour: z.string().nullable(), accentColour: z.string().nullable() })),
async handler({ user, req }) {
const look = await churchLook();
const actor = (await prisma.user.findUnique({ where: { id: user!.id }, select: { accountId: true } }))?.accountId ?? null;
await (await accounts().catch(asApiError)).request({ type: 'church.branding', actor, church: look, overwrite: true }).catch(asApiError);
await logAdminAction({ actorId: user!.id, actorRole: user!.role, action: 'account_changed_in_accounts', targetType: 'setting', targetId: 'accounts_look', metadata: look, ip: getClientIp(req) });
return { data: { name: look.name, logoUrl: look.logoUrl ?? null, primaryColour: look.primaryColour, accentColour: look.accentColour ?? null } };
},
});
// ─── An admin, for someone's account (sign-in through Accounts) ─────────────
const idParams = z.object({ id: z.uuid() });
async function targetFor(id: string) {
const u = await prisma.user.findUnique({ where: { id }, select: { id: true, accountId: true, name: true } });
if (!u) throw notFound('That person');
if (!u.accountId) throw new ApiError('CONFLICT', `${u.name} doesn't sign in through the church's account yet.`);
return u as { id: string; accountId: string; name: string };
}
async function forAccount(id: string, admin: { id: string; role: string }, req: unknown, what: 'people.resetTwoFactor' | 'people.unlock' | 'people.setActive', extra: object = {}) {
if ((await authMode()) !== 'accounts') throw new ApiError('CONFLICT', 'Sign-in is still in Cross Events: use the account\'s own settings here.');
const target = await targetFor(id);
const actor = (await prisma.user.findUnique({ where: { id: admin.id }, select: { accountId: true } }))?.accountId ?? null;
await (await accounts().catch(asApiError)).request({ type: what, actor, sub: target.accountId, ...extra } as never).catch(asApiError);
await logAdminAction({ actorId: admin.id, actorRole: admin.role, action: 'account_changed_in_accounts', targetType: 'user', targetId: target.id, metadata: { request: what, ...extra }, ip: getClientIp(req) });
return { data: { ok: true as const } };
}
const ok = single(z.object({ ok: z.literal(true) }));
export const accountResetTwoFactor = defineRoute({
method: 'post',
path: '/users/:id/account/reset-two-factor',
tag: 'Accounts',
summary: 'Reset someone\'s two-step sign-in (in Accounts)',
description: 'They set it up again at their next sign-in, and are signed out everywhere.',
access: 'admin',
params: idParams,
response: ok,
async handler({ params, user, req }) {
return forAccount(params.id, user!, req, 'people.resetTwoFactor');
},
});
export const accountUnlock = defineRoute({
method: 'post',
path: '/users/:id/account/unlock',
tag: 'Accounts',
summary: 'Unlock someone after too many wrong passwords (in Accounts)',
access: 'admin',
params: idParams,
response: ok,
async handler({ params, user, req }) {
return forAccount(params.id, user!, req, 'people.unlock');
},
});
export const accountSetActive = defineRoute({
method: 'post',
path: '/users/:id/account/active',
tag: 'Accounts',
summary: 'Turn someone\'s church account off or on everywhere (in Accounts)',
description: 'Off signs them out of every product of the church. To only stop them using Cross Events, deactivate them here instead.',
access: 'admin',
params: idParams,
body: z.object({ active: z.boolean() }),
response: ok,
async handler({ params, body, user, req }) {
return forAccount(params.id, user!, req, 'people.setActive', { active: body.active });
},
});