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
+91
View File
@@ -0,0 +1,91 @@
/**
* 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;
}
}
}
@@ -0,0 +1,74 @@
/**
* The church's Accounts, as this site's OIDC client (3.0.0, docs/EVENTS-3.0-PLAN.md §1): built on
* `@crosscode/auth-client` from the Accounts link that Connect made (Settings → Linked products).
* Its address is the one the Hub listed; its client id is this site's Hub install id and its client
* secret comes from the link's secret, so there's no `.env` setting for any of it.
*
* `@crosscode/auth-client` and `openid-client` are ES modules and this backend is CommonJS, which
* compiles `import()` into `require()`. The loader below keeps a real dynamic import, so it works on
* every Node the servers run (20+), not only where `require()` of ES modules is allowed.
*/
import type { AccountsClient } from '@crosscode/auth-client';
import { hubInstallId, siteUrl } from '../feed/context';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const { decrypt } = require('../utils/encryption') as { decrypt(v: string): string };
/* eslint-enable @typescript-eslint/no-require-imports */
export type AuthClientModule = typeof import('@crosscode/auth-client');
// eslint-disable-next-line @typescript-eslint/no-implied-eval -- a real import(), see above
const importEsm = new Function('specifier', 'return import(specifier)') as (s: string) => Promise<AuthClientModule>;
let loader: () => Promise<AuthClientModule> = () => importEsm('@crosscode/auth-client');
/** Tests: use another auth-client (a fake, or the real one loaded another way). */
export function setAuthClientLoader(next: () => Promise<AuthClientModule>): void {
loader = next;
cached = null;
}
export class AccountsUnavailable extends Error {
status = 503;
code = 'ACCOUNTS_UNAVAILABLE';
}
export type AccountsLink = { installId: string; url: string; secret: string; updatedAt: Date };
/** The Accounts link, or null when Accounts isn't connected. */
export async function accountsLink(): Promise<AccountsLink | null> {
return prisma.productLink.findFirst({ where: { product: 'accounts' }, orderBy: { connectedAt: 'desc' } });
}
let cached: { key: string; client: Promise<AccountsClient> } | null = null;
/** The client for the church's Accounts (discovery done once per link). Throws AccountsUnavailable. */
export async function accounts(): Promise<AccountsClient> {
const link = await accountsLink();
if (!link) throw new AccountsUnavailable('Accounts isn\'t connected. Connect it under Settings → Linked products.');
const [clientId, productUrl] = await Promise.all([hubInstallId(), siteUrl()]);
if (!clientId) throw new AccountsUnavailable('This site isn\'t connected to the Hub yet.');
const key = `${link.installId}|${new Date(link.updatedAt).getTime()}|${clientId}|${productUrl}`;
if (!cached || cached.key !== key) {
const client = loader().then((m) => m.accountsClient({
accountsUrl: link.url,
productUrl,
clientId,
linkSecret: decrypt(link.secret),
allowInsecure: process.env.NODE_ENV !== 'production' && link.url.startsWith('http:'),
}));
// A failed discovery (Accounts down for a moment) is tried again next time.
client.catch(() => { if (cached?.key === key) cached = null; });
cached = { key, client };
}
try {
return await cached.client;
} catch (e) {
throw new AccountsUnavailable(`Accounts can't be reached right now (${(e as Error).message}). Please try again in a minute.`);
}
}
/** The module itself (for its error classes). */
export function authClientModule(): Promise<AuthClientModule> {
return loader();
}
+106
View File
@@ -0,0 +1,106 @@
/**
* Cross Events' own sign-in, once sign-in goes through Accounts (3.0.0, docs/EVENTS-3.0-PLAN.md §6).
* Mounted after express.json, before the API:
*
* - Signing in, signing up, passwords, activation and 2FA here answer 409 `SIGN_IN_MOVED` with
* where to go instead (the frontend forwards there).
* - While a move runs, Events' own sign-in waits (503 `SIGN_IN_MOVING`).
* - Changing my name, email or phone is done in Accounts (`PATCH /me` keeps the rest).
* - An admin changing someone's name, email or phone (`PATCH /users/:id`) changes their account in
* Accounts first (`people.update`), then Events' copy; a password or 2FA change is refused.
*/
import type { NextFunction, Request, Response } from 'express';
import { accounts, AccountsUnavailable } from './client';
import { getSetting, viaAccounts } from './mode';
import { RUNNING_KEY } from './move';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
/* eslint-enable @typescript-eslint/no-require-imports */
const MOVED = [
'POST /api/v2/auth/login', 'POST /api/v2/auth/login/code', 'POST /api/v2/auth/login/code/resend', 'POST /api/v2/auth/signup',
'POST /api/v2/auth/password/forgot', 'POST /api/v2/auth/password/reset', 'POST /api/v2/auth/activate',
'POST /api/v2/me/verify-password', 'POST /api/v2/me/close',
];
const MOVED_PREFIXES = ['POST /api/v2/me/two-factor/'];
const LOCAL_SIGN_IN = ['POST /api/v2/auth/login', 'POST /api/v2/auth/login/code', 'POST /api/v2/auth/signup', 'POST /api/v2/auth/activate'];
const movedAnswer = (res: Response) => res.status(409).json({
error: {
code: 'SIGN_IN_MOVED',
message: 'Signing in, passwords and two-step sign-in are now on your church account. Use "Sign in" to continue.',
signInUrl: '/api/auth/signin',
},
});
export async function signInGuard(req: Request, res: Response, next: NextFunction) {
const key = `${req.method} ${req.path.replace(/\/+$/, '')}`;
const isMoved = MOVED.includes(key) || MOVED_PREFIXES.some((p) => key.startsWith(p));
const isMe = key === 'PATCH /api/v2/me';
const isAdminEdit = /^PATCH \/api\/v2\/users\/[^/]+$/.test(key);
if (!isMoved && !isMe && !isAdminEdit) return next();
try {
if (!(await viaAccounts())) {
if (LOCAL_SIGN_IN.includes(key)) {
const running = await getSetting(RUNNING_KEY);
if (running && Date.now() - new Date(running).getTime() < 30 * 60e3) {
return res.status(503).json({ error: { code: 'SIGN_IN_MOVING', message: 'One moment, we\'re updating the sign-in. Please try again in a minute.' } });
}
}
return next();
}
if (isMoved) return movedAnswer(res);
const body = (req.body ?? {}) as Record<string, unknown>;
if (isMe) {
if (body.password !== undefined || body.currentPassword !== undefined) return movedAnswer(res);
delete body.name;
delete body.email;
delete body.phone;
return next();
}
// An admin's change to someone (the route itself checks they're an admin).
if (body.password !== undefined || body.twoFactorEnabled !== undefined) return movedAnswer(res);
const changes: { name?: string; email?: string; phone?: string | null } = {};
if (typeof body.name === 'string') changes.name = body.name.trim();
if (typeof body.email === 'string') changes.email = body.email.trim().toLowerCase();
if (body.phoneNumber !== undefined) changes.phone = body.phoneNumber ? String(body.phoneNumber) : null;
if (!Object.keys(changes).length) return next();
const target = await prisma.user.findUnique({ where: { id: String(req.params?.id ?? req.path.split('/').pop()) }, select: { id: true, accountId: true, name: true, email: true, phoneNumber: true } });
if (!target?.accountId) return next();
const differs = (changes.name !== undefined && changes.name !== target.name) || (changes.email !== undefined && changes.email !== target.email) || (changes.phone !== undefined && changes.phone !== target.phoneNumber);
if (!differs) return next();
// Only for a signed-in admin: anyone else is refused by the route itself, untouched here.
const admin = await signedInAdmin(req);
if (!admin) return next();
await (await accounts()).request({ type: 'people.update', actor: admin.accountId, sub: target.accountId, ...changes });
return next();
} catch (e) {
if (e instanceof AccountsUnavailable) return res.status(503).json({ error: { code: 'UNAVAILABLE', message: e.message } });
const err = e as { code?: string; message: string };
if (err.code === 'EMAIL_TAKEN') return res.status(409).json({ error: { code: 'CONFLICT', message: 'Another account has that email address.' } });
if (err.code) return res.status(502).json({ error: { code: 'UNAVAILABLE', message: `Accounts didn't accept the change: ${err.message}` } });
return next(e);
}
}
/**
* The request's user when it's a valid, current admin token (as `protect` + `admin` would accept,
* not viewing as someone else), or null. Their `accountId` goes to Accounts' audit log.
*/
async function signedInAdmin(req: Request): Promise<{ id: string; accountId: string | null } | null> {
try {
const header = String(req.headers.authorization || '');
if (!header.startsWith('Bearer ')) return null;
// eslint-disable-next-line @typescript-eslint/no-require-imports
const jwt = require('jsonwebtoken');
const decoded = jwt.verify(header.slice(7), process.env.JWT_SECRET, { algorithms: ['HS256'] }) as { id?: string; tokenVersion?: number; imp?: string; asi?: string; mfa?: boolean };
// Viewing as someone, or an Accounts sign-in without the second step admins need.
if (!decoded.id || decoded.imp || (decoded.asi && decoded.mfa !== true)) return null;
const u = await prisma.user.findUnique({ where: { id: decoded.id }, select: { id: true, accountId: true, role: true, isActive: true, tokenVersion: true } });
if (!u || !u.isActive || u.role !== 'admin' || (decoded.tokenVersion ?? 0) !== u.tokenVersion) return null;
return { id: u.id, accountId: u.accountId };
} catch {
return null;
}
}
+49
View File
@@ -0,0 +1,49 @@
/**
* Where people sign in (3.0.0, docs/EVENTS-3.0-PLAN.md §5): `local` (Cross Events' own sign-in, as
* 2.x, before the move or after Undo) or `accounts` (through the church's Accounts). Kept in
* AppSetting `auth_mode`; read with a short cache, so every PM2 process follows a move within
* seconds. A new install starts in `accounts` (§9); everyone else starts in `local`.
*
* Other keys: `auth_moved_at` (ISO, when the move finished: Undo is allowed for 14 days, then the
* old secrets are cleared), `auth_move_report` (JSON), `auth_secrets_cleared_at` (ISO).
*/
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
/* eslint-enable @typescript-eslint/no-require-imports */
export type AuthMode = 'local' | 'accounts';
export const MODE_KEY = 'auth_mode';
export const MOVED_AT_KEY = 'auth_moved_at';
export const REPORT_KEY = 'auth_move_report';
export const CLEARED_KEY = 'auth_secrets_cleared_at';
export const UNDO_DAYS = 14;
const TTL_MS = 5000;
let cache: { mode: AuthMode; at: number } | null = null;
export async function authMode(): Promise<AuthMode> {
if (cache && Date.now() - cache.at < TTL_MS) return cache.mode;
const row = await prisma.appSetting.findUnique({ where: { key: MODE_KEY } }).catch(() => null);
const mode: AuthMode = row?.value === 'accounts' ? 'accounts' : 'local';
cache = { mode, at: Date.now() };
return mode;
}
export async function viaAccounts(): Promise<boolean> {
return (await authMode()) === 'accounts';
}
export async function setSetting(key: string, value: string | null): Promise<void> {
if (value === null) await prisma.appSetting.deleteMany({ where: { key } });
else await prisma.appSetting.upsert({ where: { key }, update: { value }, create: { key, value } });
if (key === MODE_KEY) cache = null;
}
export async function getSetting(key: string): Promise<string | null> {
return (await prisma.appSetting.findUnique({ where: { key } }))?.value ?? null;
}
/** For tests. */
export function forgetMode(): void {
cache = null;
}
+327
View File
@@ -0,0 +1,327 @@
/**
* Moving sign-in to the church's Accounts (3.0.0, docs/EVENTS-3.0-PLAN.md §4–§5), from
* Settings → Sign-in:
*
* check() a dry run: who would be moved, linked to an existing account, skipped or refused
* move() copies everyone into Accounts (crosscode.identity-request/1, batches of 200, secrets
* sealed with the link's secret), checks Accounts holds the same people, then switches
* `auth_mode` to `accounts`. Idempotent: a failed move can be run again
* undo() back to Cross Events' own sign-in, for 14 days (the old passwords are still here)
* clearOldSecrets() after those 14 days: Events' password hashes, authenticator secrets,
* recovery codes and trusted devices go (the `accounts-secrets` job)
*
* Who moves: everyone with a real email address who isn't linked yet. Guests (`@guest.local`) and
* deleted people stay Events-only. Recovery codes don't move (decision 2): Accounts shows new ones.
*/
import crypto from 'node:crypto';
import { IMPORT_BATCH_MAX, phoneSchema, type ImportPerson, type ImportResult } from '@crosscode/contracts';
import { importIdsHash } from '@crosscode/contracts/signing';
import { siteUrl } from '../feed/context';
import { accounts, accountsLink, AccountsUnavailable } from './client';
import { authMode, CLEARED_KEY, getSetting, MODE_KEY, MOVED_AT_KEY, REPORT_KEY, setSetting, UNDO_DAYS } from './mode';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const { decrypt } = require('../utils/encryption') as { decrypt(v: string): string };
const { logAdminAction } = require('../utils/adminAudit') as { logAdminAction(entry: object): Promise<void> };
const { getSettingSync } = require('../utils/settingsCache') as { getSettingSync(k: string, f?: string): string };
/* eslint-enable @typescript-eslint/no-require-imports */
export class MoveError extends Error {
constructor(message: string, public code = 'MOVE_FAILED', public status = 409) {
super(message);
}
}
/** While a move runs, Cross Events' own sign-in waits (people already signed in stay signed in). */
export const RUNNING_KEY = 'auth_move_running';
const MIN_ACCOUNTS = [1, 1, 0];
const NOT_MOVED = /@(guest\.local|deleted\.invalid|deleted\.local)$/i;
const HASH = /^(\$argon2(id|i|d)\$|\$2[aby]\$)/;
const iso = (d: Date | string | null | undefined) => (d ? new Date(d).toISOString() : null);
type Row = {
id: string; name: string; email: string; phoneNumber: string | null; password: string; role: string; isActive: boolean; createdAt: Date;
failedAttempts: number; lockUntil: Date | null; twoFactorEnabled: boolean; twoFactorMethod: string | null; totpSecret: string | null; totpLastStep: number | null;
newsEmail: boolean; newsWhatsApp: boolean; newsAskedAt: Date | null; noticeVersionAccepted: number | null; lastLoginAt: Date | null;
};
const SELECT = {
id: true, name: true, email: true, phoneNumber: true, password: true, role: true, isActive: true, createdAt: true, failedAttempts: true, lockUntil: true,
twoFactorEnabled: true, twoFactorMethod: true, totpSecret: true, totpLastStep: true, newsEmail: true, newsWhatsApp: true, newsAskedAt: true,
noticeVersionAccepted: true, lastLoginAt: true,
} as const;
/** The people who move: a real email, not linked yet. */
async function peopleToMove(): Promise<Row[]> {
const rows: Row[] = await prisma.user.findMany({ where: { accountId: null }, select: SELECT, orderBy: { createdAt: 'asc' } });
return rows.filter((u) => !NOT_MOVED.test(u.email));
}
async function skippedCount(): Promise<number> {
const rows: { email: string }[] = await prisma.user.findMany({ where: { accountId: null }, select: { email: true } });
return rows.filter((u) => NOT_MOVED.test(u.email)).length;
}
/** Accounts' notice versions are Events' + 1: its built-in notice is 1, Events' is 0 (null: never accepted). */
const toAccountsVersion = (v: number | null) => (v === null || v === undefined ? 0 : v + 1);
/** Never activated (made by staff, the link not used yet): Accounts' "choose your password" instead. */
const pendingActivation = (u: Row) => !u.isActive && !u.lastLoginAt;
async function person(u: Row, opts: { admins: Set<string>; seal: (v: string) => string; keepAccountsNotices: boolean }): Promise<ImportPerson> {
const [acceptances, consents] = await Promise.all([
prisma.noticeAcceptance.findMany({ where: { userId: u.id }, select: { version: true, createdAt: true }, orderBy: { createdAt: 'asc' }, take: 100 }),
prisma.communicationConsent.findMany({ where: { userId: u.id }, select: { channel: true, granted: true, createdAt: true }, orderBy: { createdAt: 'asc' }, take: 500 }),
]);
const totp = u.twoFactorEnabled && u.twoFactorMethod === 'authenticator' && u.totpSecret ? (() => { try { return decrypt(u.totpSecret!); } catch { return null; } })() : null;
// An authenticator whose secret can't be read moves without 2FA rather than locking them out.
const twoFactor = !u.twoFactorEnabled ? null : u.twoFactorMethod === 'authenticator' ? (totp ? 'totp' as const : null) : u.twoFactorMethod === 'whatsapp' ? 'whatsapp' as const : 'email' as const;
const phone = u.phoneNumber && phoneSchema.safeParse(u.phoneNumber).success ? u.phoneNumber : null;
return {
id: u.id,
name: (u.name || '').trim().slice(0, 200) || u.email,
email: u.email.trim().toLowerCase(),
emailVerified: !!u.lastLoginAt,
phone,
passwordHash: !pendingActivation(u) && HASH.test(u.password) ? opts.seal(u.password) : null,
twoFactor: twoFactor === 'whatsapp' && !phone ? 'email' : twoFactor,
totpSecret: totp ? opts.seal(totp) : null,
totpLastStep: totp ? u.totpLastStep ?? null : null,
failedSignIns: Math.min(1000, Math.max(0, u.failedAttempts || 0)),
lockedUntil: iso(u.lockUntil),
news: { email: !!u.newsEmail, whatsapp: !!u.newsWhatsApp },
newsAskedAt: iso(u.newsAskedAt),
noticeVersionAccepted: opts.keepAccountsNotices ? 0 : toAccountsVersion(u.noticeVersionAccepted),
noticeAcceptances: opts.keepAccountsNotices ? [] : acceptances.map((a: { version: number; createdAt: Date }) => ({ version: a.version + 1, acceptedAt: iso(a.createdAt)! })),
consentChanges: consents.filter((c: { channel: string }) => c.channel === 'email' || c.channel === 'whatsapp').map((c: { channel: 'email' | 'whatsapp'; granted: boolean; createdAt: Date }) => ({ channel: c.channel, granted: c.granted, at: iso(c.createdAt)! })),
lastSignInAt: iso(u.lastLoginAt),
status: u.isActive || pendingActivation(u) ? 'active' : 'deactivated',
admin: opts.admins.has(u.id) && u.role === 'admin',
createdAt: iso(u.createdAt)!,
};
}
/** Events' published notice versions, as Accounts numbers them. */
async function notices() {
const rows: { version: number; sections: unknown; publishedAt: Date }[] = await prisma.privacyNotice.findMany({ orderBy: { version: 'asc' }, take: 100 });
return rows.map((n) => {
const sections = Array.isArray(n.sections) ? (n.sections as { title?: string; body?: string }[]) : [];
const body = sections.map((s) => [s.title ? `${s.title}` : '', s.body ?? ''].filter(Boolean).join('\n\n')).join('\n\n').slice(0, 200_000) || 'Privacy notice';
return { version: n.version + 1, title: 'Privacy notice', body, publishedAt: iso(n.publishedAt)! };
});
}
function versionAtLeast(v: string, min: number[]) {
const parts = String(v).split('.').map((x) => parseInt(x, 10) || 0);
for (let i = 0; i < min.length; i++) {
if ((parts[i] ?? 0) !== min[i]) return (parts[i] ?? 0) > min[i]!;
}
return true;
}
const chunk = <T,>(list: T[], n: number) => Array.from({ length: Math.ceil(list.length / n) }, (_, i) => list.slice(i * n, i * n + n));
export type MoveSummary = {
mode: 'local' | 'accounts';
accountsConnected: boolean;
accountsUrl: string | null;
movedAt: string | null;
undoUntil: string | null;
secretsCleared: boolean;
running: boolean;
report: unknown;
};
export async function status(): Promise<MoveSummary> {
const [mode, link, movedAt, cleared, report, running] = await Promise.all([authMode(), accountsLink(), getSetting(MOVED_AT_KEY), getSetting(CLEARED_KEY), getSetting(REPORT_KEY), getSetting(RUNNING_KEY)]);
const undoUntil = movedAt && !cleared ? new Date(new Date(movedAt).getTime() + UNDO_DAYS * 86400e3).toISOString() : null;
return {
mode, accountsConnected: !!link, accountsUrl: link?.url ?? null, movedAt, undoUntil, secretsCleared: !!cleared,
running: !!running && Date.now() - new Date(running).getTime() < 30 * 60e3,
report: report ? JSON.parse(report) : null,
};
}
function church() {
const name = getSettingSync('org_name', '') || getSettingSync('site_name', '') || null;
const colour = getSettingSync('primary_color', '') || getSettingSync('brand_color', '');
return { name: name ? name.slice(0, 200) : null, primaryColour: /^#[0-9a-fA-F]{6}$/.test(colour) ? colour : null };
}
export type CheckResult = {
accountsVersion: string;
toMove: number;
wouldCreate: number;
wouldLink: { name: string; email: string }[];
refused: { name: string; email: string; reason: string }[];
skipped: number;
admins: { id: string; name: string; email: string }[];
noticeConflict: { accountsVersions: number[]; eventsVersions: number[] } | null;
withTwoFactor: number;
};
async function connected() {
if ((await authMode()) === 'accounts') throw new MoveError('Sign-in already goes through Accounts.', 'ALREADY_MOVED');
try {
return await accounts();
} catch (e) {
if (e instanceof AccountsUnavailable) throw new MoveError(e.message, 'ACCOUNTS_UNAVAILABLE', 503);
throw e;
}
}
/** The dry run: nothing is written, here or in Accounts. */
export async function check(): Promise<CheckResult> {
const auth = await connected();
const begin = await auth.request<{ noticesTaken: boolean; accountsNoticeVersions: number[]; accountsVersion: string }>({ type: 'import.begin', actor: null, check: true, notices: [], church: church() });
if (!versionAtLeast(begin.accountsVersion, MIN_ACCOUNTS)) {
throw new MoveError(`The church's Accounts is version ${begin.accountsVersion}; moving sign-in needs 1.1.0 or later. Update Accounts first.`, 'ACCOUNTS_TOO_OLD');
}
const people = await peopleToMove();
const seal = (v: string) => auth.seal(v);
const byId = new Map(people.map((p) => [p.id, p]));
const results: ImportResult[] = [];
for (const batch of chunk(people, IMPORT_BATCH_MAX)) {
const built = await Promise.all(batch.map((u) => person(u, { admins: new Set(), seal, keepAccountsNotices: false })));
const r = await auth.request<{ results: ImportResult[] }>({ type: 'import.batch', actor: null, check: true, people: built });
results.push(...r.results);
}
const eventsNotices = await notices();
const who = (id: string) => ({ name: byId.get(id)?.name ?? '', email: byId.get(id)?.email ?? '' });
return {
accountsVersion: begin.accountsVersion,
toMove: people.length,
wouldCreate: results.filter((r) => r.outcome === 'created' || r.outcome === 'updated').length,
wouldLink: results.filter((r) => r.outcome === 'linked').map((r) => who(r.id)),
refused: results.filter((r) => r.outcome === 'refused').map((r) => ({ ...who(r.id), reason: r.reason ?? '' })),
skipped: await skippedCount(),
admins: people.filter((p) => p.role === 'admin').map((p) => ({ id: p.id, name: p.name, email: p.email })),
noticeConflict: !begin.noticesTaken && eventsNotices.length ? { accountsVersions: begin.accountsNoticeVersions, eventsVersions: eventsNotices.map((n) => n.version - 1) } : null,
withTwoFactor: people.filter((p) => p.twoFactorEnabled).length,
};
}
export type MoveReport = {
movedAt: string;
by: string;
created: number;
linked: { name: string; email: string }[];
refused: { name: string; email: string; reason: string }[];
skipped: number;
accountsAdmins: { name: string; email: string }[];
notices: 'events' | 'accounts';
};
/** The move. Throws MoveError when it doesn't finish; nothing changes for anyone then. */
export async function move(opts: { actor: { id: string; role: string; name?: string }; adminIds: string[]; keepAccountsNotices?: boolean; ip?: string | null }): Promise<MoveReport> {
const auth = await connected();
const running = await getSetting(RUNNING_KEY);
if (running && Date.now() - new Date(running).getTime() < 30 * 60e3) throw new MoveError('A move is already running.', 'RUNNING');
await setSetting(RUNNING_KEY, new Date().toISOString());
const audit = (action: string, metadata: object) => logAdminAction({ actorId: opts.actor.id, actorRole: opts.actor.role, action, targetType: 'setting', targetId: MODE_KEY, metadata, ip: opts.ip ?? null });
await audit('sign_in_move_started', { adminIds: opts.adminIds });
let begun = false;
try {
const eventsNotices = await notices();
const begin = await auth.request<{ noticesTaken: boolean; accountsVersion: string }>({
type: 'import.begin', actor: opts.actor.id, check: false, notices: opts.keepAccountsNotices ? [] : eventsNotices, church: church(),
});
begun = true;
if (!versionAtLeast(begin.accountsVersion, MIN_ACCOUNTS)) throw new MoveError(`The church's Accounts is version ${begin.accountsVersion}; moving sign-in needs 1.1.0 or later.`, 'ACCOUNTS_TOO_OLD');
if (!begin.noticesTaken && eventsNotices.length && !opts.keepAccountsNotices) {
throw new MoveError('Accounts already has its own privacy notice. Choose which notice to keep, then move again.', 'NOTICE_CONFLICT');
}
const people = await peopleToMove();
const byId = new Map(people.map((p) => [p.id, p]));
const admins = new Set(opts.adminIds);
const results: ImportResult[] = [];
for (const batch of chunk(people, IMPORT_BATCH_MAX)) {
const built = await Promise.all(batch.map((u) => person(u, { admins, seal: (v) => auth.seal(v), keepAccountsNotices: !!opts.keepAccountsNotices })));
const r = await auth.request<{ results: ImportResult[] }>({ type: 'import.batch', actor: opts.actor.id, check: false, people: built }, { timeoutMs: 120000 });
for (const res of r.results) {
if (res.sub && res.outcome !== 'refused') await prisma.user.update({ where: { id: res.id }, data: { accountId: res.sub } });
}
results.push(...r.results);
}
// Everyone this site has linked, including a move run again after a failure.
const linkedRows: { accountId: string }[] = await prisma.user.findMany({ where: { accountId: { not: null } }, select: { accountId: true } });
const subs = [...new Set(linkedRows.map((x) => x.accountId))];
const finish = await auth.request<{ matched: boolean; count: number }>({ type: 'import.finish', actor: opts.actor.id, count: subs.length, idsHash: importIdsHash(subs) });
if (!finish.matched) throw new MoveError(`Accounts holds ${finish.count} people from this site, but ${subs.length} were sent. Nothing was switched; run the move again.`, 'MISMATCH');
const who = (id: string) => ({ name: byId.get(id)?.name ?? '', email: byId.get(id)?.email ?? '' });
const report: MoveReport = {
movedAt: new Date().toISOString(),
by: opts.actor.name ?? opts.actor.id,
created: results.filter((r) => r.outcome === 'created' || r.outcome === 'updated').length,
linked: results.filter((r) => r.outcome === 'linked').map((r) => who(r.id)),
refused: results.filter((r) => r.outcome === 'refused').map((r) => ({ ...who(r.id), reason: r.reason ?? '' })),
skipped: await skippedCount(),
accountsAdmins: people.filter((p) => admins.has(p.id) && p.role === 'admin').map((p) => ({ name: p.name, email: p.email })),
notices: opts.keepAccountsNotices ? 'accounts' : 'events',
};
await setSetting(REPORT_KEY, JSON.stringify(report));
await setSetting(MOVED_AT_KEY, report.movedAt);
await setSetting(CLEARED_KEY, null);
await setSetting(MODE_KEY, 'accounts');
await audit('sign_in_move_finished', { created: report.created, linked: report.linked.length, refused: report.refused.length, skipped: report.skipped });
emailReport(opts.actor.id, report).catch(() => {});
return report;
} catch (e) {
if (begun) await auth.request({ type: 'import.abort', actor: opts.actor.id }).catch(() => {});
await audit('sign_in_move_failed', { message: (e as Error).message });
if (e instanceof MoveError) throw e;
throw new MoveError(`The move stopped: ${(e as Error).message}. Nothing was switched; you can run it again.`, (e as { code?: string }).code ?? 'MOVE_FAILED', 502);
} finally {
await setSetting(RUNNING_KEY, null);
}
}
async function emailReport(actorId: string, report: MoveReport) {
const admin = await prisma.user.findUnique({ where: { id: actorId }, select: { email: true, name: true } });
if (!admin?.email || NOT_MOVED.test(admin.email)) return;
const { sendMail } = require('../utils/email') as { sendMail(m: object): Promise<void> };
const lines = [
`Hello ${admin.name || 'there'},`,
'',
`Sign-in for ${await siteUrl()} now goes through your church's Accounts.`,
'',
`Moved: ${report.created}`,
`Linked to an account they already had: ${report.linked.length}${report.linked.length ? ` (${report.linked.map((l) => l.email).join(', ')})` : ''}`,
`Not moved: ${report.refused.length}${report.refused.length ? ` (${report.refused.map((r) => `${r.email}: ${r.reason}`).join('; ')})` : ''}`,
`Guests and deleted people (stay in Cross Events only): ${report.skipped}`,
`Also Accounts admins: ${report.accountsAdmins.map((a) => a.name).join(', ') || 'nobody'}`,
'',
`You can undo this under Settings → Sign-in for ${UNDO_DAYS} days.`,
];
await sendMail({ to: admin.email, subject: 'Sign-in has moved to your church\'s Accounts', text: lines.join('\n'), html: lines.map((l) => (l ? `<p>${l.replace(/</g, '&lt;')}</p>` : '')).join('') });
}
export async function undo(actor: { id: string; role: string }, ip: string | null = null) {
const s = await status();
if (s.mode !== 'accounts') throw new MoveError('Sign-in is already in Cross Events.', 'NOT_MOVED');
if (!s.undoUntil || new Date(s.undoUntil) < new Date()) throw new MoveError(`Undo was possible for ${UNDO_DAYS} days after the move; the old passwords have been removed since.`, 'TOO_LATE');
await setSetting(MODE_KEY, 'local');
await logAdminAction({ actorId: actor.id, actorRole: actor.role, action: 'sign_in_move_undone', targetType: 'setting', targetId: MODE_KEY, metadata: { movedAt: s.movedAt }, ip });
return status();
}
/** The `accounts-secrets` job: 14 days after the move, Events stops holding passwords and 2FA secrets. */
export async function clearOldSecrets(now = new Date()) {
const [mode, movedAt, cleared] = await Promise.all([authMode(), getSetting(MOVED_AT_KEY), getSetting(CLEARED_KEY)]);
if (mode !== 'accounts' || !movedAt || cleared) return { cleared: 0 };
if (now.getTime() - new Date(movedAt).getTime() < UNDO_DAYS * 86400e3) return { cleared: 0 };
const linked: { id: string }[] = await prisma.user.findMany({ where: { accountId: { not: null } }, select: { id: true } });
const ids = linked.map((u) => u.id);
for (const id of ids) {
await prisma.user.update({ where: { id }, data: { password: `!accounts:${crypto.randomBytes(12).toString('hex')}`, totpSecret: null, totpLastStep: null } });
}
await prisma.recoveryCode.deleteMany({ where: { userId: { in: ids } } });
await prisma.trustedDevice.deleteMany({ where: { userId: { in: ids } } });
await prisma.passwordReset.updateMany({ where: { userId: { in: ids }, used: false }, data: { used: true } });
await setSetting(CLEARED_KEY, now.toISOString());
await logAdminAction({ actorId: null, actorRole: 'system', action: 'sign_in_secrets_cleared', targetType: 'setting', targetId: MODE_KEY, metadata: { people: ids.length } });
return { cleared: ids.length };
}
+25
View File
@@ -0,0 +1,25 @@
/**
* News consent lives in the church's Accounts once sign-in goes through it (3.0.0,
* docs/EVENTS-3.0-PLAN.md decision 7). An unsubscribe link or a WhatsApp STOP here turns news off
* there too (`people.newsOff`), so it's off for every product, and Accounts' next `user.updated`
* doesn't turn it back on here. Never fails the unsubscribe itself.
*/
import { accounts } from './client';
import { viaAccounts } from './mode';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
/* eslint-enable @typescript-eslint/no-require-imports */
export async function newsOffInAccounts(userId: string, channels: string[]): Promise<void> {
try {
if (!(await viaAccounts())) return;
const u = await prisma.user.findUnique({ where: { id: userId }, select: { accountId: true } });
if (!u?.accountId) return;
const both = channels.includes('email') && channels.includes('whatsapp');
const channel = both ? 'all' : channels.includes('whatsapp') ? 'whatsapp' : 'email';
await (await accounts()).request({ type: 'people.newsOff', actor: null, sub: u.accountId, channel });
} catch (e) {
console.warn('[accounts] news off not passed on:', (e as Error).message);
}
}
+280
View File
@@ -0,0 +1,280 @@
/**
* Signing in through the church's Accounts (3.0.0, docs/EVENTS-3.0-PLAN.md §3), under /api:
*
* GET /auth/signin?returnTo=…[&signup=1][&mfa=1] start: PKCE + state, a pending cookie, off to Accounts
* GET /auth/callback back from Accounts: find or link the user, then
* /auth/complete#<one-time code>
* POST /auth/handoff { code } the page swaps the code for Events' own token
* POST /auth/signout ends Events' sessions; answers Accounts' sign-out address
* POST /auth/backchannel-logout Accounts: this person signed out somewhere
* POST /accounts/v1/events Accounts: user.updated / user.export / user.deleted
*
* Events keeps its own session (the 30-day token with `tokenVersion`), so the rest of the API is
* unchanged; only how a token is obtained changes. The token carries `asi` (this sign-in's row) and
* `mfa` (whether Accounts asked for a second step), which `protect` checks for staff roles.
*/
import crypto from 'node:crypto';
import express, { type Request, type Response } from 'express';
import { ACCOUNTS_CALL_PATH, OIDC_CLIENT_PATHS, safeReturnPath, type IdentityClaims } from '@crosscode/contracts';
import { siteUrl } from '../feed/context';
import { accounts, AccountsUnavailable } from './client';
import { viaAccounts } from './mode';
import { handleAccountsCall } from './calls';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const { generateToken } = require('../config/auth') as { generateToken(id: string, role: string, v: number, extra?: object): string };
const { encrypt, decrypt } = require('../utils/encryption') as { encrypt(v: string): string; decrypt(v: string): string };
const { requiresTwoFactor } = require('../utils/twoFactor') as { requiresTwoFactor(u: { role: string }): boolean };
const { logSecurityEvent } = require('../utils/securityEvents') as { logSecurityEvent(e: object): Promise<void> };
const { getClientIp } = require('../utils/requestUtils') as { getClientIp(req: unknown): string | null };
/* eslint-enable @typescript-eslint/no-require-imports */
const PENDING_COOKIE = 'ev_signin';
const MFA_COOKIE = 'ev_signin_mfa';
const COOKIE_PATH = '/api/auth';
const PENDING_MINUTES = 10;
const HANDOFF_SECONDS = 60;
const hash = (s: string) => crypto.createHash('sha256').update(s).digest('hex');
function cookies(req: Request): Record<string, string> {
const out: Record<string, string> = {};
for (const part of String(req.headers.cookie || '').split(';')) {
const i = part.indexOf('=');
if (i > 0) out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());
}
return out;
}
const cookieOptions = () => ({ httpOnly: true, sameSite: 'lax' as const, secure: process.env.NODE_ENV === 'production', path: COOKIE_PATH });
/** A page of this site (absolute: in development the API and the pages are on different ports). */
async function page(path: string): Promise<string> {
return `${(await siteUrl()).replace(/\/+$/, '')}${path}`;
}
/** Where a problem page sends people: a short reason and "Try again" with the same return path. */
const problem = async (res: Response, code: string, returnTo = '/') =>
res.redirect(303, await page(`/auth/problem?code=${encodeURIComponent(code)}&returnTo=${encodeURIComponent(safeReturnPath(returnTo))}`));
/** A placeholder for `User.password` (required by the schema): never a valid hash, so never a password. */
const NO_PASSWORD = () => `!accounts:${crypto.randomBytes(12).toString('hex')}`;
type EventsUser = { id: string; name: string; email: string; role: string; tokenVersion: number; isActive: boolean; accountId: string | null; phoneNumber: string | null };
const USER_SELECT = { id: true, name: true, email: true, role: true, tokenVersion: true, isActive: true, accountId: true, phoneNumber: true } as const;
const isGuestEmail = (e: string) => /@(guest\.local|deleted\.invalid|deleted\.local)$/.test(e);
/**
* The Events user for an Accounts sign-in (§2): by `accountId`; else a user (often a guest
* record from the door) with the same **verified** email that isn't linked yet; else a new `user`.
*/
export async function userForClaims(claims: IdentityClaims): Promise<{ user: EventsUser | null; problem?: string; linked?: boolean; created?: boolean }> {
const byAccount = await prisma.user.findUnique({ where: { accountId: claims.sub }, select: USER_SELECT });
if (byAccount) return { user: byAccount };
const email = claims.email.toLowerCase();
const byEmail = await prisma.user.findFirst({ where: { email: { equals: email, mode: 'insensitive' } }, select: USER_SELECT });
if (byEmail) {
if (byEmail.accountId) return { user: null, problem: 'EMAIL_IN_USE' };
if (!claims.email_verified) return { user: null, problem: 'EMAIL_NOT_VERIFIED' };
const linked = await prisma.user.update({ where: { id: byEmail.id }, data: { accountId: claims.sub }, select: USER_SELECT });
return { user: linked, linked: true };
}
// New to Events. Its id is the sub when that's free, as for everyone moved in.
const taken = await prisma.user.findUnique({ where: { id: claims.sub }, select: { id: true } });
const created = await prisma.user.create({
data: {
...(taken ? {} : { id: claims.sub }),
accountId: claims.sub,
name: claims.name,
email,
password: NO_PASSWORD(),
role: 'user',
newsEmail: claims.news_consent.email,
newsWhatsApp: claims.news_consent.whatsapp,
newsAskedAt: new Date(),
// Accounts' notice versions are Events' + 1 (its built-in notice is 1, Events' is 0).
noticeVersionAccepted: Math.max(0, claims.privacy_notice_version - 1),
},
select: USER_SELECT,
});
return { user: created, created: true };
}
/** Keeps Events' copy of the profile (for lists and messages) as Accounts has it. */
export async function updateLocalCopy(userId: string, profile: Pick<IdentityClaims, 'name' | 'email' | 'phone_number' | 'news_consent'> & { privacy_notice_version?: number; two_factor?: IdentityClaims['two_factor'] }) {
const data: Record<string, unknown> = {
name: profile.name,
// The 2FA method, for admins' list of staff (2.3.0); Accounts' `totp` is Events' `authenticator`.
...(profile.two_factor !== undefined ? { twoFactorEnabled: profile.two_factor !== null, twoFactorMethod: profile.two_factor === 'totp' ? 'authenticator' : profile.two_factor } : {}),
newsEmail: profile.news_consent.email,
newsWhatsApp: profile.news_consent.whatsapp,
...(profile.privacy_notice_version ? { noticeVersionAccepted: Math.max(0, profile.privacy_notice_version - 1) } : {}),
};
const email = profile.email.toLowerCase();
const sameEmail = await prisma.user.findFirst({ where: { email: { equals: email, mode: 'insensitive' }, NOT: { id: userId } }, select: { id: true } });
if (!sameEmail && !isGuestEmail(email)) data.email = email;
if (profile.phone_number) {
const samePhone = await prisma.user.findFirst({ where: { phoneNumber: profile.phone_number, NOT: { id: userId } }, select: { id: true } });
if (!samePhone) data.phoneNumber = profile.phone_number;
} else {
data.phoneNumber = null;
}
await prisma.user.update({ where: { id: userId }, data });
}
async function startSignIn(req: Request, res: Response) {
const returnTo = safeReturnPath(req.query.returnTo);
if (!(await viaAccounts())) return res.redirect(303, await page(`/login?redirect=${encodeURIComponent(returnTo)}&local=1`));
try {
const auth = await accounts();
const requireTwoFactor = req.query.mfa === '1';
const { url, cookie } = await auth.startSignIn(returnTo, {
requireTwoFactor,
signUp: req.query.signup === '1',
...(typeof req.query.email === 'string' && req.query.email.length < 200 ? { loginHint: req.query.email } : {}),
});
res.cookie(PENDING_COOKIE, cookie, { ...cookieOptions(), maxAge: PENDING_MINUTES * 60e3 });
if (requireTwoFactor) res.cookie(MFA_COOKIE, '1', { ...cookieOptions(), maxAge: PENDING_MINUTES * 60e3 });
else res.clearCookie(MFA_COOKIE, cookieOptions());
return res.redirect(303, url);
} catch (e) {
console.warn('[accounts] sign-in could not start:', (e as Error).message);
return problem(res, e instanceof AccountsUnavailable ? 'ACCOUNTS_UNAVAILABLE' : 'START_FAILED', returnTo);
}
}
async function callback(req: Request, res: Response) {
const jar = cookies(req);
const askedMfa = jar[MFA_COOKIE] === '1';
res.clearCookie(PENDING_COOKIE, cookieOptions());
res.clearCookie(MFA_COOKIE, cookieOptions());
// Cancelled at Accounts: back to the home page, signed out.
if (req.query.error === 'access_denied') return res.redirect(303, await page('/'));
let auth;
try {
auth = await accounts();
} catch {
return problem(res, 'ACCOUNTS_UNAVAILABLE');
}
let signed;
try {
// The address Accounts sent the browser to, as it registered it (never the backend's own port).
signed = await auth.finishSignIn(`${(await siteUrl()).replace(/\/+$/, '')}${req.originalUrl}`, jar[PENDING_COOKIE]);
} catch (e) {
const code = (e as { code?: string }).code;
console.warn('[accounts] sign-in could not finish:', (e as Error).message);
return problem(res, code === 'NO_PENDING' ? 'EXPIRED' : 'FINISH_FAILED');
}
const { claims, returnTo, idToken } = signed;
const found = await userForClaims(claims);
if (!found.user) return problem(res, found.problem ?? 'NO_USER', returnTo);
const user = found.user;
if (!user.isActive) return problem(res, 'EVENTS_OFF', returnTo);
// Staff roles need a second step (§3): ask Accounts for it once; a second miss is a problem.
const mfa = claims.amr.includes('mfa');
if (requiresTwoFactor(user) && !mfa) {
if (askedMfa) return problem(res, 'MFA_REQUIRED', returnTo);
return res.redirect(303, `/api/auth/signin?mfa=1&returnTo=${encodeURIComponent(returnTo)}`);
}
await updateLocalCopy(user.id, claims).catch((e: Error) => console.warn('[accounts] profile copy:', e.message));
await prisma.user.update({ where: { id: user.id }, data: { lastLoginAt: new Date(), inactivityWarnedAt: null } }).catch(() => {});
logSecurityEvent({ userId: user.id, type: 'login', ip: getClientIp(req), userAgent: req.headers['user-agent'] }).catch(() => {});
const code = crypto.randomBytes(32).toString('base64url');
const sid = (claims as unknown as { sid?: string }).sid ?? null;
await prisma.accountsSignIn.create({
data: { userId: user.id, codeHash: hash(code), codeUsedAt: null, codeExpires: new Date(Date.now() + HANDOFF_SECONDS * 1000), returnTo, idToken: encrypt(idToken), sid, mfa },
});
return res.redirect(303, await page(`/auth/complete#${code}`));
}
async function handoff(req: Request, res: Response) {
const code = typeof req.body?.code === 'string' ? req.body.code : '';
const row = code ? await prisma.accountsSignIn.findUnique({ where: { codeHash: hash(code) } }) : null;
if (!row || row.codeUsedAt || !row.codeExpires || row.codeExpires < new Date()) {
return res.status(400).json({ error: { code: 'EXPIRED', message: 'This sign-in has expired. Please sign in again.' } });
}
// Single use, whatever happens next.
const used = await prisma.accountsSignIn.updateMany({ where: { id: row.id, codeUsedAt: null }, data: { codeUsedAt: new Date(), codeHash: null } });
if (!used.count) return res.status(400).json({ error: { code: 'EXPIRED', message: 'This sign-in has expired. Please sign in again.' } });
const user = await prisma.user.findUnique({ where: { id: row.userId }, select: USER_SELECT });
if (!user || !user.isActive) return res.status(401).json({ error: { code: 'UNAUTHENTICATED', message: 'Please sign in again.' } });
return res.json({
data: {
status: 'signed_in',
token: generateToken(user.id, user.role, user.tokenVersion, { asi: row.id, mfa: row.mfa }),
user: { id: user.id, name: user.name, email: user.email, role: user.role },
newsPromptPending: false,
noticePromptPending: false,
returnTo: safeReturnPath(row.returnTo),
},
});
}
/** Ends this person's Events sessions (every token they hold stops working at the next request). */
export async function endEventsSessions(userId: string) {
await prisma.user.update({ where: { id: userId }, data: { tokenVersion: { increment: 1 } } });
}
async function signOut(req: Request, res: Response) {
// `protect` ran: req.user is the person; the token's `asi` finds the ID token for Accounts.
const user = (req as unknown as { user?: { id: string } }).user;
const asi = (req as unknown as { tokenClaims?: { asi?: string } }).tokenClaims?.asi;
if (!user) return res.status(401).json({ error: { code: 'UNAUTHENTICATED', message: 'Not signed in.' } });
await endEventsSessions(user.id);
let url: string | null = null;
if (await viaAccounts()) {
try {
const row = asi ? await prisma.accountsSignIn.findUnique({ where: { id: asi } }) : null;
const idToken = row?.idToken ? (() => { try { return decrypt(row.idToken); } catch { return undefined; } })() : undefined;
url = (await accounts()).signOutUrl(idToken);
} catch (e) {
console.warn('[accounts] sign-out address:', (e as Error).message);
}
}
return res.json({ data: { signedOut: true, url } });
}
async function backchannelLogout(req: Request, res: Response) {
try {
const { sub } = await (await accounts()).verifyLogoutToken(String(req.body?.logout_token ?? ''));
const user = await prisma.user.findUnique({ where: { accountId: sub }, select: { id: true } });
if (user) await endEventsSessions(user.id);
return res.status(200).end();
} catch (e) {
console.warn('[accounts] back-channel logout refused:', (e as Error).message);
return res.status(400).json({ error: 'invalid_request' });
}
}
async function accountsCall(req: Request, res: Response) {
try {
const raw = Buffer.isBuffer(req.body) ? req.body : Buffer.from('');
const call = (await accounts()).verifyAccountsCall(raw, req.headers as Record<string, string | string[] | undefined>);
return res.json(await handleAccountsCall(call));
} catch (e) {
const err = e as { code?: string; message: string; status?: number };
const status = err.code === 'BAD_SIGNATURE' || err.code === 'STALE_REQUEST' ? 401 : err.code === 'INVALID_REQUEST' ? 400 : err.status ?? 500;
if (status >= 500) console.warn('[accounts] call failed:', err.message);
return res.status(status).json({ message: err.message, code: err.code ?? 'SERVER_ERROR' });
}
}
/** Mounted at /api before express.json (the Accounts calls need the exact bytes). */
export function accountsRouter(protect: express.RequestHandler) {
const r = express.Router();
const strip = (p: string) => p.replace(/^\/api/, '');
r.get('/auth/signin', startSignIn);
r.get(strip(OIDC_CLIENT_PATHS.callback), callback);
r.post('/auth/handoff', express.json({ limit: '4kb' }), handoff);
r.post('/auth/signout', express.json({ limit: '4kb' }), protect, signOut);
r.post(strip(OIDC_CLIENT_PATHS.backchannelLogout), express.urlencoded({ extended: false, limit: '16kb' }), backchannelLogout);
r.post(strip(ACCOUNTS_CALL_PATH), express.raw({ type: () => true, limit: '256kb' }), accountsCall);
return r;
}