/** * "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'; import { exportReadyEmail } from '../lib/emails.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; 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, ...(await exportReadyEmail(ctx, { name: a.name, url: `${ctx.config.publicUrl}/account/privacy`, days: Math.round(KEEP_MS / 86400e3) })) }); 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 }; }