Cross Events 3.0.0: sign-in through the church's Accounts

Settings -> Sign-in: check, move (everyone into Accounts with their password
hashes and authenticator apps, count/hash check, then switch) and undo for
14 days. Sign-in through auth-client with a one-time handoff to Events' own
token; staff roles stepped up to mfa; sign-out and back-channel logout;
user.updated/export/deleted; admin 2FA reset, unlock and profile changes via
Accounts; /login, /register, /forgot-password forward once moved; Events'
own sign-in endpoints answer SIGN_IN_MOVED. User.accountId, AccountsSignIn.

npm run test:accounts runs Events' code against the real Accounts app (11
tests); 5 new Jest tests. MIGRATING-TO-3.md, plan "Changes while building".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 14:10:30 +02:00
co-authored by Claude Opus 5.5
parent 56cbef1d9b
commit c627c61de1
49 changed files with 4094 additions and 245 deletions
+1
View File
@@ -25,6 +25,7 @@ import './resources/auth';
import './resources/ai';
import './resources/feedback';
import './resources/linkedProducts';
import './resources/signIn';
const pkg = require('../../package.json') as { version: string };
@@ -0,0 +1,197 @@
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';
/* 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(),
})),
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) };
},
});
// ─── 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 });
},
});