Files
crosscode-platform/apps/accounts/backend/src/accounts/twoFactor.ts
T
joshuaandClaude Opus 5.5 069b66fd30 Accounts 1.0.0 backend: OIDC provider, sign-in steps, account and admin API
oidc-provider 9.13.3 with PKCE, ES256, crosscode.identity/1 claims and
back-channel logout; clients are the linked products (Connect). Sign-in
steps (password, sign-up, email check, 2FA and its setup, privacy notice,
news question, password reset) survive to the product. Account page and
admin API, church profile, export and deletion fan-out, Hub v2 client,
jobs. End-to-end tests with a test product on openid-client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:33:49 +02:00

99 lines
5.1 KiB
TypeScript

/**
* Two-factor sign-in (as Cross Events 2.3): an authenticator app (TOTP), or a code by email or
* WhatsApp, with 10 single-use recovery codes. Used by the sign-in flow and the account page.
*/
import type { Request } from 'express';
import type { Ctx } from '../context.js';
import type { Account } from '../generated/prisma/client.js';
import { codeMatches, sendCode, CODE_MINUTES } from './service.js';
import { loginEvent } from '../lib/audit.js';
import { hashRecoveryCode, newRecoveryCodes } from '../lib/recoveryCodes.js';
import { generateSecret, matchStep, otpauthUrl } from '../lib/totp.js';
export class TwoFactorError extends Error {
status = 400;
constructor(message: string, public code = 'BAD_CODE') {
super(message);
}
}
const METHODS = new Set(['totp', 'email', 'whatsapp']);
/** After a second factor: RFC 8176 `otp` and `mfa`. */
export const accessAfterTwoFactor = (amr: string[]) => [...new Set([...amr, 'otp', 'mfa'])];
export async function verifyTotp(ctx: Ctx, a: Account, code: unknown): Promise<boolean> {
if (!a.totpSecret) return false;
const step = matchStep(ctx.secrets.decrypt(a.totpSecret), code, { now: ctx.now().getTime(), afterStep: a.totpLastStep ?? -1 });
if (step === null) return false;
await ctx.db.account.update({ where: { id: a.id }, data: { totpLastStep: step } });
return true;
}
export async function useRecoveryCode(ctx: Ctx, a: Account, code: unknown, req?: Request): Promise<boolean> {
const row = await ctx.db.recoveryCode.findUnique({ where: { codeHash: hashRecoveryCode(String(code)) } });
if (!row || row.accountId !== a.id || row.usedAt) return false;
await ctx.db.recoveryCode.update({ where: { id: row.id }, data: { usedAt: ctx.now() } });
await loginEvent(ctx, a.id, 'recovery_code_used', req);
return true;
}
/** Starts setting up a method: an app gets a new secret to scan; email or WhatsApp gets a code. */
export async function startTwoFactorSetup(ctx: Ctx, a: Account, method: unknown) {
if (!METHODS.has(String(method))) throw new TwoFactorError('Choose how you want to get your codes.', 'BAD_METHOD');
if (method === 'whatsapp' && (!a.phone || !(await ctx.messenger.whatsappReady()))) throw new TwoFactorError('WhatsApp codes need a phone number on your account.', 'BAD_METHOD');
if (method === 'totp') {
const secret = generateSecret();
const issuer = (await ctx.settings.json<{ shortName?: string; name?: string }>('church_profile', {}));
return {
encryptedSecret: ctx.secrets.encrypt(secret),
codeHash: null as string | null,
forScreen: { method: 'totp', secret, otpauthUrl: otpauthUrl(secret, a.email, issuer.shortName || issuer.name || 'Church') },
};
}
const sent = await sendCode(ctx, a, method as 'email' | 'whatsapp', 'setup');
return { encryptedSecret: null as string | null, codeHash: sent.codeHash, forScreen: { method, sentTo: sent.sentTo } };
}
/** Confirms the first code, turns the method on and returns new recovery codes (shown once). */
export async function confirmTwoFactorSetup(
ctx: Ctx, a: Account,
s: { method: unknown; code: unknown; pendingSecret: string | null; codeHash: string | null; codeSentAt: Date | null },
req?: Request,
): Promise<string[]> {
const method = String(s.method);
if (!METHODS.has(method)) throw new TwoFactorError('Choose how you want to get your codes.', 'BAD_METHOD');
let totpSecret: string | null = null;
let totpLastStep: number | null = null;
if (method === 'totp') {
if (!s.pendingSecret) throw new TwoFactorError('Start again: scan the QR code first.', 'RESTART');
const step = matchStep(ctx.secrets.decrypt(s.pendingSecret), s.code, { now: ctx.now().getTime() });
if (step === null) throw new TwoFactorError('That code isn\'t right. Check your authenticator app\'s time is correct.');
totpSecret = s.pendingSecret;
totpLastStep = step;
} else {
const fresh = s.codeSentAt && ctx.now().getTime() - s.codeSentAt.getTime() < CODE_MINUTES * 60e3;
if (!fresh || !codeMatches(s.code, s.codeHash)) throw new TwoFactorError('That code isn\'t right, or it has expired.');
}
await ctx.db.account.update({ where: { id: a.id }, data: { twoFactorMethod: method as 'totp' | 'email' | 'whatsapp', totpSecret, totpLastStep } });
const codes = await replaceRecoveryCodes(ctx, a.id);
await loginEvent(ctx, a.id, 'two_factor_on', req, { detail: { method } });
return codes;
}
export async function replaceRecoveryCodes(ctx: Ctx, accountId: string): Promise<string[]> {
const { codes, hashes } = newRecoveryCodes();
await ctx.db.recoveryCode.deleteMany({ where: { accountId } });
for (const codeHash of hashes) await ctx.db.recoveryCode.create({ data: { accountId, codeHash, createdAt: ctx.now() } });
return codes;
}
export async function turnOff(ctx: Ctx, accountId: string) {
await ctx.db.account.update({ where: { id: accountId }, data: { twoFactorMethod: null, totpSecret: null, totpLastStep: null } });
await ctx.db.recoveryCode.deleteMany({ where: { accountId } });
}
export async function recoveryCodesLeft(ctx: Ctx, accountId: string): Promise<number> {
return ctx.db.recoveryCode.count({ where: { accountId, usedAt: null } });
}