Files
crosscode-platform/apps/events/backend/src/accounts/calls.ts
T
joshuaandClaude Opus 5.5 c627c61de1 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>
2026-11-19 14:10:30 +02:00

92 lines
4.3 KiB
TypeScript

/**
* Accounts' signed calls to Events (`crosscode.identity/1`, 3.0.0, docs/EVENTS-3.0-PLAN.md §7):
*
* - `user.updated`: keep Events' copy of the profile and news consent current.
* - `user.export`: Events' part of "Download my data", from the same export Events' own privacy
* page gives (utils/privacy.exportUserData), as sections.
* - `user.deleted`: Events' existing rules: anonymise, keeping financial records without the name;
* `deferred` while the person has a registration for an event that hasn't ended.
*
* A call for someone Events doesn't know is answered as done: there's nothing here to change.
*/
import { IDENTITY_SCHEMA, type AccountsCall, type UserDeletedReply, type UserExportReply } from '@crosscode/contracts';
import { updateLocalCopy, endEventsSessions } from './signin';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const privacy = require('../utils/privacy') as {
exportUserData(userId: string): Promise<Record<string, unknown> | null>;
deletionBlockers(userId: string): Promise<{ eventTitle: string; endDate: Date }[]>;
anonymiseUser(userId: string): Promise<unknown>;
};
/* eslint-enable @typescript-eslint/no-require-imports */
const TITLES: Record<string, string> = {
account: 'Your Cross Events details',
registrations: 'Registrations',
payments: 'Payments',
tickets: 'Tickets and check-ins',
waitlist: 'Waiting lists',
certificates: 'Certificates',
feedback: 'Feedback you gave',
consents: 'Message preferences (history)',
accountActivity: 'Sign-ins to Cross Events before the move',
dataRequests: 'Privacy requests',
notices: 'Privacy notices accepted',
kidsFamily: 'Family and children',
volunteering: 'Volunteering',
seriesFollowed: 'Series you follow',
seasonPasses: 'Season passes',
};
const sectionKey = (k: string) => k.replace(/([A-Z])/g, '_$1').toLowerCase().replace(/[^a-z0-9_]/g, '').replace(/^[^a-z]+/, '').slice(0, 50) || 'other';
const asRecords = (v: unknown): Record<string, unknown>[] =>
(Array.isArray(v) ? v : v && typeof v === 'object' ? [v] : []).map((x) => (x && typeof x === 'object' ? (JSON.parse(JSON.stringify(x)) as Record<string, unknown>) : { value: x }));
/** Events' export as `crosscode.identity/1` sections (at most 100). */
export function exportSections(data: Record<string, unknown>) {
return Object.entries(data)
.filter(([, v]) => v !== null && v !== undefined)
.map(([k, v]) => ({ key: sectionKey(k), title: TITLES[k] ?? k, records: asRecords(v) }))
.filter((s) => s.records.length > 0)
.slice(0, 100);
}
const DEFER_HOURS = 24;
export async function handleAccountsCall(call: AccountsCall): Promise<object> {
const user = await prisma.user.findUnique({ where: { accountId: call.sub }, select: { id: true } });
switch (call.type) {
case 'user.updated': {
if (user) await updateLocalCopy(user.id, call.profile);
return { schema: IDENTITY_SCHEMA, ok: true };
}
case 'user.export': {
const data = user ? await privacy.exportUserData(user.id) : null;
const reply: UserExportReply = {
schema: IDENTITY_SCHEMA, exportId: call.exportId, sub: call.sub, product: 'events', generatedAt: new Date().toISOString(),
sections: data ? exportSections(data) : [],
};
return reply;
}
case 'user.deleted': {
if (!user) return { schema: IDENTITY_SCHEMA, status: 'deleted' } satisfies UserDeletedReply;
const blockers = await privacy.deletionBlockers(user.id);
if (blockers.length) {
const first = blockers[0]!;
const end = new Date(Math.max(new Date(first.endDate).getTime(), Date.now()) + DEFER_HOURS * 3600e3);
const more = blockers.length > 1 ? ` and ${blockers.length - 1} more` : '';
return {
schema: IDENTITY_SCHEMA, status: 'deferred',
reason: `Has a registration for ${first.eventTitle} (${new Date(first.endDate).toISOString().slice(0, 10)})${more}`.slice(0, 500),
retryAfter: end.toISOString(),
} satisfies UserDeletedReply;
}
await endEventsSessions(user.id);
await privacy.anonymiseUser(user.id);
await prisma.user.update({ where: { id: user.id }, data: { accountId: null } }).catch(() => {});
return { schema: IDENTITY_SCHEMA, status: 'deleted' } satisfies UserDeletedReply;
}
}
}