- contracts 1.8.0 / Accounts 1.1.0: import.finish lists the subs the product relies on; Accounts checks each is held, not deleted and known to it (the count+hash failed a second move after Undo once someone had joined through Accounts). - Events: connects to the church's Accounts once the Hub lists it; moveNewPeople (demo data, people added after the move); set-demo moves demo people; e2e/sign-in-accounts.spec.ts with Accounts in memory and an e2e-only /api rewrite. test:accounts 14/14; Jest auto-connect tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
369 lines
21 KiB
TypeScript
369 lines
21 KiB
TypeScript
/**
|
|
* 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 { 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';
|
|
};
|
|
|
|
/**
|
|
* 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<ReturnType<typeof accounts>>, 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;
|
|
}
|
|
}
|
|
|
|
/** 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);
|
|
}
|
|
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<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, '<')}</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 };
|
|
}
|