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,246 @@
|
||||
/**
|
||||
* 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');
|
||||
pending = 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 } };
|
||||
}
|
||||
@@ -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