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>
This commit is contained in:
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* 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 { loginEvent } from '../lib/audit.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';
|
||||
|
||||
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 });
|
||||
await loginEvent(ctx, pending.accountId, 'sign_in', req, { clientId: String(details.params.client_id ?? '') || null, detail: { amr: pending.amr } });
|
||||
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);
|
||||
});
|
||||
|
||||
r.get('/interaction/:uid', 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) => { await flow.twoFactor(ctx, p, req.body ?? {}, req); }));
|
||||
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) => {
|
||||
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,
|
||||
subject: 'Reset your password',
|
||||
text: `Someone (we hope you) asked to reset the password for your account.\n\nChoose a new password here (the link works for ${RESET_MINUTES} minutes):\n${ctx.config.publicUrl}/reset?token=${token}\n\nIf you didn't ask, you can ignore this email: your password stays the same.`,
|
||||
});
|
||||
}
|
||||
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 });
|
||||
await ctx.db.account.update({ where: { id: row.accountId }, data: { passwordHash: await hashPassword(String(req.body.password)), failedSignIns: 0, lockedUntil: null } });
|
||||
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).
|
||||
return { reset: true, uid: row.interactionUid };
|
||||
}));
|
||||
|
||||
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;
|
||||
}
|
||||
Reference in New Issue
Block a user