Files
crosscode-platform/apps/accounts/backend/src/me/routes.ts
T
joshuaandClaude Opus 5.5 bbcafe61b9 Events 3.4.0, Accounts 1.4.0, contracts 1.12.0, agent 1.3.0: jobs from the dashboard, styled Accounts emails, .env from the Hub
- Events and Accounts: Background jobs are switched on or off and rescheduled from the admin;
  the choice is kept in the database (job_overrides), wins over the .env and applies at once.
  Accounts gets an Admin -> Background jobs page and per-job env flags, as Events.
- Accounts: every email styled as Cross Events' (church colour, logo, button, footer), same
  plain text (src/lib/emails.ts).
- Contracts 1.12.0: env-read / env-set agent jobs, envReadResultSchema, isSecretEnvName.
- crosscode script: `crosscode env <church> <product>` reads the .env (secrets hidden) and, with
  --set/--unset/--restart, changes one file, rebuilds the frontend when its file changed, reloads,
  and puts the file back if the site doesn't answer (lib/envedit.cjs, tests/envedit.bats).
- Agent 1.3.0: runs env-read and env-set.

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

233 lines
14 KiB
TypeScript

/**
* The account page's API (`/api/v2/me/…`): profile, password, 2FA, sign-ins, news consent,
* download my data, delete my account, sign out everywhere. Signed in with the Accounts session.
*/
import fs from 'node:fs/promises';
import express, { type Request, type Response } from 'express';
import type Provider from 'oidc-provider';
import type { Ctx } from '../context.js';
import { ApiError, handle, limit } from '../http.js';
import { loginEvent } from '../lib/audit.js';
import { confirmNewEmail, emailChangedNotice } from '../lib/emails.js';
import { hashPassword, passwordProblem, verifyPassword } from '../lib/passwords.js';
import { emailProblem, normaliseEmail, normalisePhone, profileChanged, setNewsConsent } from '../accounts/service.js';
import { confirmTwoFactorSetup, recoveryCodesLeft, replaceRecoveryCodes, startTwoFactorSetup, turnOff } from '../accounts/twoFactor.js';
import { currentSession, signOutEverywhere, type SignedIn } from '../oidc/sessions.js';
import { currentNotice } from '../privacy/notice.js';
import { requestExport } from '../privacy/export.js';
import { requestDeletion } from '../privacy/deletion.js';
import { hashToken, randomToken } from '../lib/crypto.js';
import { linkedProducts } from '../links/store.js';
/** 1.3.0: the quick links on the account page. Events' own sign-in, already signed in here, lands on the dashboard. */
const APP_NAMES: Record<string, string> = { events: 'Events', website: 'Website', app: 'Church app' };
const APP_BLURBS: Record<string, string> = { events: 'Your bookings, tickets and serving', website: 'The church\'s website', app: 'The church app on your phone' };
const OPEN_PATHS: Record<string, string> = { events: '/api/auth/signin?returnTo=%2Fdashboard' };
const appName = (product: string) => APP_NAMES[product] ?? product;
export function meView(a: SignedIn['account'], extra: { recoveryCodesLeft: number; noticeVersion: number }) {
return {
id: a.id, name: a.name, givenName: a.givenName, familyName: a.familyName, email: a.email, emailVerified: a.emailVerified,
phone: a.phone, role: a.role, twoFactor: a.twoFactorMethod, recoveryCodesLeft: extra.recoveryCodesLeft,
news: { email: a.newsEmail, whatsapp: a.newsWhatsApp }, noticeVersionAccepted: a.noticeVersionAccepted, noticeVersion: extra.noticeVersion,
createdAt: a.createdAt, lastSignInAt: a.lastSignInAt,
};
}
export function meRouter(ctx: Ctx, provider: Provider) {
const r = express.Router();
const signedIn = async (req: Request, res: Response) => {
const s = await currentSession(ctx, provider, req, res);
if (!s) throw new ApiError(401, 'UNAUTHENTICATED', 'Please sign in.');
return s;
};
const view = async (s: SignedIn) => {
const a = (await ctx.db.account.findUnique({ where: { id: s.account.id } }))!;
return meView(a, { recoveryCodesLeft: await recoveryCodesLeft(ctx, a.id), noticeVersion: (await currentNotice(ctx)).version });
};
const needPassword = async (s: SignedIn, password: unknown) => {
if (!(await verifyPassword(String(password ?? ''), s.account.passwordHash))) throw new ApiError(400, 'BAD_PASSWORD', 'That isn\'t your current password.', { password: 'That isn\'t your current password.' });
};
r.get('/me', handle(async (req, res) => view(await signedIn(req, res))));
// 1.3.0: the church's sites and apps that sign in here, for the account page's quick links.
r.get('/me/apps', handle(async (req, res) => {
await signedIn(req, res);
const [links, listed] = await Promise.all([ctx.db.productLink.findMany({ orderBy: { connectedAt: 'asc' } }), linkedProducts(ctx)]);
return {
items: links.map((l) => {
const url = (listed.find((x) => x.installId === l.installId)?.url ?? l.url).replace(/\/+$/, '');
return { id: l.installId, product: l.product, name: appName(l.product), description: APP_BLURBS[l.product] ?? null, url: `${url}${OPEN_PATHS[l.product] ?? '/'}` };
}),
};
}));
r.put('/me', handle(async (req, res) => {
const s = await signedIn(req, res);
const name = req.body?.name !== undefined ? String(req.body.name).trim().replace(/\s+/g, ' ') : s.account.name;
if (name.length < 2 || name.length > 200) throw new ApiError(400, 'VALIDATION', 'Enter your name.', { name: 'Enter your name.' });
const phone = req.body?.phone !== undefined ? (req.body.phone ? normalisePhone(req.body.phone) : null) : s.account.phone;
if (req.body?.phone && !phone) throw new ApiError(400, 'VALIDATION', 'Enter a phone number like 082 123 4567.', { phone: 'Enter a phone number like 082 123 4567.' });
const parts = name.split(' ');
await ctx.db.account.update({
where: { id: s.account.id },
data: {
name, givenName: req.body?.givenName ?? parts[0] ?? null, familyName: req.body?.familyName ?? (parts.length > 1 ? parts.slice(1).join(' ') : null), phone,
...(phone !== s.account.phone ? { phoneVerified: false } : {}),
// No phone, no WhatsApp news.
...(phone ? {} : { newsWhatsApp: false }),
},
});
await profileChanged(ctx, s.account.id);
return view(s);
}));
// A new email address is confirmed by a link sent to it; the old one keeps working until then.
r.post('/me/email', limit(5), handle(async (req, res) => {
const s = await signedIn(req, res);
await needPassword(s, req.body?.password);
const email = normaliseEmail(req.body?.email);
const problem = emailProblem(email);
if (problem) throw new ApiError(400, 'VALIDATION', problem, { email: problem });
if (await ctx.db.account.findUnique({ where: { email } })) throw new ApiError(409, 'EXISTS', 'Another account uses that email address.', { email: 'Another account uses that email address.' });
const token = randomToken();
await ctx.db.emailToken.create({ data: { accountId: s.account.id, purpose: `change_email:${email}`, tokenHash: hashToken(token), expiresAt: new Date(ctx.now().getTime() + 24 * 3600e3) } });
await ctx.messenger.email({ to: email, ...(await confirmNewEmail(ctx, { name: s.account.name, url: `${ctx.config.publicUrl}/account/confirm-email?token=${token}` })) });
return { sent: true };
}));
r.post('/me/email/confirm', handle(async (req, res) => {
const s = await signedIn(req, res);
const row = await ctx.db.emailToken.findUnique({ where: { tokenHash: hashToken(String(req.body?.token ?? '')) } });
if (!row || row.accountId !== s.account.id || !row.purpose.startsWith('change_email:') || row.usedAt || row.expiresAt < ctx.now()) throw new ApiError(400, 'BAD_TOKEN', 'This link has expired or was already used.');
const email = row.purpose.slice('change_email:'.length);
if (await ctx.db.account.findUnique({ where: { email } })) throw new ApiError(409, 'EXISTS', 'Another account uses that email address now.');
await ctx.db.account.update({ where: { id: s.account.id }, data: { email, emailVerified: true } });
await ctx.db.emailToken.update({ where: { id: row.id }, data: { usedAt: ctx.now() } });
await ctx.messenger.email({ to: s.account.email, ...(await emailChangedNotice(ctx, { name: s.account.name, newEmail: email })) });
await loginEvent(ctx, s.account.id, 'email_changed', req);
await profileChanged(ctx, s.account.id);
return view(s);
}));
r.post('/me/password', limit(10), handle(async (req, res) => {
const s = await signedIn(req, res);
await needPassword(s, req.body?.current);
const problem = passwordProblem(req.body?.password);
if (problem) throw new ApiError(400, 'VALIDATION', problem, { password: problem });
await ctx.db.account.update({ where: { id: s.account.id }, data: { passwordHash: await hashPassword(String(req.body.password)) } });
await loginEvent(ctx, s.account.id, 'password_changed', req);
return { changed: true };
}));
// ─── Two-factor ────────────────────────────────────────────────────────────
const setupKey = (id: string) => `me:${id}`;
r.post('/me/two-factor/setup', limit(10), handle(async (req, res) => {
const s = await signedIn(req, res);
const started = await startTwoFactorSetup(ctx, s.account, req.body?.method);
const data = { uid: setupKey(s.account.id), accountId: s.account.id, stage: 'setup', pendingTotpSecret: started.encryptedSecret, codeHash: started.codeHash, codeSentAt: started.codeHash ? ctx.now() : null, amr: [], attempts: 0, expiresAt: new Date(ctx.now().getTime() + 3600e3) };
await ctx.db.pendingSignIn.upsert({ where: { uid: data.uid }, create: data, update: data });
return started.forScreen;
}));
r.post('/me/two-factor/confirm', limit(20), handle(async (req, res) => {
const s = await signedIn(req, res);
const p = await ctx.db.pendingSignIn.findUnique({ where: { uid: setupKey(s.account.id) } });
if (!p || p.expiresAt < ctx.now()) throw new ApiError(400, 'RESTART', 'Start setting it up again.');
const recoveryCodes = await confirmTwoFactorSetup(ctx, s.account, { method: req.body?.method, code: req.body?.code, pendingSecret: p.pendingTotpSecret, codeHash: p.codeHash, codeSentAt: p.codeSentAt }, req);
await ctx.db.pendingSignIn.deleteMany({ where: { uid: p.uid } });
await profileChanged(ctx, s.account.id);
return { ...(await view(s)), recoveryCodes };
}));
r.post('/me/two-factor/off', limit(10), handle(async (req, res) => {
const s = await signedIn(req, res);
await needPassword(s, req.body?.password);
if (s.account.role === 'admin' && (await ctx.settings.bool('two_factor_required_for_admins', true))) throw new ApiError(400, 'REQUIRED', 'Admins must keep two-factor sign-in on. You can change how you get your codes instead.');
await turnOff(ctx, s.account.id);
await loginEvent(ctx, s.account.id, 'two_factor_off', req);
await profileChanged(ctx, s.account.id);
return view(s);
}));
r.post('/me/recovery-codes', limit(5), handle(async (req, res) => {
const s = await signedIn(req, res);
await needPassword(s, req.body?.password);
if (!s.account.twoFactorMethod) throw new ApiError(400, 'NO_2FA', 'Turn on two-factor sign-in first.');
const codes = await replaceRecoveryCodes(ctx, s.account.id);
await loginEvent(ctx, s.account.id, 'recovery_codes_replaced', req);
return { recoveryCodes: codes };
}));
// ─── Activity, consent, privacy ─────────────────────────────────────────────
r.get('/me/sign-ins', handle(async (req, res) => {
const s = await signedIn(req, res);
const events = await ctx.db.loginEvent.findMany({ where: { accountId: s.account.id }, orderBy: { createdAt: 'desc' }, take: 50 });
const links = await ctx.db.productLink.findMany();
const names = new Map(links.map((l) => [l.installId, l.url]));
return { items: events.map((e) => ({ type: e.type, at: e.createdAt, ip: e.ip, device: e.userAgent, site: e.clientId ? names.get(e.clientId) ?? null : null })) };
}));
r.put('/me/news', handle(async (req, res) => {
const s = await signedIn(req, res);
const changed = await setNewsConsent(ctx, s.account, { email: req.body?.email === true, whatsapp: req.body?.whatsapp === true && !!s.account.phone }, 'account_page');
if (changed) await profileChanged(ctx, s.account.id);
return view(s);
}));
r.get('/me/notice', handle(async (req, res) => {
await signedIn(req, res);
const n = await currentNotice(ctx);
return { version: n.version, title: n.title, body: n.body, publishedAt: n.publishedAt };
}));
r.post('/me/sign-out-everywhere', handle(async (req, res) => {
const s = await signedIn(req, res);
const told = await signOutEverywhere(ctx, provider, s.account.id);
await loginEvent(ctx, s.account.id, 'signed_out_everywhere', req, { detail: { productsTold: told } });
return { signedOut: true };
}));
r.get('/me/exports', handle(async (req, res) => {
const s = await signedIn(req, res);
const list = await ctx.db.dataExport.findMany({ where: { accountId: s.account.id }, orderBy: { createdAt: 'desc' }, take: 5 });
return { items: list.map((e) => ({ id: e.id, status: e.status, createdAt: e.createdAt, readyAt: e.readyAt, expiresAt: e.expiresAt })) };
}));
r.post('/me/exports', limit(3, 60), handle(async (req, res) => {
const s = await signedIn(req, res);
const e = await requestExport(ctx, s.account.id);
return { id: e.id, status: (await ctx.db.dataExport.findUnique({ where: { id: e.id } }))!.status };
}));
r.get('/me/exports/:id/download', async (req, res) => {
try {
const s = await signedIn(req, res);
const e = await ctx.db.dataExport.findUnique({ where: { id: String(req.params.id) } });
if (!e || e.accountId !== s.account.id || e.status !== 'ready' || !e.file) throw new ApiError(404, 'NOT_FOUND', 'That download isn\'t available any more.');
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Content-Disposition', `attachment; filename="my-data-${e.createdAt.toISOString().slice(0, 10)}.json"`);
res.send(await fs.readFile(e.file));
} catch (err) {
const { sendError } = await import('../http.js');
sendError(res, err);
}
});
r.post('/me/delete', limit(3, 60), handle(async (req, res) => {
const s = await signedIn(req, res);
await needPassword(s, req.body?.password);
const admins = await ctx.db.account.count({ where: { role: 'admin', status: 'active' } });
if (s.account.role === 'admin' && admins <= 1) throw new ApiError(400, 'LAST_ADMIN', 'You\'re the only admin. Make someone else an admin first.');
await requestDeletion(ctx, provider, s.account.id, req);
return { requested: true };
}));
return r;
}