|
| 1 | +/** |
| 2 | + * Self-service account actions for data-protection (GDPR): export a copy of your data, and |
| 3 | + * permanently delete your account. Both are scoped strictly to the requesting user. |
| 4 | + */ |
| 5 | +import type { FastifyPluginAsync } from 'fastify'; |
| 6 | +import { passwordConfirmSchema } from '@opencoperlock/shared'; |
| 7 | +import { prisma } from '../db.js'; |
| 8 | +import { parseOr400 } from '../lib/validate.js'; |
| 9 | +import { verifyPassword } from '../services/password.js'; |
| 10 | +import { remainingRecoveryCodes } from '../services/recovery.js'; |
| 11 | +import { toPublicFile, toPublicFolder, toPublicShare, toPublicUser } from '../lib/serialize.js'; |
| 12 | +import { clearSessionCookie } from '../lib/cookies.js'; |
| 13 | +import { audit } from '../services/audit.js'; |
| 14 | + |
| 15 | +export const accountRoutes: FastifyPluginAsync = async (app) => { |
| 16 | + app.addHook('preHandler', app.requireAuth); |
| 17 | + const secureCookies = app.ctx.env.NODE_ENV === 'production'; |
| 18 | + |
| 19 | + // GET /account/export — a JSON copy of the user's data (metadata, not file contents). |
| 20 | + app.get('/export', async (req, reply) => { |
| 21 | + const userId = req.user!.id; |
| 22 | + const [user, folders, files, shares, sessions, logs] = await Promise.all([ |
| 23 | + prisma.user.findUniqueOrThrow({ where: { id: userId } }), |
| 24 | + prisma.folder.findMany({ where: { ownerId: userId } }), |
| 25 | + prisma.fileObject.findMany({ where: { ownerId: userId } }), |
| 26 | + prisma.shareLink.findMany({ where: { ownerId: userId } }), |
| 27 | + prisma.session.findMany({ |
| 28 | + where: { userId }, |
| 29 | + select: { ip: true, userAgent: true, lastSeenAt: true, createdAt: true }, |
| 30 | + }), |
| 31 | + prisma.auditLog.findMany({ where: { actorId: userId }, orderBy: { createdAt: 'desc' }, take: 1000 }), |
| 32 | + ]); |
| 33 | + |
| 34 | + const data = { |
| 35 | + exportedAt: new Date().toISOString(), |
| 36 | + user: { ...toPublicUser(user), twoFactorEnabled: user.totpEnabled }, |
| 37 | + recoveryCodesRemaining: await remainingRecoveryCodes(userId), |
| 38 | + folders: folders.map(toPublicFolder), |
| 39 | + files: files.map(toPublicFile), |
| 40 | + shares: shares.map((s) => toPublicShare(s, '')), |
| 41 | + sessions: sessions.map((s) => ({ |
| 42 | + ip: s.ip, |
| 43 | + userAgent: s.userAgent, |
| 44 | + lastSeenAt: s.lastSeenAt.toISOString(), |
| 45 | + createdAt: s.createdAt.toISOString(), |
| 46 | + })), |
| 47 | + activity: logs.map((l) => ({ action: l.action, target: l.target, ip: l.ip, at: l.createdAt.toISOString() })), |
| 48 | + }; |
| 49 | + |
| 50 | + await audit(req, 'account.export'); |
| 51 | + reply |
| 52 | + .header('Content-Type', 'application/json') |
| 53 | + .header('Content-Disposition', 'attachment; filename="opencoperlock-export.json"'); |
| 54 | + return reply.send(JSON.stringify(data, null, 2)); |
| 55 | + }); |
| 56 | + |
| 57 | + // POST /account/delete — permanently delete the account (password required). Removes the |
| 58 | + // user's storage blobs first, then the row (which cascades folders/files/shares/etc.). |
| 59 | + app.post('/delete', async (req, reply) => { |
| 60 | + const body = parseOr400(reply, passwordConfirmSchema, req.body); |
| 61 | + if (!body) return; |
| 62 | + const user = await prisma.user.findUniqueOrThrow({ where: { id: req.user!.id } }); |
| 63 | + if (!(await verifyPassword(user.passwordHash, body.password))) { |
| 64 | + return reply.code(401).send({ error: 'Incorrect password' }); |
| 65 | + } |
| 66 | + // Don't allow the last admin to delete themselves and lock the instance out. |
| 67 | + if (user.role === 'ADMIN') { |
| 68 | + const admins = await prisma.user.count({ where: { role: 'ADMIN' } }); |
| 69 | + if (admins <= 1) { |
| 70 | + return reply.code(400).send({ error: 'Cannot delete the only administrator account' }); |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + const [files, versions] = await Promise.all([ |
| 75 | + prisma.fileObject.findMany({ where: { ownerId: user.id }, select: { storageKey: true } }), |
| 76 | + prisma.fileVersion.findMany({ where: { file: { ownerId: user.id } }, select: { storageKey: true } }), |
| 77 | + ]); |
| 78 | + for (const f of [...files, ...versions]) { |
| 79 | + await app.ctx.storage.delete(f.storageKey).catch(() => {}); |
| 80 | + } |
| 81 | + await audit(req, 'account.delete', { actorId: user.id, target: user.id }); |
| 82 | + await prisma.user.delete({ where: { id: user.id } }); |
| 83 | + clearSessionCookie(reply, secureCookies); |
| 84 | + return { ok: true }; |
| 85 | + }); |
| 86 | +}; |
0 commit comments