Accounts 1.9.0 (one migration): - messaging.get (sealed settings) and the messaging.changed hint to products that asked, on admin or product changes - the WhatsApp opt-out for every product: whatsapp.optout, Accounts' own WAWP webhook, WhatsAppOptOut kept per number, whatsapp_opted_out in user.updated, no WhatsApp from Accounts to an opted-out person, "Turn WhatsApp back on" - demo scenarios: npm run demo -- --profile <scenario> --force replaces the church profile (with an SVG logo and icon at /api/demo-assets/) and the demo people, ids kept across loads @crosscode/demo 1.0.0 (new): the eight scenarios' churches, people and logos. crosscode script: crosscode demo <church> accounts, --scenario on every demo, Accounts installs and builds packages/demo. Checked on PostgreSQL 18: migrations, scenario loads, opt-out, npm run demo. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
244 lines
14 KiB
TypeScript
244 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';
|
|
import { applyKnownOptOut, optBackIn } from '../accounts/whatsapp.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 },
|
|
// 1.9.0: replied STOP to the church's WhatsApp number; turned back on here.
|
|
whatsappOptedOut: a.whatsappOptedOut, 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 }),
|
|
},
|
|
});
|
|
// 1.9.0: a number that replied STOP starts opted out (which tells the products itself).
|
|
if (!(phone !== s.account.phone && (await applyKnownOptOut(ctx, s.account.id)))) 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 && !s.account.whatsappOptedOut }, 'account_page');
|
|
if (changed) await profileChanged(ctx, s.account.id);
|
|
return view(s);
|
|
}));
|
|
|
|
// 1.9.0: WhatsApp back on after a STOP (every product may send it again; news stays off until chosen).
|
|
r.post('/me/whatsapp-on', handle(async (req, res) => {
|
|
const s = await signedIn(req, res);
|
|
await optBackIn(ctx, s.account);
|
|
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;
|
|
}
|