Files
crosscode-platform/apps/accounts/backend/src/interaction/flow.ts
T
joshuaandClaude Opus 5.5 a3e3921b4f packages/auth-client: the product side of signing in through Accounts
Start a sign-in with the return path (state, nonce, PKCE), finish it,
sign-out address, back-channel logout tokens and Accounts' signed
user.* calls. Tested against the real provider. Root lint covers
Accounts' backend.

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

247 lines
14 KiB
TypeScript

/**
* One sign-in, step by step (docs/ACCOUNTS-1.0-PLAN.md §5). oidc-provider hands us an interaction
* (`uid`); `PendingSignIn` keeps where the person is in it, so every step — password, 2FA, setting
* up 2FA, verifying a new email, the privacy notice, the news question, and a password reset in
* between — carries on to the product they came from.
*
* password ─┬─ verify_email ─ two_factor | setup_two_factor ─ notice ─ news ─ done
* sign-up ──┘
*
* A session that's already signed in skips the password (the provider asked again only because a
* product wants 2FA, or the notice changed).
*/
import { ACR_MFA } from '@crosscode/contracts';
import type { Request } from 'express';
import type Provider from 'oidc-provider';
import type { Ctx } from '../context.js';
import type { Account, PendingSignIn } from '../generated/prisma/client.js';
import {
codeMatches, emailProblem, isLocked, maskedTarget, normaliseEmail, normalisePhone, sendCode, setNewsConsent, signInFailed, signInSucceeded, CODE_MINUTES,
} from '../accounts/service.js';
import { accessAfterTwoFactor, confirmTwoFactorSetup, startTwoFactorSetup, useRecoveryCode, verifyTotp } from '../accounts/twoFactor.js';
import { loginEvent } from '../lib/audit.js';
import { dummyHash, hashPassword, needsRehash, passwordProblem, verifyPassword } from '../lib/passwords.js';
import { accept as acceptNotice, currentNotice } from '../privacy/notice.js';
import { productName } from '../oidc/clients.js';
export type Stage = 'password' | 'verify_email' | 'two_factor' | 'setup_two_factor' | 'notice' | 'news' | 'done';
export class FlowError extends Error {
constructor(message: string, public code = 'INVALID', public status = 400, public fields?: Record<string, string>) {
super(message);
}
}
type Details = Awaited<ReturnType<Provider['interactionDetails']>>;
const PENDING_MINUTES = 60;
export function mfaRequested(details: Details): boolean {
return String(details.params.acr_values ?? '').split(' ').includes(ACR_MFA);
}
/** Where someone goes next, from what's done so far. */
export async function nextStage(ctx: Ctx, pending: PendingSignIn, details: Details): Promise<Stage> {
if (!pending.accountId) return 'password';
const a = await ctx.db.account.findUnique({ where: { id: pending.accountId } });
if (!a || a.status !== 'active') return 'password';
if (!a.emailVerified) return 'verify_email';
const adminNeeds2fa = a.role === 'admin' && (await ctx.settings.bool('two_factor_required_for_admins', true));
const wants2fa = !!a.twoFactorMethod || mfaRequested(details) || adminNeeds2fa;
if (wants2fa && !pending.amr.includes('mfa')) return a.twoFactorMethod ? 'two_factor' : 'setup_two_factor';
if (a.noticeVersionAccepted < (await currentNotice(ctx)).version) return 'notice';
if (!a.newsAskedAt) return 'news';
return 'done';
}
/** The interaction's pending sign-in, made on first sight (signed in already: the session's account and how it signed in). */
export async function pendingFor(ctx: Ctx, details: Details): Promise<PendingSignIn> {
const existing = await ctx.db.pendingSignIn.findUnique({ where: { uid: details.uid } });
if (existing && existing.expiresAt > ctx.now()) return existing;
const reasons = (details.prompt?.reasons ?? []) as string[];
// Only skip the password when the provider asked again for one of our own reasons.
const trustSession = !!details.session?.accountId && reasons.every((r) => r === 'mfa_required' || r === 'account_needs_attention');
const data = {
uid: details.uid,
accountId: trustSession ? details.session!.accountId : null,
stage: 'password',
amr: trustSession ? ((details.session as { amr?: string[] }).amr ?? ['pwd']) : [],
attempts: 0,
expiresAt: new Date(ctx.now().getTime() + PENDING_MINUTES * 60e3),
};
return ctx.db.pendingSignIn.upsert({ where: { uid: details.uid }, create: data, update: data });
}
async function save(ctx: Ctx, pending: PendingSignIn, data: Partial<PendingSignIn>): Promise<PendingSignIn> {
return ctx.db.pendingSignIn.update({ where: { uid: pending.uid }, data: data as never });
}
async function account(ctx: Ctx, pending: PendingSignIn): Promise<Account> {
const a = pending.accountId ? await ctx.db.account.findUnique({ where: { id: pending.accountId } }) : null;
if (!a || a.status !== 'active') throw new FlowError('Please sign in again.', 'RESTART', 409);
return a;
}
/** What the page for the current step needs. Sends the code when a step needs one and none was sent. */
export async function describe(ctx: Ctx, details: Details, pending: PendingSignIn) {
const stage = await nextStage(ctx, pending, details);
if (stage !== pending.stage) pending = await save(ctx, pending, { stage, codeHash: null, codeSentAt: null, attempts: 0 });
const client = details.params.client_id ? await ctx.db.productLink.findUnique({ where: { installId: String(details.params.client_id) } }) : null;
const base = {
uid: details.uid,
stage,
product: client ? productName(client.product) : 'your account',
signupEnabled: await ctx.settings.bool('signup_enabled', true),
mfaRequested: mfaRequested(details),
loginHint: typeof details.params.login_hint === 'string' ? details.params.login_hint : null,
};
if (stage === 'password' || stage === 'done') return base;
const a = await account(ctx, pending);
if ((stage === 'verify_email' || (stage === 'two_factor' && a.twoFactorMethod !== 'totp')) && !pending.codeSentAt) {
const method = stage === 'verify_email' ? 'email' : (a.twoFactorMethod as 'email' | 'whatsapp');
const sent = await sendCode(ctx, a, method, stage === 'verify_email' ? 'verify_email' : 'sign_in');
await save(ctx, pending, { codeHash: sent.codeHash, codeSentAt: ctx.now(), attempts: 0 });
}
const extra: Record<string, unknown> = { name: a.name, email: a.email };
if (stage === 'verify_email') extra.sentTo = maskedTarget(a, 'email');
if (stage === 'two_factor') {
extra.method = a.twoFactorMethod;
if (a.twoFactorMethod !== 'totp') extra.sentTo = maskedTarget(a, a.twoFactorMethod as 'email' | 'whatsapp');
}
if (stage === 'setup_two_factor') {
extra.methods = ['totp', 'email', ...((await ctx.messenger.whatsappReady()) && a.phone ? ['whatsapp'] : [])];
extra.why = a.role === 'admin' ? 'admin' : 'product';
}
if (stage === 'notice') {
const n = await currentNotice(ctx);
extra.notice = { version: n.version, title: n.title, body: n.body };
extra.updated = a.noticeVersionAccepted > 0;
}
return { ...base, ...extra };
}
// ─── Steps ────────────────────────────────────────────────────────────────────
const CODE_ATTEMPTS = 5;
export async function submitPassword(ctx: Ctx, pending: PendingSignIn, input: { email?: unknown; password?: unknown; remember?: unknown }, req?: Request) {
const email = normaliseEmail(input.email);
const password = String(input.password ?? '');
const a = email ? await ctx.db.account.findUnique({ where: { email } }) : null;
const generic = new FlowError('That email address and password don\'t match.', 'BAD_CREDENTIALS', 401);
if (!a || a.status !== 'active' || !a.passwordHash) {
await verifyPassword(password, await dummyHash());
throw generic;
}
if (isLocked(ctx, a)) throw new FlowError(`Too many tries. Wait ${15} minutes, or reset your password.`, 'LOCKED', 429);
if (!(await verifyPassword(password, a.passwordHash))) {
await signInFailed(ctx, a, req);
throw generic;
}
await signInSucceeded(ctx, a);
if (needsRehash(a.passwordHash)) await ctx.db.account.update({ where: { id: a.id }, data: { passwordHash: await hashPassword(password) } });
return save(ctx, pending, { accountId: a.id, amr: ['pwd'], remember: input.remember === true, stage: 'password', codeHash: null, codeSentAt: null, attempts: 0 });
}
export async function signUp(ctx: Ctx, pending: PendingSignIn, input: Record<string, unknown>) {
if (!(await ctx.settings.bool('signup_enabled', true))) throw new FlowError('New accounts are made by the church\'s office. Please ask them.', 'SIGNUP_OFF', 403);
const fields: Record<string, string> = {};
const name = String(input.name ?? '').trim().replace(/\s+/g, ' ');
const email = normaliseEmail(input.email);
const phone = input.phone ? normalisePhone(input.phone) : null;
if (name.length < 2 || name.length > 200) fields.name = 'Enter your name.';
const ep = emailProblem(email);
if (ep) fields.email = ep;
const pp = passwordProblem(input.password);
if (pp) fields.password = pp;
if (input.phone && !phone) fields.phone = 'Enter a phone number like 082 123 4567.';
if (input.acceptNotice !== true) fields.acceptNotice = 'Please read and accept the privacy notice.';
if (Object.keys(fields).length) throw new FlowError('Some details need fixing.', 'VALIDATION', 400, fields);
if (await ctx.db.account.findUnique({ where: { email } })) {
throw new FlowError('There\'s already an account with that email address. Sign in, or reset your password if you\'ve forgotten it.', 'EXISTS', 409, { email: 'Already has an account.' });
}
const notice = await currentNotice(ctx);
const parts = name.split(' ');
const a = await ctx.db.account.create({
data: {
name, givenName: parts[0] ?? null, familyName: parts.length > 1 ? parts.slice(1).join(' ') : null, email, phone,
passwordHash: await hashPassword(String(input.password)), noticeVersionAccepted: notice.version, lastSignInAt: ctx.now(),
},
});
await ctx.db.noticeAcceptance.create({ data: { accountId: a.id, version: notice.version, acceptedAt: ctx.now() } });
await setNewsConsent(ctx, a, { email: input.newsEmail === true, whatsapp: input.newsWhatsApp === true && !!phone }, 'sign_up');
await loginEvent(ctx, a.id, 'account_created');
return save(ctx, pending, { accountId: a.id, amr: ['pwd'], remember: input.remember === true, codeHash: null, codeSentAt: null, attempts: 0 });
}
async function checkCode(ctx: Ctx, pending: PendingSignIn, code: unknown) {
if (!pending.codeHash || !pending.codeSentAt || ctx.now().getTime() - pending.codeSentAt.getTime() > CODE_MINUTES * 60e3) {
throw new FlowError('That code has expired. Send a new one.', 'CODE_EXPIRED', 400);
}
if (pending.attempts >= CODE_ATTEMPTS) throw new FlowError('Too many wrong codes. Send a new one.', 'TOO_MANY', 429);
if (!codeMatches(code, pending.codeHash)) {
await save(ctx, pending, { attempts: pending.attempts + 1 });
throw new FlowError('That code isn\'t right.', 'BAD_CODE', 400);
}
}
export async function resendCode(ctx: Ctx, pending: PendingSignIn) {
if (pending.codeSentAt && ctx.now().getTime() - pending.codeSentAt.getTime() < 30e3) throw new FlowError('Wait half a minute before asking for another code.', 'TOO_SOON', 429);
return save(ctx, pending, { codeHash: null, codeSentAt: null, attempts: 0 });
}
export async function verifyEmail(ctx: Ctx, pending: PendingSignIn, code: unknown) {
await checkCode(ctx, pending, code);
await ctx.db.account.update({ where: { id: pending.accountId! }, data: { emailVerified: true } });
return save(ctx, pending, { codeHash: null, codeSentAt: null, attempts: 0 });
}
export async function twoFactor(ctx: Ctx, pending: PendingSignIn, input: { code?: unknown; recoveryCode?: unknown }, req?: Request) {
const a = await account(ctx, pending);
if (input.recoveryCode) {
if (!(await useRecoveryCode(ctx, a, input.recoveryCode, req))) throw new FlowError('That recovery code isn\'t right, or it was used already.', 'BAD_CODE', 400);
} else if (a.twoFactorMethod === 'totp') {
if (pending.attempts >= CODE_ATTEMPTS) throw new FlowError('Too many wrong codes. Wait a few minutes.', 'TOO_MANY', 429);
if (!(await verifyTotp(ctx, a, input.code))) {
await save(ctx, pending, { attempts: pending.attempts + 1 });
throw new FlowError('That code isn\'t right. Check your authenticator app\'s time is correct.', 'BAD_CODE', 400);
}
} else {
await checkCode(ctx, pending, input.code);
}
return save(ctx, pending, { amr: accessAfterTwoFactor(pending.amr), codeHash: null, codeSentAt: null, attempts: 0 });
}
export async function setupStart(ctx: Ctx, pending: PendingSignIn, method: unknown) {
const a = await account(ctx, pending);
const started = await startTwoFactorSetup(ctx, a, method);
await save(ctx, pending, { pendingTotpSecret: started.encryptedSecret, codeHash: started.codeHash, codeSentAt: started.codeHash ? ctx.now() : null, attempts: 0 });
return started.forScreen;
}
export async function setupConfirm(ctx: Ctx, pending: PendingSignIn, input: { method?: unknown; code?: unknown }, req?: Request) {
const a = await account(ctx, pending);
const recoveryCodes = await confirmTwoFactorSetup(ctx, a, { method: input.method, code: input.code, pendingSecret: pending.pendingTotpSecret, codeHash: pending.codeHash, codeSentAt: pending.codeSentAt }, req);
const next = await save(ctx, pending, { amr: accessAfterTwoFactor(pending.amr), pendingTotpSecret: null, codeHash: null, codeSentAt: null, attempts: 0 });
return { pending: next, recoveryCodes };
}
export async function notice(ctx: Ctx, pending: PendingSignIn, version: unknown) {
const current = await currentNotice(ctx);
if (Number(version) !== current.version) throw new FlowError('The notice changed while you were reading it. Please read it again.', 'STALE', 409);
await acceptNotice(ctx, pending.accountId!, current.version);
return pending;
}
export async function news(ctx: Ctx, pending: PendingSignIn, input: { email?: unknown; whatsapp?: unknown }) {
const a = await account(ctx, pending);
await setNewsConsent(ctx, a, { email: input.email === true, whatsapp: input.whatsapp === true && !!a.phone }, 'news_question');
return pending;
}
/** The result oidc-provider needs to finish the sign-in. */
export function loginResult(pending: PendingSignIn) {
const mfa = pending.amr.includes('mfa');
return { login: { accountId: pending.accountId!, amr: pending.amr, acr: mfa ? ACR_MFA : 'pwd', remember: pending.remember } };
}