/** * "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; 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 }; }