feat: GDPR (export+delete) + catalogo ricette 46→96
GDPR (PRD §14, art. 17 + 20) - GET /me/export.json: dump completo dei dati personali (User, Profile, Preferences, WeightEntry, FastEvent, MealPlan+slots, DailyCheckIn, DeviceToken). I campi @encrypted vengono decifrati a runtime dall'extension Prisma. Risposta con Content-Disposition attachment. - DELETE /me: cancellazione account con cascade automatico. Per gli account email/password richiede conferma password (verifica via auth.api.signInEmail). Account OAuth-only: solo sessione attiva. - Proxy Next /api/gdpr-export per same-origin + cookie sessione. - /profile: nuova sezione "I tuoi dati (GDPR)" in fondo con due azioni (esporta + elimina) e modale di conferma password per la cancellazione. Catalogo ricette 46 → 96 (target 100) - 50 ricette nuove italiane keto/low-carb bilanciate per categoria: 12 colazioni, 14 pranzi, 12 spuntini, 12 cene - Macros realistici, ingredienti dal seed esistente (no nuovi ingredienti necessari) - Run db:seed: ingredients +0 (catalog 55), recipes +49 (catalog 96), recipe-ingredient links: 323 i18n: namespace Profile esteso con dataEyebrow/Title/Subtitle, dataExport*, dataDelete* (incluso typed errors map), working. 81/81 unit test verdi. Lint, typecheck verdi. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
d8f2a17888
commit
60a3d072f6
8 files changed
+1206
No files matched your search
@@ -8,6 +8,7 @@ import { env } from './config/env.js';
|
||||
import { Sentry } from './lib/sentry.js';
|
||||
import { dbRoutes } from './modules/db/db.routes.js';
|
||||
import { healthRoutes } from './modules/health/health.routes.js';
|
||||
import { gdprRoutes } from './modules/me/gdpr.routes.js';
|
||||
import { meRoutes } from './modules/me/me.routes.js';
|
||||
import { notificationsRoutes } from './modules/notifications/notifications.routes.js';
|
||||
import { planExportRoutes } from './modules/plan/export.routes.js';
|
||||
@@ -54,6 +55,7 @@ export async function buildApp(): Promise<FastifyInstance> {
|
||||
await app.register(healthRoutes);
|
||||
await app.register(dbRoutes);
|
||||
await app.register(meRoutes);
|
||||
await app.register(gdprRoutes);
|
||||
await app.register(profileRoutes);
|
||||
await app.register(preferencesRoutes);
|
||||
await app.register(weightRoutes);
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
// PRD §14 — Diritto all'oblio (art. 17 GDPR) + portabilità (art. 20).
|
||||
//
|
||||
// `/me/export.json` restituisce un dump completo dei dati personali in JSON.
|
||||
// I campi @encrypted vengono decifrati a runtime dal Prisma extension, quindi
|
||||
// arrivano qui in chiaro: l'export deve essere autenticato e con
|
||||
// Content-Disposition attachment.
|
||||
//
|
||||
// `DELETE /me` cancella l'utente e tutti i dati collegati via cascade. Per
|
||||
// evitare cancellazioni accidentali richiediamo conferma re-inserendo la
|
||||
// password (per gli account email/password); per gli OAuth-only basta la
|
||||
// sessione attiva.
|
||||
|
||||
import { auth } from '@ketopath/auth';
|
||||
import type { FastifyPluginAsync } from 'fastify';
|
||||
|
||||
import { requireAuth } from '../../plugins/auth.js';
|
||||
|
||||
export const gdprRoutes: FastifyPluginAsync = async (fastify) => {
|
||||
fastify.get('/me/export.json', { preHandler: requireAuth() }, async (request, reply) => {
|
||||
const userId = request.user!.id;
|
||||
|
||||
const [
|
||||
user,
|
||||
profile,
|
||||
preferences,
|
||||
weightEntries,
|
||||
fastEvents,
|
||||
mealPlans,
|
||||
checkIns,
|
||||
deviceTokens,
|
||||
] = await Promise.all([
|
||||
fastify.prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
emailVerified: true,
|
||||
name: true,
|
||||
image: true,
|
||||
role: true,
|
||||
disclaimerAcceptedAt: true,
|
||||
phase2StartedAt: true,
|
||||
fastingPausedUntil: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
},
|
||||
}),
|
||||
fastify.prisma.profile.findUnique({ where: { userId } }),
|
||||
fastify.prisma.preferences.findUnique({ where: { userId } }),
|
||||
fastify.prisma.weightEntry.findMany({
|
||||
where: { userId },
|
||||
orderBy: { date: 'asc' },
|
||||
}),
|
||||
fastify.prisma.fastEvent.findMany({
|
||||
where: { userId },
|
||||
orderBy: { startedAt: 'asc' },
|
||||
}),
|
||||
fastify.prisma.mealPlan.findMany({
|
||||
where: { userId },
|
||||
orderBy: { weekStart: 'asc' },
|
||||
include: {
|
||||
slots: {
|
||||
include: {
|
||||
selected: { select: { id: true, name: true } },
|
||||
alternatives: { select: { id: true, name: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
fastify.prisma.dailyCheckIn.findMany({
|
||||
where: { userId },
|
||||
orderBy: { date: 'asc' },
|
||||
}),
|
||||
fastify.prisma.deviceToken.findMany({
|
||||
where: { userId },
|
||||
select: {
|
||||
id: true,
|
||||
platform: true,
|
||||
userAgent: true,
|
||||
createdAt: true,
|
||||
lastSeenAt: true,
|
||||
// endpoint/p256dh/auth omessi: sono token push, non dato personale
|
||||
},
|
||||
}),
|
||||
]);
|
||||
|
||||
const payload = {
|
||||
exportedAt: new Date().toISOString(),
|
||||
schemaVersion: '1.0',
|
||||
user,
|
||||
profile,
|
||||
preferences,
|
||||
weightEntries,
|
||||
fastEvents,
|
||||
mealPlans,
|
||||
dailyCheckIns: checkIns,
|
||||
deviceTokens,
|
||||
};
|
||||
|
||||
return reply
|
||||
.header('Content-Type', 'application/json; charset=utf-8')
|
||||
.header('Content-Disposition', 'attachment; filename="ketopath-export.json"')
|
||||
.send(payload);
|
||||
});
|
||||
|
||||
// DELETE /me — cancellazione account.
|
||||
// Body opzionale { password } per ulteriore conferma sull'account
|
||||
// email/password. Il cascade del modello rimuove tutto il resto.
|
||||
fastify.delete('/me', { preHandler: requireAuth() }, async (request, reply) => {
|
||||
const userId = request.user!.id;
|
||||
const body = (request.body ?? {}) as { password?: unknown };
|
||||
|
||||
// Se l'utente ha un account credential, esigiamo la password per
|
||||
// confermare la cancellazione. Per OAuth-only saltiamo il check.
|
||||
const credentialAccount = await fastify.prisma.account.findFirst({
|
||||
where: { userId, providerId: 'credential' },
|
||||
select: { password: true },
|
||||
});
|
||||
if (credentialAccount && credentialAccount.password) {
|
||||
if (typeof body.password !== 'string' || body.password.length === 0) {
|
||||
return reply.code(400).send({ error: 'password_required' });
|
||||
}
|
||||
const email = request.user!.email;
|
||||
if (!email) return reply.code(400).send({ error: 'email_required' });
|
||||
// Better Auth: verifica la password tentando un sign-in. Se la password
|
||||
// non corrisponde lancia un errore. Non emettiamo cookie reply.
|
||||
try {
|
||||
await auth.api.signInEmail({
|
||||
body: { email, password: body.password },
|
||||
});
|
||||
} catch {
|
||||
return reply.code(401).send({ error: 'invalid_password' });
|
||||
}
|
||||
}
|
||||
|
||||
// Hard-delete con cascade.
|
||||
await fastify.prisma.user.delete({ where: { id: userId } });
|
||||
|
||||
request.log.info({ userId }, '[gdpr] user account deleted');
|
||||
|
||||
// Cookie di sessione: l'utente è già stato cancellato (cascade) ma il
|
||||
// browser potrebbe ancora avere il cookie. Lo invalidiamo via API.
|
||||
return reply
|
||||
.header('Set-Cookie', 'ketopath.session_token=; Path=/; Max-Age=0; HttpOnly')
|
||||
.code(204)
|
||||
.send();
|
||||
});
|
||||
};
|
||||
@@ -571,6 +571,26 @@
|
||||
"LIGHT": "Leggero · sport 1–3 volte / settimana",
|
||||
"MODERATE": "Moderato · sport 3–5 volte / settimana",
|
||||
"INTENSE": "Intenso · sport 6+ volte / settimana"
|
||||
},
|
||||
"working": "Attendere…",
|
||||
"dataEyebrow": "I tuoi dati (GDPR)",
|
||||
"dataTitle": "I tuoi diritti sui dati personali",
|
||||
"dataSubtitle": "Puoi scaricare in qualsiasi momento una copia completa dei tuoi dati o eliminare l'account. Le richieste sono evase immediatamente.",
|
||||
"dataExportEyebrow": "Esporta",
|
||||
"dataExportDescription": "Scarica un file JSON con profilo, preferenze, pesate, sessioni di digiuno, piani e check-in.",
|
||||
"dataExportAction": "Esporta i miei dati",
|
||||
"dataDeleteEyebrow": "Elimina account",
|
||||
"dataDeleteDescription": "Cancellazione completa e irreversibile di tutti i tuoi dati. Niente backup, niente recupero.",
|
||||
"dataDeleteAction": "Elimina account",
|
||||
"dataDeleteWarning": "Questa azione è irreversibile. Conferma con la tua password per procedere.",
|
||||
"dataDeletePasswordPlaceholder": "La tua password",
|
||||
"dataDeleteConfirm": "Elimina definitivamente",
|
||||
"dataDeleteCancel": "Annulla",
|
||||
"dataDeleteErrors": {
|
||||
"password_required": "Inserisci la tua password.",
|
||||
"invalid_password": "Password non corretta.",
|
||||
"email_required": "Email assente sul tuo account.",
|
||||
"api_error": "Errore di rete. Riprova fra poco."
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,21 @@ export async function fetchProfile(): Promise<unknown | null> {
|
||||
return data.profile;
|
||||
}
|
||||
|
||||
export async function deleteAccount(
|
||||
password: string,
|
||||
): Promise<{ ok: true } | { ok: false; error: string }> {
|
||||
const cookie = headers().get('cookie') ?? '';
|
||||
const res = await fetch(`${API_URL}/me`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json', cookie },
|
||||
body: JSON.stringify({ password }),
|
||||
cache: 'no-store',
|
||||
});
|
||||
if (res.status === 204) return { ok: true };
|
||||
const body = (await res.json().catch(() => ({}))) as { error?: string };
|
||||
return { ok: false, error: body.error ?? `api_error_${res.status}` };
|
||||
}
|
||||
|
||||
export type SaveConditionsResult = { ok: true } | { ok: false; error: string };
|
||||
|
||||
export async function saveConditions(conditions: readonly string[]): Promise<SaveConditionsResult> {
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
'use client';
|
||||
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useTranslations } from 'next-intl';
|
||||
import { useState, useTransition } from 'react';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
|
||||
import { deleteAccount } from './actions';
|
||||
|
||||
export function DataPanel() {
|
||||
const t = useTranslations('Profile');
|
||||
const router = useRouter();
|
||||
const [confirmOpen, setConfirmOpen] = useState(false);
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [pending, startTransition] = useTransition();
|
||||
|
||||
function handleDelete(): void {
|
||||
setError(null);
|
||||
startTransition(async () => {
|
||||
const result = await deleteAccount(password);
|
||||
if (!result.ok) {
|
||||
setError(t(`dataDeleteErrors.${result.error}` as never) ?? t('dataDeleteErrors.api_error'));
|
||||
return;
|
||||
}
|
||||
// Account cancellato: vai alla home pubblica.
|
||||
router.replace('/');
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="space-y-8">
|
||||
<header className="space-y-3">
|
||||
<p className="editorial-eyebrow">{t('dataEyebrow')}</p>
|
||||
<h2 className="font-display text-ink text-3xl font-medium leading-tight tracking-tight">
|
||||
{t('dataTitle')}
|
||||
</h2>
|
||||
<p className="font-display text-ink-soft max-w-xl text-base italic leading-snug">
|
||||
{t('dataSubtitle')}
|
||||
</p>
|
||||
</header>
|
||||
|
||||
<div className="border-ink/15 border-t" />
|
||||
|
||||
<div className="grid gap-8 md:grid-cols-2">
|
||||
<article className="space-y-3">
|
||||
<p className="editorial-eyebrow">{t('dataExportEyebrow')}</p>
|
||||
<p className="font-display text-ink text-base leading-snug">
|
||||
{t('dataExportDescription')}
|
||||
</p>
|
||||
<a
|
||||
href="/api/gdpr-export"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-ink hover:text-pomodoro decoration-pomodoro inline-block font-mono text-[11px] uppercase tracking-widest underline decoration-[1.5px] underline-offset-[5px] transition-colors"
|
||||
>
|
||||
{t('dataExportAction')} ↗
|
||||
</a>
|
||||
</article>
|
||||
|
||||
<article className="border-pomodoro/40 space-y-3 border-l pl-6">
|
||||
<p className="editorial-eyebrow text-pomodoro">{t('dataDeleteEyebrow')}</p>
|
||||
<p className="font-display text-ink text-base leading-snug">
|
||||
{t('dataDeleteDescription')}
|
||||
</p>
|
||||
{!confirmOpen ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setConfirmOpen(true)}
|
||||
className="border-pomodoro text-pomodoro hover:bg-pomodoro hover:text-carta-light"
|
||||
>
|
||||
{t('dataDeleteAction')}
|
||||
</Button>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
<p className="font-display text-pomodoro text-sm italic">{t('dataDeleteWarning')}</p>
|
||||
<Input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder={t('dataDeletePasswordPlaceholder')}
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
{error ? (
|
||||
<p className="font-display text-pomodoro text-sm italic" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button
|
||||
type="button"
|
||||
onClick={handleDelete}
|
||||
disabled={pending || password.length === 0}
|
||||
className="bg-pomodoro text-carta-light hover:bg-ink"
|
||||
>
|
||||
{pending ? t('working') : t('dataDeleteConfirm')}
|
||||
</Button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setConfirmOpen(false);
|
||||
setPassword('');
|
||||
setError(null);
|
||||
}}
|
||||
className="text-ink-soft hover:text-ink font-mono text-[11px] uppercase tracking-widest"
|
||||
>
|
||||
{t('dataDeleteCancel')}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { Masthead } from '@/components/masthead';
|
||||
import { getServerSession } from '@/lib/auth';
|
||||
|
||||
import { fetchProfile } from './actions';
|
||||
import { DataPanel } from './data-panel';
|
||||
import { fetchNotificationConfig } from './notifications-actions';
|
||||
import { NotificationsPanel } from './notifications-panel';
|
||||
import { fetchPreferences } from './preferences-actions';
|
||||
@@ -74,6 +75,12 @@ function ProfilePageContent({
|
||||
<div className="animate-fade-up [animation-delay:660ms]">
|
||||
<NotificationsPanel initial={notifications} />
|
||||
</div>
|
||||
|
||||
<div className="rule animate-rule-in my-16 [animation-delay:780ms]" />
|
||||
|
||||
<div className="animate-fade-up [animation-delay:840ms]">
|
||||
<DataPanel />
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
// Proxy verso /me/export.json (GDPR art. 20).
|
||||
|
||||
import { headers } from 'next/headers';
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
|
||||
const API_URL = process.env.API_URL ?? 'http://localhost:4000';
|
||||
|
||||
export async function GET(): Promise<Response> {
|
||||
const cookie = headers().get('cookie') ?? '';
|
||||
const upstream = await fetch(`${API_URL}/me/export.json`, {
|
||||
headers: { cookie },
|
||||
cache: 'no-store',
|
||||
});
|
||||
if (!upstream.ok) {
|
||||
return NextResponse.json(
|
||||
{ error: `api_error_${upstream.status}` },
|
||||
{ status: upstream.status },
|
||||
);
|
||||
}
|
||||
const body = await upstream.text();
|
||||
return new NextResponse(body, {
|
||||
status: 200,
|
||||
headers: {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'Content-Disposition':
|
||||
upstream.headers.get('content-disposition') ??
|
||||
'attachment; filename="ketopath-export.json"',
|
||||
'Cache-Control': 'no-store',
|
||||
},
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user