/** * 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, REMOVE_DEMO_MAX, type ImportPerson, type ImportResult } from '@crosscode/contracts'; import { siteUrl } from '../feed/context'; import { accounts, accountsLink, AccountsUnavailable } from './client'; import { accountsMessaging } from './messaging'; import { churchLook } from './look'; 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 }; /* 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 { 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 { 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; seal: (v: string) => string; keepAccountsNotices: boolean }): Promise { 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 = (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 { 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, }; } 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; /** 3.1.0: what Accounts can send. The move needs email (codes and password links); WhatsApp codes go by email when WhatsApp can't. */ messaging: { email: boolean; whatsapp: boolean; whatsappTwoFactor: 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 { const auth = await connected(); const begin = await auth.request<{ noticesTaken: boolean; accountsNoticeVersions: number[]; accountsVersion: string }>({ type: 'import.begin', actor: null, check: true, notices: [], church: await churchLook() }); 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, messaging: await messagingNow(people), }; } async function messagingNow(people: Row[]) { const status = await accountsMessaging(); return { email: status.email.ready, whatsapp: status.whatsapp.ready, whatsappTwoFactor: people.filter((p) => p.twoFactorEnabled && p.twoFactorMethod === 'whatsapp').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'; }; /** * Ends a move: Accounts checks it holds every account this site now relies on (everyone linked, * including a move run again after a failure, and people who signed up through Accounts since). */ async function finishMove(auth: Awaited>, actor: string | null) { 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; missing: string[] }>({ type: 'import.finish', actor, subs }); if (!finish.matched) { throw new MoveError(`Accounts holds ${finish.count} of the ${subs.length} people this site relies on (missing, for example, ${finish.missing.slice(0, 3).join(', ')}). Nothing was switched; run the move again.`, 'MISMATCH'); } } /** * People added here after sign-in moved, without signing in through Accounts (demo data, an * import): moved into Accounts the same way, so they can sign in. Only while sign-in goes through * Accounts; returns how many were moved. */ export async function moveNewPeople(actor: string | null = null): Promise<{ moved: number; refused: { email: string; reason: string }[] }> { if ((await authMode()) !== 'accounts') return { moved: 0, refused: [] }; const people = await peopleToMove(); if (!people.length) return { moved: 0, refused: [] }; const auth = await accounts(); await auth.request({ type: 'import.begin', actor, check: false, notices: [], church: { name: null, primaryColour: null } }); try { const byId = new Map(people.map((p) => [p.id, p])); let moved = 0; const refused: { email: string; reason: string }[] = []; for (const batch of chunk(people, IMPORT_BATCH_MAX)) { const built = await Promise.all(batch.map((u) => person(u, { admins: new Set(), seal: (v) => auth.seal(v), keepAccountsNotices: false }))); const r = await auth.request<{ results: ImportResult[] }>({ type: 'import.batch', actor, 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 } }); moved++; } else refused.push({ email: byId.get(res.id)?.email ?? res.id, reason: res.reason ?? '' }); } } await finishMove(auth, actor); return { moved, refused }; } catch (e) { await auth.request({ type: 'import.abort', actor }).catch(() => {}); throw e; } } /** * 3.3.0: new demo data replaced the old (set-demo), so the old demo people's church accounts go * too (contracts 1.11.0 `people.removeDemo`). Accounts removes only demo addresses * (`@example.com`) it knows through this site, never an Accounts admin. Only while sign-in goes * through Accounts; returns how many went and how many it kept. */ export async function removeDemoPeople(subs: string[], actor: string | null = null): Promise<{ removed: number; kept: number }> { const unique = [...new Set(subs.filter(Boolean))]; if ((await authMode()) !== 'accounts' || !unique.length) return { removed: 0, kept: 0 }; const auth = await accounts(); let removed = 0; let kept = 0; for (const batch of chunk(unique, REMOVE_DEMO_MAX)) { const r = await auth.request<{ removed: number; kept: unknown[] }>({ type: 'people.removeDemo', actor, subs: batch }, { timeoutMs: 120000 }); removed += r.removed; kept += r.kept.length; } return { removed, kept }; } /** 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 { const auth = await connected(); // 3.1.0: without email in Accounts nobody can get a code or a password link there, so nobody // could sign in after the move. Set it up first (Settings → Sign-in → Email and WhatsApp). const messaging = await accountsMessaging(); if (!messaging.email.ready) { throw new MoveError("The church's Accounts can't send email yet, so people couldn't get their sign-in codes or password links there. Set up its email first (copy this site's, test it, save it), then move.", 'EMAIL_NOT_READY'); } 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: await churchLook(), }); 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); } await finishMove(auth, opts.actor.id); 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 }; 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 ? `

${l.replace(/` : '')).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 }; }