Files
crosscode-platform/apps/accounts/backend/src/interaction/routes.ts
T
joshuaandClaude Opus 5.5 405b5f1b92 Accounts 1.6.0: a "New sign-in" email (and WhatsApp) after every sign-in
As Cross Events' own sign-in sends: when, the site, rough location and device, with what to do if
it wasn't them. WhatsApp too for a verified number. Admins can turn it off (signin_notices).
Fire-and-forget: never holds up or fails a sign-in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:54:03 +02:00

162 lines
9.7 KiB
TypeScript

/**
* The sign-in pages' API (`/api/v2/interaction/:uid/…`), forgot / reset password, and Accounts'
* own sign-in for the account page (`/api/self/…`, an OIDC client of itself).
*/
import crypto from 'node:crypto';
import express, { type Request, type Response } from 'express';
import type Provider from 'oidc-provider';
import { decodeState, encodeState, safeReturnPath } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { ApiError, handle, limit } from '../http.js';
import { clientIp, loginEvent } from '../lib/audit.js';
import { sendSignInNotice } from '../accounts/signInNotice.js';
import { resetPasswordEmail } from '../lib/emails.js';
import { hashToken, randomToken } from '../lib/crypto.js';
import { hashPassword, passwordProblem } from '../lib/passwords.js';
import { normaliseEmail } from '../accounts/service.js';
import { SELF_CALLBACK, SELF_CLIENT_ID } from '../oidc/clients.js';
import { issuerOf } from '../oidc/provider.js';
import * as flow from './flow.js';
import { signedInThrough } from '../links/requests.js';
const RESET_MINUTES = 60;
export function interactionRouter(ctx: Ctx, provider: Provider) {
const r = express.Router();
/** The interaction behind `uid`, from this browser's interaction cookie. */
async function load(req: Request, res: Response) {
let details;
try {
details = await provider.interactionDetails(req, res);
} catch {
throw new ApiError(410, 'EXPIRED', 'This sign-in has expired. Go back to the site you came from and sign in again.');
}
if (details.uid !== req.params.uid) throw new ApiError(410, 'EXPIRED', 'This sign-in has expired. Go back to the site you came from and sign in again.');
return { details, pending: await flow.pendingFor(ctx, details) };
}
/** After a step: the next step's page data, or the address to finish at (the product). */
async function next(req: Request, res: Response, extra: Record<string, unknown> = {}) {
const { details, pending } = await load(req, res);
const state = await flow.describe(ctx, details, pending);
if (state.stage !== 'done') return { ...state, ...extra };
const redirectTo = await provider.interactionResult(req, res, flow.loginResult(pending), { mergeWithLastSubmission: false });
const clientId = String(details.params.client_id ?? '') || null;
await loginEvent(ctx, pending.accountId, 'sign_in', req, { clientId, detail: { amr: pending.amr } });
await signedInThrough(ctx, clientId, pending.accountId);
// 1.6.0: "New sign-in" email (and WhatsApp), as Cross Events; never waited for.
if (pending.accountId) void sendSignInNotice(ctx, { accountId: pending.accountId, ip: clientIp(req), userAgent: req.get('user-agent') ?? null, clientId });
await ctx.db.pendingSignIn.deleteMany({ where: { uid: pending.uid } });
return { stage: 'done', redirectTo, ...extra };
}
const step = (fn: (req: Request, res: Response, pending: Awaited<ReturnType<typeof load>>['pending']) => Promise<Record<string, unknown> | void>) =>
handle(async (req, res) => {
const { pending } = await load(req, res);
const extra = (await fn(req, res, pending)) ?? {};
return next(req, res, extra);
});
// Where oidc-provider sends the browser (its cookie's path): on to the sign-in page.
r.get('/interaction/:uid', (req, res) => {
const uid = String(req.params.uid);
res.redirect(303, /^[A-Za-z0-9_-]{10,64}$/.test(uid) ? `/signin?uid=${uid}` : '/account');
});
// The page's state for the current step.
r.get('/interaction/:uid/state', handle(async (req, res) => next(req, res)));
r.post('/interaction/:uid/password', limit(20), step(async (req, _res, p) => { await flow.submitPassword(ctx, p, req.body ?? {}, req); }));
r.post('/interaction/:uid/signup', limit(10, 60), step(async (req, _res, p) => { await flow.signUp(ctx, p, req.body ?? {}); }));
r.post('/interaction/:uid/verify-email', limit(20), step(async (req, _res, p) => { await flow.verifyEmail(ctx, p, req.body?.code); }));
r.post('/interaction/:uid/two-factor', limit(20), step(async (req, _res, p) => {
const { recoveryCodes } = await flow.twoFactor(ctx, p, req.body ?? {}, req);
return recoveryCodes ? { recoveryCodes } : undefined;
}));
r.post('/interaction/:uid/resend', limit(10), step(async (_req, _res, p) => { await flow.resendCode(ctx, p); }));
r.post('/interaction/:uid/two-factor/setup', limit(10), handle(async (req, res) => {
const { pending } = await load(req, res);
return flow.setupStart(ctx, pending, req.body?.method);
}));
r.post('/interaction/:uid/two-factor/setup/confirm', limit(20), step(async (req, _res, p) => {
const { recoveryCodes } = await flow.setupConfirm(ctx, p, req.body ?? {}, req);
return { recoveryCodes };
}));
r.post('/interaction/:uid/notice', step(async (req, _res, p) => { await flow.notice(ctx, p, req.body?.version); }));
r.post('/interaction/:uid/news', step(async (req, _res, p) => { await flow.news(ctx, p, req.body ?? {}); }));
r.post('/interaction/:uid/cancel', handle(async (req, res) => {
await load(req, res);
const redirectTo = await provider.interactionResult(req, res, { error: 'access_denied', error_description: 'The person cancelled signing in.' }, { mergeWithLastSubmission: false });
return { stage: 'done', redirectTo };
}));
// ─── Forgot / reset password ───────────────────────────────────────────────
r.post('/password/forgot', limit(5), handle(async (req) => {
// 1.2.0: without email nobody gets a link; say so (the same answer whoever asks).
if (!(await ctx.messenger.emailReady())) throw new ApiError(503, 'EMAIL_NOT_READY', 'Password reset links can\'t be sent right now: the church\'s email isn\'t set up. Please let the church office know.');
const email = normaliseEmail(req.body?.email);
const a = email ? await ctx.db.account.findUnique({ where: { email } }) : null;
// The same answer either way, so nobody can find out who has an account (Events 1.51.17).
if (a && a.status === 'active') {
const token = randomToken();
const uid = typeof req.body?.uid === 'string' && /^[A-Za-z0-9_-]{10,64}$/.test(req.body.uid) ? req.body.uid : null;
await ctx.db.emailToken.create({ data: { accountId: a.id, purpose: 'reset_password', tokenHash: hashToken(token), interactionUid: uid, expiresAt: new Date(ctx.now().getTime() + RESET_MINUTES * 60e3) } });
await ctx.messenger.email({ to: a.email, ...(await resetPasswordEmail(ctx, { name: a.name, url: `${ctx.config.publicUrl}/reset?token=${token}`, minutes: RESET_MINUTES })) });
}
return { sent: true };
}));
r.post('/password/reset', limit(10), handle(async (req) => {
const token = String(req.body?.token ?? '');
const row = token ? await ctx.db.emailToken.findUnique({ where: { tokenHash: hashToken(token) } }) : null;
if (!row || row.purpose !== 'reset_password' || row.usedAt || row.expiresAt < ctx.now()) throw new ApiError(400, 'BAD_TOKEN', 'This link has expired or was already used. Ask for a new one.');
const problem = passwordProblem(req.body?.password);
if (problem) throw new ApiError(400, 'VALIDATION', problem, { password: problem });
// Setting a password from an emailed link also proves the address.
await ctx.db.account.update({ where: { id: row.accountId }, data: { passwordHash: await hashPassword(String(req.body.password)), failedSignIns: 0, lockedUntil: null, emailVerified: true } });
await ctx.db.emailToken.update({ where: { id: row.id }, data: { usedAt: ctx.now() } });
await ctx.db.emailToken.deleteMany({ where: { accountId: row.accountId, purpose: 'reset_password', usedAt: null } });
await loginEvent(ctx, row.accountId, 'password_reset', req);
// Back to the sign-in it started from, if this browser still has it (§5).
// A "set your password" link a product asked for (people.ensure) ends on that product, which signs them in.
return { reset: true, uid: row.interactionUid, returnUrl: row.returnUrl ?? null };
}));
return r;
}
/**
* The account page signs in like any product: `/api/self/signin?returnTo=/account` starts an
* authorization request for `accounts-self`; the callback only needs the session the sign-in made.
*/
export function selfRouter(ctx: Ctx) {
const r = express.Router();
const callback = `${ctx.config.publicUrl}${SELF_CALLBACK}`;
r.get('/signin', (req, res) => {
const nonce = crypto.randomBytes(16).toString('base64url');
const verifier = crypto.randomBytes(32).toString('base64url');
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url');
const state = encodeState({ nonce, returnTo: safeReturnPath(req.query.returnTo, '/account') });
res.cookie('acc_self', nonce, { httpOnly: true, sameSite: 'lax', secure: ctx.config.production, maxAge: 3600e3, path: '/api/self' });
const url = new URL(`${issuerOf(ctx)}/auth`);
url.search = new URLSearchParams({
client_id: SELF_CLIENT_ID, response_type: 'code', scope: 'openid', redirect_uri: callback, state,
code_challenge: challenge, code_challenge_method: 'S256', nonce,
...(req.query.prompt === 'login' ? { prompt: 'login' } : {}),
...(req.query.acr === 'mfa' ? { acr_values: 'mfa' } : {}),
}).toString();
res.redirect(url.toString());
});
r.get('/callback', (req, res) => {
const state = decodeState(req.query.state);
const cookies = Object.fromEntries(String(req.get('cookie') || '').split(';').map((c) => c.trim().split('=')).filter((p) => p.length === 2)) as Record<string, string>;
res.clearCookie('acc_self', { path: '/api/self' });
if (!state || state.nonce !== cookies.acc_self || req.query.error) return res.redirect('/account');
return res.redirect(safeReturnPath(state.returnTo, '/account'));
});
return r;
}