Files
crosscode-platform/apps/events/backend/src/accounts/signin.ts
T
joshuaandClaude Opus 5.5 63d36c3ecf Events 3.0: auto-connect, demo people in Accounts, e2e; import.finish checks the subs
- contracts 1.8.0 / Accounts 1.1.0: import.finish lists the subs the product
  relies on; Accounts checks each is held, not deleted and known to it (the
  count+hash failed a second move after Undo once someone had joined
  through Accounts).
- Events: connects to the church's Accounts once the Hub lists it;
  moveNewPeople (demo data, people added after the move); set-demo moves
  demo people; e2e/sign-in-accounts.spec.ts with Accounts in memory and an
  e2e-only /api rewrite. test:accounts 14/14; Jest auto-connect tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 14:28:54 +02:00

283 lines
15 KiB
TypeScript

/**
* Signing in through the church's Accounts (3.0.0, docs/EVENTS-3.0-PLAN.md §3), under /api:
*
* GET /auth/signin?returnTo=…[&signup=1][&mfa=1] start: PKCE + state, a pending cookie, off to Accounts
* GET /auth/callback back from Accounts: find or link the user, then
* /auth/complete#<one-time code>
* POST /auth/handoff { code } the page swaps the code for Events' own token
* POST /auth/signout ends Events' sessions; answers Accounts' sign-out address
* POST /auth/backchannel-logout Accounts: this person signed out somewhere
* POST /accounts/v1/events Accounts: user.updated / user.export / user.deleted
*
* Events keeps its own session (the 30-day token with `tokenVersion`), so the rest of the API is
* unchanged; only how a token is obtained changes. The token carries `asi` (this sign-in's row) and
* `mfa` (whether Accounts asked for a second step), which `protect` checks for staff roles.
*/
import crypto from 'node:crypto';
import express, { type Request, type Response } from 'express';
import { ACCOUNTS_CALL_PATH, OIDC_CLIENT_PATHS, safeReturnPath, type IdentityClaims } from '@crosscode/contracts';
import { siteUrl } from '../feed/context';
import { accounts, AccountsUnavailable } from './client';
import { viaAccounts } from './mode';
import { handleAccountsCall } from './calls';
/* eslint-disable @typescript-eslint/no-require-imports -- CommonJS */
const prisma = require('../config/db');
const { generateToken } = require('../config/auth') as { generateToken(id: string, role: string, v: number, extra?: object): string };
const { encrypt, decrypt } = require('../utils/encryption') as { encrypt(v: string): string; decrypt(v: string): string };
const { requiresTwoFactor } = require('../utils/twoFactor') as { requiresTwoFactor(u: { role: string }): boolean };
const { logSecurityEvent } = require('../utils/securityEvents') as { logSecurityEvent(e: object): Promise<void> };
const { getClientIp } = require('../utils/requestUtils') as { getClientIp(req: unknown): string | null };
/* eslint-enable @typescript-eslint/no-require-imports */
const PENDING_COOKIE = 'ev_signin';
const MFA_COOKIE = 'ev_signin_mfa';
const COOKIE_PATH = '/api/auth';
const PENDING_MINUTES = 10;
const HANDOFF_SECONDS = 60;
const hash = (s: string) => crypto.createHash('sha256').update(s).digest('hex');
function cookies(req: Request): Record<string, string> {
const out: Record<string, string> = {};
for (const part of String(req.headers.cookie || '').split(';')) {
const i = part.indexOf('=');
if (i > 0) out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());
}
return out;
}
const cookieOptions = () => ({ httpOnly: true, sameSite: 'lax' as const, secure: process.env.NODE_ENV === 'production', path: COOKIE_PATH });
/** A page of this site (absolute: in development the API and the pages are on different ports). */
async function page(path: string): Promise<string> {
return `${(await siteUrl()).replace(/\/+$/, '')}${path}`;
}
/** Where a problem page sends people: a short reason and "Try again" with the same return path. */
const problem = async (res: Response, code: string, returnTo = '/') =>
res.redirect(303, await page(`/auth/problem?code=${encodeURIComponent(code)}&returnTo=${encodeURIComponent(safeReturnPath(returnTo))}`));
/** A placeholder for `User.password` (required by the schema): never a valid hash, so never a password. */
const NO_PASSWORD = () => `!accounts:${crypto.randomBytes(12).toString('hex')}`;
type EventsUser = { id: string; name: string; email: string; role: string; tokenVersion: number; isActive: boolean; accountId: string | null; phoneNumber: string | null };
const USER_SELECT = { id: true, name: true, email: true, role: true, tokenVersion: true, isActive: true, accountId: true, phoneNumber: true } as const;
const isGuestEmail = (e: string) => /@(guest\.local|deleted\.invalid|deleted\.local)$/.test(e);
/**
* The Events user for an Accounts sign-in (§2): by `accountId`; else a user (often a guest
* record from the door) with the same **verified** email that isn't linked yet; else a new `user`.
*/
export async function userForClaims(claims: IdentityClaims): Promise<{ user: EventsUser | null; problem?: string; linked?: boolean; created?: boolean }> {
const byAccount = await prisma.user.findUnique({ where: { accountId: claims.sub }, select: USER_SELECT });
if (byAccount) return { user: byAccount };
const email = claims.email.toLowerCase();
const byEmail = await prisma.user.findFirst({ where: { email: { equals: email, mode: 'insensitive' } }, select: USER_SELECT });
if (byEmail) {
if (byEmail.accountId) return { user: null, problem: 'EMAIL_IN_USE' };
if (!claims.email_verified) return { user: null, problem: 'EMAIL_NOT_VERIFIED' };
const linked = await prisma.user.update({ where: { id: byEmail.id }, data: { accountId: claims.sub }, select: USER_SELECT });
return { user: linked, linked: true };
}
// New to Events. Its id is the sub when that's free, as for everyone moved in.
const taken = await prisma.user.findUnique({ where: { id: claims.sub }, select: { id: true } });
const created = await prisma.user.create({
data: {
...(taken ? {} : { id: claims.sub }),
accountId: claims.sub,
name: claims.name,
email,
password: NO_PASSWORD(),
role: 'user',
isActive: true,
tokenVersion: 0,
newsEmail: claims.news_consent.email,
newsWhatsApp: claims.news_consent.whatsapp,
newsAskedAt: new Date(),
// Accounts' notice versions are Events' + 1 (its built-in notice is 1, Events' is 0).
noticeVersionAccepted: Math.max(0, claims.privacy_notice_version - 1),
},
select: USER_SELECT,
});
return { user: created, created: true };
}
/** Keeps Events' copy of the profile (for lists and messages) as Accounts has it. */
export async function updateLocalCopy(userId: string, profile: Pick<IdentityClaims, 'name' | 'email' | 'phone_number' | 'news_consent'> & { privacy_notice_version?: number; two_factor?: IdentityClaims['two_factor'] }) {
const data: Record<string, unknown> = {
name: profile.name,
// The 2FA method, for admins' list of staff (2.3.0); Accounts' `totp` is Events' `authenticator`.
...(profile.two_factor !== undefined ? { twoFactorEnabled: profile.two_factor !== null, twoFactorMethod: profile.two_factor === 'totp' ? 'authenticator' : profile.two_factor } : {}),
newsEmail: profile.news_consent.email,
newsWhatsApp: profile.news_consent.whatsapp,
...(profile.privacy_notice_version ? { noticeVersionAccepted: Math.max(0, profile.privacy_notice_version - 1) } : {}),
};
const email = profile.email.toLowerCase();
const sameEmail = await prisma.user.findFirst({ where: { email: { equals: email, mode: 'insensitive' }, NOT: { id: userId } }, select: { id: true } });
if (!sameEmail && !isGuestEmail(email)) data.email = email;
if (profile.phone_number) {
const samePhone = await prisma.user.findFirst({ where: { phoneNumber: profile.phone_number, NOT: { id: userId } }, select: { id: true } });
if (!samePhone) data.phoneNumber = profile.phone_number;
} else {
data.phoneNumber = null;
}
await prisma.user.update({ where: { id: userId }, data });
}
async function startSignIn(req: Request, res: Response) {
const returnTo = safeReturnPath(req.query.returnTo);
if (!(await viaAccounts())) return res.redirect(303, await page(`/login?redirect=${encodeURIComponent(returnTo)}&local=1`));
try {
const auth = await accounts();
const requireTwoFactor = req.query.mfa === '1';
const { url, cookie } = await auth.startSignIn(returnTo, {
requireTwoFactor,
signUp: req.query.signup === '1',
...(typeof req.query.email === 'string' && req.query.email.length < 200 ? { loginHint: req.query.email } : {}),
});
res.cookie(PENDING_COOKIE, cookie, { ...cookieOptions(), maxAge: PENDING_MINUTES * 60e3 });
if (requireTwoFactor) res.cookie(MFA_COOKIE, '1', { ...cookieOptions(), maxAge: PENDING_MINUTES * 60e3 });
else res.clearCookie(MFA_COOKIE, cookieOptions());
return res.redirect(303, url);
} catch (e) {
console.warn('[accounts] sign-in could not start:', (e as Error).message);
return problem(res, e instanceof AccountsUnavailable ? 'ACCOUNTS_UNAVAILABLE' : 'START_FAILED', returnTo);
}
}
async function callback(req: Request, res: Response) {
const jar = cookies(req);
const askedMfa = jar[MFA_COOKIE] === '1';
res.clearCookie(PENDING_COOKIE, cookieOptions());
res.clearCookie(MFA_COOKIE, cookieOptions());
// Cancelled at Accounts: back to the home page, signed out.
if (req.query.error === 'access_denied') return res.redirect(303, await page('/'));
let auth;
try {
auth = await accounts();
} catch {
return problem(res, 'ACCOUNTS_UNAVAILABLE');
}
let signed;
try {
// The address Accounts sent the browser to, as it registered it (never the backend's own port).
signed = await auth.finishSignIn(`${(await siteUrl()).replace(/\/+$/, '')}${req.originalUrl}`, jar[PENDING_COOKIE]);
} catch (e) {
const code = (e as { code?: string }).code;
console.warn('[accounts] sign-in could not finish:', (e as Error).message);
return problem(res, code === 'NO_PENDING' ? 'EXPIRED' : 'FINISH_FAILED');
}
const { claims, returnTo, idToken } = signed;
const found = await userForClaims(claims);
if (!found.user) return problem(res, found.problem ?? 'NO_USER', returnTo);
const user = found.user;
if (!user.isActive) return problem(res, 'EVENTS_OFF', returnTo);
// Staff roles need a second step (§3): ask Accounts for it once; a second miss is a problem.
const mfa = claims.amr.includes('mfa');
if (requiresTwoFactor(user) && !mfa) {
if (askedMfa) return problem(res, 'MFA_REQUIRED', returnTo);
return res.redirect(303, `/api/auth/signin?mfa=1&returnTo=${encodeURIComponent(returnTo)}`);
}
await updateLocalCopy(user.id, claims).catch((e: Error) => console.warn('[accounts] profile copy:', e.message));
await prisma.user.update({ where: { id: user.id }, data: { lastLoginAt: new Date(), inactivityWarnedAt: null } }).catch(() => {});
logSecurityEvent({ userId: user.id, type: 'login', ip: getClientIp(req), userAgent: req.headers['user-agent'] }).catch(() => {});
const code = crypto.randomBytes(32).toString('base64url');
const sid = (claims as unknown as { sid?: string }).sid ?? null;
await prisma.accountsSignIn.create({
data: { userId: user.id, codeHash: hash(code), codeUsedAt: null, codeExpires: new Date(Date.now() + HANDOFF_SECONDS * 1000), returnTo, idToken: encrypt(idToken), sid, mfa },
});
return res.redirect(303, await page(`/auth/complete#${code}`));
}
async function handoff(req: Request, res: Response) {
const code = typeof req.body?.code === 'string' ? req.body.code : '';
const row = code ? await prisma.accountsSignIn.findUnique({ where: { codeHash: hash(code) } }) : null;
if (!row || row.codeUsedAt || !row.codeExpires || row.codeExpires < new Date()) {
return res.status(400).json({ error: { code: 'EXPIRED', message: 'This sign-in has expired. Please sign in again.' } });
}
// Single use, whatever happens next.
const used = await prisma.accountsSignIn.updateMany({ where: { id: row.id, codeUsedAt: null }, data: { codeUsedAt: new Date(), codeHash: null } });
if (!used.count) return res.status(400).json({ error: { code: 'EXPIRED', message: 'This sign-in has expired. Please sign in again.' } });
const user = await prisma.user.findUnique({ where: { id: row.userId }, select: USER_SELECT });
if (!user || !user.isActive) return res.status(401).json({ error: { code: 'UNAUTHENTICATED', message: 'Please sign in again.' } });
return res.json({
data: {
status: 'signed_in',
token: generateToken(user.id, user.role, user.tokenVersion, { asi: row.id, mfa: row.mfa }),
user: { id: user.id, name: user.name, email: user.email, role: user.role },
newsPromptPending: false,
noticePromptPending: false,
returnTo: safeReturnPath(row.returnTo),
},
});
}
/** Ends this person's Events sessions (every token they hold stops working at the next request). */
export async function endEventsSessions(userId: string) {
await prisma.user.update({ where: { id: userId }, data: { tokenVersion: { increment: 1 } } });
}
async function signOut(req: Request, res: Response) {
// `protect` ran: req.user is the person; the token's `asi` finds the ID token for Accounts.
const user = (req as unknown as { user?: { id: string } }).user;
const asi = (req as unknown as { tokenClaims?: { asi?: string } }).tokenClaims?.asi;
if (!user) return res.status(401).json({ error: { code: 'UNAUTHENTICATED', message: 'Not signed in.' } });
await endEventsSessions(user.id);
let url: string | null = null;
if (await viaAccounts()) {
try {
const row = asi ? await prisma.accountsSignIn.findUnique({ where: { id: asi } }) : null;
const idToken = row?.idToken ? (() => { try { return decrypt(row.idToken); } catch { return undefined; } })() : undefined;
url = (await accounts()).signOutUrl(idToken);
} catch (e) {
console.warn('[accounts] sign-out address:', (e as Error).message);
}
}
return res.json({ data: { signedOut: true, url } });
}
async function backchannelLogout(req: Request, res: Response) {
try {
const { sub } = await (await accounts()).verifyLogoutToken(String(req.body?.logout_token ?? ''));
const user = await prisma.user.findUnique({ where: { accountId: sub }, select: { id: true } });
if (user) await endEventsSessions(user.id);
return res.status(200).end();
} catch (e) {
console.warn('[accounts] back-channel logout refused:', (e as Error).message);
return res.status(400).json({ error: 'invalid_request' });
}
}
async function accountsCall(req: Request, res: Response) {
try {
const raw = Buffer.isBuffer(req.body) ? req.body : Buffer.from('');
const call = (await accounts()).verifyAccountsCall(raw, req.headers as Record<string, string | string[] | undefined>);
return res.json(await handleAccountsCall(call));
} catch (e) {
const err = e as { code?: string; message: string; status?: number };
const status = err.code === 'BAD_SIGNATURE' || err.code === 'STALE_REQUEST' ? 401 : err.code === 'INVALID_REQUEST' ? 400 : err.status ?? 500;
if (status >= 500) console.warn('[accounts] call failed:', err.message);
return res.status(status).json({ message: err.message, code: err.code ?? 'SERVER_ERROR' });
}
}
/** Mounted at /api before express.json (the Accounts calls need the exact bytes). */
export function accountsRouter(protect: express.RequestHandler) {
const r = express.Router();
const strip = (p: string) => p.replace(/^\/api/, '');
r.get('/auth/signin', startSignIn);
r.get(strip(OIDC_CLIENT_PATHS.callback), callback);
r.post('/auth/handoff', express.json({ limit: '4kb' }), handoff);
r.post('/auth/signout', express.json({ limit: '4kb' }), protect, signOut);
r.post(strip(OIDC_CLIENT_PATHS.backchannelLogout), express.urlencoded({ extended: false, limit: '16kb' }), backchannelLogout);
r.post(strip(ACCOUNTS_CALL_PATH), express.raw({ type: () => true, limit: '256kb' }), accountsCall);
return r;
}