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:
2026-11-18 13:33:49 +02:00
co-authored by Claude Opus 5.5
parent 45c6539bf1
commit 069b66fd30
51 changed files with 4863 additions and 9 deletions
@@ -0,0 +1,112 @@
/**
* "Delete my account" (docs/ACCOUNTS-1.0-PLAN.md §6, as Cross Events): the account is deactivated
* and signed out everywhere at once; an admin approves; then every linked product gets
* `user.deleted`. A product that answers `deferred` (e.g. an open registration for an upcoming
* event) is asked again after its `retryAfter`. Once every product has answered `deleted`, the
* account is anonymised.
*/
import { IDENTITY_SCHEMA, userDeletedReplySchema } from '@crosscode/contracts';
import type { Request } from 'express';
import type Provider from 'oidc-provider';
import type { Ctx } from '../context.js';
import { audit, clientIp, loginEvent } from '../lib/audit.js';
import { onReply, queueCall } from '../links/deliveries.js';
import { signOutEverywhere } from '../oidc/sessions.js';
type ProductState = { status: 'pending' | 'deleted' | 'deferred'; reason?: string; retryAfter?: string; product?: string };
type States = Record<string, ProductState>;
export async function requestDeletion(ctx: Ctx, provider: Provider, accountId: string, req?: Request) {
const open = await ctx.db.deletionRequest.findFirst({ where: { accountId, status: { in: ['waiting_approval', 'approved'] } } });
await ctx.db.account.update({ where: { id: accountId }, data: { status: 'deactivated', deactivatedAt: ctx.now() } });
await signOutEverywhere(ctx, provider, accountId);
await loginEvent(ctx, accountId, 'signed_out_everywhere', req, { detail: { reason: 'deletion_requested' } });
return open ?? ctx.db.deletionRequest.create({ data: { accountId, requestedAt: ctx.now() } });
}
export async function cancelDeletion(ctx: Ctx, requestId: string, actor: { id: string; role: string }, req?: Request) {
const r = await ctx.db.deletionRequest.findUnique({ where: { id: requestId } });
if (!r || r.status !== 'waiting_approval') return null;
await ctx.db.deletionRequest.update({ where: { id: r.id }, data: { status: 'cancelled', completedAt: ctx.now() } });
await ctx.db.account.update({ where: { id: r.accountId }, data: { status: 'active', deactivatedAt: null } });
await audit(ctx, { actorId: actor.id, actorRole: actor.role, action: 'deletion_cancelled', targetType: 'account', targetId: r.accountId, ip: clientIp(req) });
return r;
}
export async function approveDeletion(ctx: Ctx, requestId: string, actor: { id: string; role: string }, req?: Request) {
const r = await ctx.db.deletionRequest.findUnique({ where: { id: requestId } });
if (!r || r.status !== 'waiting_approval') return null;
const links = await ctx.db.productLink.findMany();
const states: States = Object.fromEntries(links.map((l) => [l.installId, { status: 'pending', product: l.product }]));
await ctx.db.deletionRequest.update({ where: { id: r.id }, data: { status: 'approved', approvedAt: ctx.now(), approvedById: actor.id, products: states as never } });
await audit(ctx, { actorId: actor.id, actorRole: actor.role, action: 'deletion_approved', targetType: 'account', targetId: r.accountId, ip: clientIp(req) });
await askProducts(ctx, r.id, r.accountId, links.map((l) => l.installId));
await finishIfDone(ctx, r.id);
return r;
}
async function askProducts(ctx: Ctx, requestId: string, accountId: string, linkIds: string[]) {
if (!linkIds.length) return;
await queueCall(ctx, 'user.deleted', (callId) => ({ schema: IDENTITY_SCHEMA, type: 'user.deleted', callId, occurredAt: ctx.now().toISOString(), sub: accountId, approvedAt: ctx.now().toISOString(), requestId }), { linkIds });
}
onReply('user.deleted', async (ctx, delivery, reply) => {
const body = delivery.body as { requestId?: string };
if (!body.requestId) return;
const r = await ctx.db.deletionRequest.findUnique({ where: { id: body.requestId } });
if (!r || r.status !== 'approved') return;
const parsed = userDeletedReplySchema.safeParse(reply);
const states = { ...(r.products as States) };
const prev = states[delivery.linkId] ?? { status: 'pending' };
states[delivery.linkId] = !parsed.success
? { ...prev, status: 'deferred', reason: 'The product answered in a way Accounts doesn\'t understand; asking again tomorrow.', retryAfter: new Date(ctx.now().getTime() + 24 * 3600e3).toISOString() }
: parsed.data.status === 'deleted'
? { ...prev, status: 'deleted' }
: { ...prev, status: 'deferred', reason: parsed.data.reason, retryAfter: parsed.data.retryAfter };
await ctx.db.deletionRequest.update({ where: { id: r.id }, data: { products: states as never } });
await finishIfDone(ctx, r.id);
});
/** Anonymises the account once every product has deleted its part. */
export async function finishIfDone(ctx: Ctx, requestId: string) {
const r = await ctx.db.deletionRequest.findUnique({ where: { id: requestId } });
if (!r || r.status !== 'approved') return false;
const states = r.products as States;
// A product disconnected since has nothing left to delete here.
const linked = new Set((await ctx.db.productLink.findMany({ select: { installId: true } })).map((l) => l.installId));
if (Object.entries(states).some(([id, s]) => linked.has(id) && s.status !== 'deleted')) return false;
await anonymise(ctx, r.accountId);
await ctx.db.deletionRequest.update({ where: { id: r.id }, data: { status: 'done', completedAt: ctx.now() } });
return true;
}
export async function anonymise(ctx: Ctx, accountId: string) {
await ctx.db.recoveryCode.deleteMany({ where: { accountId } });
await ctx.db.emailToken.deleteMany({ where: { accountId } });
await ctx.db.account.update({
where: { id: accountId },
data: {
name: 'Deleted account', givenName: null, familyName: null, email: `deleted-${accountId}@deleted.invalid`, emailVerified: false,
phone: null, phoneVerified: false, passwordHash: null, twoFactorMethod: null, totpSecret: null, totpLastStep: null,
newsEmail: false, newsWhatsApp: false, status: 'deleted', anonymisedAt: ctx.now(),
},
});
// Sign-in history held IP addresses and devices: gone with the person.
await ctx.db.loginEvent.deleteMany({ where: { accountId } });
}
/** The `deletions` job: ask products that deferred again once their `retryAfter` has passed. */
export async function runDeletionJob(ctx: Ctx) {
const open = await ctx.db.deletionRequest.findMany({ where: { status: 'approved' } });
let asked = 0;
for (const r of open) {
const states = { ...(r.products as States) };
const due = Object.entries(states).filter(([, s]) => s.status === 'deferred' && s.retryAfter && new Date(s.retryAfter) <= ctx.now()).map(([id]) => id);
if (!due.length) continue;
for (const id of due) states[id] = { ...states[id]!, status: 'pending' };
await ctx.db.deletionRequest.update({ where: { id: r.id }, data: { products: states as never } });
await askProducts(ctx, r.id, r.accountId, due);
asked += due.length;
}
return { asked };
}
@@ -0,0 +1,88 @@
/**
* "Download my data" (docs/ACCOUNTS-1.0-PLAN.md §6): Accounts' own part, plus a `user.export` call
* to every linked product; their answers (`crosscode.identity/1` export sections) are put together
* in one file. It's ready once every product has answered, or after 24 hours with the missing ones
* listed; the person gets an email and downloads it from their account page for 7 days.
*/
import fs from 'node:fs/promises';
import path from 'node:path';
import { IDENTITY_SCHEMA, userExportReplySchema } from '@crosscode/contracts';
import type { Ctx } from '../context.js';
import { onReply, queueCall } from '../links/deliveries.js';
const WAIT_MS = 24 * 3600e3;
const KEEP_MS = 7 * 24 * 3600e3;
export const exportsDir = () => path.resolve(process.env.EXPORTS_DIR || 'exports');
type Parts = Record<string, unknown>;
async function ownPart(ctx: Ctx, accountId: string) {
const a = await ctx.db.account.findUniqueOrThrow({ where: { id: accountId } });
const [signIns, consents, notices] = await Promise.all([
ctx.db.loginEvent.findMany({ where: { accountId }, orderBy: { createdAt: 'desc' }, take: 500 }),
ctx.db.consentChange.findMany({ where: { accountId }, orderBy: { createdAt: 'asc' } }),
ctx.db.noticeAcceptance.findMany({ where: { accountId }, orderBy: { acceptedAt: 'asc' } }),
]);
return {
product: 'accounts',
sections: [
{ key: 'profile', title: 'Your account', records: [{ name: a.name, givenName: a.givenName, familyName: a.familyName, email: a.email, emailVerified: a.emailVerified, phone: a.phone, twoFactor: a.twoFactorMethod, createdAt: a.createdAt, lastSignInAt: a.lastSignInAt }] },
{ key: 'news_consent', title: 'News consent', records: consents.map((c) => ({ channel: c.channel, granted: c.granted, source: c.source, at: c.createdAt })) },
{ key: 'privacy_notice', title: 'Privacy notices accepted', records: notices.map((n) => ({ version: n.version, acceptedAt: n.acceptedAt })) },
{ key: 'sign_ins', title: 'Sign-ins and changes', records: signIns.map((e) => ({ type: e.type, at: e.createdAt, ip: e.ip, device: e.userAgent })) },
],
};
}
export async function requestExport(ctx: Ctx, accountId: string) {
const open = await ctx.db.dataExport.findFirst({ where: { accountId, status: 'collecting' } });
if (open) return open;
const exp = await ctx.db.dataExport.create({ data: { accountId, parts: { accounts: await ownPart(ctx, accountId) } as never, createdAt: ctx.now(), expiresAt: new Date(ctx.now().getTime() + WAIT_MS + KEEP_MS) } });
await queueCall(ctx, 'user.export', (callId) => ({ schema: IDENTITY_SCHEMA, type: 'user.export', callId, occurredAt: ctx.now().toISOString(), sub: accountId, exportId: exp.id }));
await finishIfComplete(ctx, exp.id);
return exp;
}
onReply('user.export', async (ctx, delivery, reply) => {
const parsed = userExportReplySchema.safeParse(reply);
const body = delivery.body as { exportId?: string };
if (!body.exportId) return;
const exp = await ctx.db.dataExport.findUnique({ where: { id: body.exportId } });
if (!exp || exp.status !== 'collecting') return;
const parts = { ...(exp.parts as Parts), [delivery.linkId]: parsed.success ? parsed.data : { error: 'The product answered in a way Accounts doesn\'t understand.' } };
await ctx.db.dataExport.update({ where: { id: exp.id }, data: { parts: parts as never } });
await finishIfComplete(ctx, exp.id);
});
/** Writes the file and emails the person once every product answered (or the wait is over). */
export async function finishIfComplete(ctx: Ctx, exportId: string, force = false) {
const exp = await ctx.db.dataExport.findUnique({ where: { id: exportId } });
if (!exp || exp.status !== 'collecting') return false;
const links = await ctx.db.productLink.findMany();
const parts = exp.parts as Parts;
const missing = links.filter((l) => !(l.installId in parts));
if (missing.length && !force) return false;
const file = path.join(exportsDir(), `${exp.id}.json`);
await fs.mkdir(exportsDir(), { recursive: true });
await fs.writeFile(file, JSON.stringify({
schema: IDENTITY_SCHEMA, exportId: exp.id, generatedAt: ctx.now().toISOString(),
parts: Object.values(parts),
missing: missing.map((l) => ({ product: l.product, url: l.url, note: 'Didn\'t answer within 24 hours. Ask the church for this part.' })),
}, null, 2), { mode: 0o600 });
await ctx.db.dataExport.update({ where: { id: exp.id }, data: { status: 'ready', file, readyAt: ctx.now(), expiresAt: new Date(ctx.now().getTime() + KEEP_MS) } });
const a = await ctx.db.account.findUnique({ where: { id: exp.accountId } });
if (a) await ctx.messenger.email({ to: a.email, subject: 'Your data is ready to download', text: `The copy of your data you asked for is ready. Download it from your account page (it's kept for 7 days):\n${ctx.config.publicUrl}/account/privacy` });
return true;
}
/** The `exports` job: finish exports that waited long enough, delete expired files. */
export async function runExportsJob(ctx: Ctx) {
const stale = await ctx.db.dataExport.findMany({ where: { status: 'collecting', createdAt: { lt: new Date(ctx.now().getTime() - WAIT_MS) } } });
for (const e of stale) await finishIfComplete(ctx, e.id, true);
const expired = await ctx.db.dataExport.findMany({ where: { status: 'ready', expiresAt: { lt: ctx.now() } } });
for (const e of expired) {
if (e.file) await fs.rm(e.file, { force: true });
await ctx.db.dataExport.update({ where: { id: e.id }, data: { status: 'expired', file: null } });
}
return { finished: stale.length, expired: expired.length };
}
@@ -0,0 +1,45 @@
/**
* The privacy notice (ROADMAP-v3 §3, as Cross Events): versions an admin publishes, and who
* accepted which. Version 1 is the built-in notice; published versions are 2, 3, … Someone who
* accepted an older version is asked again before signing in to a product (§5 of the plan).
*/
import type { Ctx } from '../context.js';
import { church } from '../church/profile.js';
export const BUILT_IN_VERSION = 1;
export async function builtInNotice(ctx: Ctx) {
const c = await church(ctx);
const contact = c.contact.email ? ` You can reach us at ${c.contact.email}.` : '';
return {
version: BUILT_IN_VERSION,
title: `How ${c.name} looks after your information`,
body: [
`${c.name} keeps your name, email address and (if you give it) phone number so you can sign in to the church's websites and apps, and so we can contact you about what you've signed up for.`,
'We only send you news if you say yes, and you can change that at any time on your account page.',
'You can download everything we hold about you, or ask us to delete your account, from your account page. We keep a record of sign-ins to protect your account.',
`We don't sell or share your information. The services that store it for us are bound to keep it safe.${contact}`,
].join('\n\n'),
publishedAt: null as Date | null,
};
}
export async function currentNotice(ctx: Ctx) {
const latest = await ctx.db.privacyNotice.findFirst({ orderBy: { version: 'desc' } });
return latest ?? (await builtInNotice(ctx));
}
export async function currentNoticeVersion(ctx: Ctx): Promise<number> {
return (await currentNotice(ctx)).version;
}
export async function accept(ctx: Ctx, accountId: string, version: number) {
await ctx.db.noticeAcceptance.create({ data: { accountId, version, acceptedAt: ctx.now() } });
await ctx.db.account.update({ where: { id: accountId }, data: { noticeVersionAccepted: version } });
}
export async function publish(ctx: Ctx, input: { title: string; body: string }, actorId: string) {
const latest = await ctx.db.privacyNotice.findFirst({ orderBy: { version: 'desc' } });
const version = Math.max(BUILT_IN_VERSION, latest?.version ?? BUILT_IN_VERSION) + 1;
return ctx.db.privacyNotice.create({ data: { version, title: input.title, body: input.body, publishedAt: ctx.now(), publishedById: actorId } });
}