feat(db): encrypt Profile health fields at rest (ADR 0002)

Wire prisma-field-encryption AES-256-GCM extension on the shared Prisma
client and annotate the four sensitive columns on Profile with @encrypted:
- weightStartKg / weightCurrentKg / weightGoalKg (Decimal → String)
- targetDate (DateTime @db.Date → String, ISO YYYY-MM-DD)

Other Profile fields stay in clear text per ADR 0002 (age, gender,
heightCm, activityLevel) — they're needed for plan generation and
aggregate analytics, and are not strongly identifying on their own.

apps/api profile.routes.ts:
- serialize() now reads the columns as strings and parses them back to
  numbers for BMR/TDEE; targetDate is already an ISO string from the DB
- the upsert stringifies numeric inputs and slices the date to YYYY-MM-DD

Env wiring:
- packages/db, apps/api, apps/web .env.example all document
  PRISMA_FIELD_ENCRYPTION_KEY (k1.aesgcm256.<base64url>) — must match
  across every process that hits the DB
- key generation snippet documented inline

Migration is intentionally NOT in this commit: needs to be created against
a live Postgres instance and applied. The fields change Decimal/Date → text
so prisma migrate dev will require a USING cast — see the follow-up commit.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
lucianoandClaude Opus 4.7 committed 2026-04-29 15:03:24 +02:00
1 parent f954be610b
commit 9555022143
8 files changed
+51 -23

No files matched your search

+5
View File
@@ -8,6 +8,11 @@ CORS_ORIGINS=http://localhost:3000
DATABASE_URL=postgresql://luciano:luciano%40@localhost:5432/ketopath?schema=public DATABASE_URL=postgresql://luciano:luciano%40@localhost:5432/ketopath?schema=public
# Cifratura at-rest dei campi sanitari (vedi ADR 0002).
# Genera con: node -e "console.log('k1.aesgcm256.'+require('crypto').generateKeySync('aes',{length:256}).export().toString('base64url'))"
# DEVE coincidere con apps/web/.env e con tutti i deploy che leggono il DB.
PRISMA_FIELD_ENCRYPTION_KEY=
# Better Auth — DEVE coincidere con apps/web/.env (sessione condivisa) # Better Auth — DEVE coincidere con apps/web/.env (sessione condivisa)
BETTER_AUTH_SECRET= BETTER_AUTH_SECRET=
BETTER_AUTH_URL=http://localhost:3000 BETTER_AUTH_URL=http://localhost:3000
+21 -16
View File
@@ -10,21 +10,24 @@ import type { FastifyPluginAsync } from 'fastify';
import { requireAuth } from '../../plugins/auth.js'; import { requireAuth } from '../../plugins/auth.js';
// The weight columns are encrypted at rest (ADR 0002) and therefore stored
// as String. The Zod input schema parses numeric strings → numbers, but the
// Prisma row keeps them as strings — so serialize/parse explicitly here.
function serialize( function serialize(
profile: { profile: {
age: number; age: number;
gender: Gender; gender: Gender;
heightCm: number; heightCm: number;
weightStartKg: { toNumber(): number }; weightStartKg: string;
weightCurrentKg: { toNumber(): number }; weightCurrentKg: string;
weightGoalKg: { toNumber(): number }; weightGoalKg: string;
activityLevel: ActivityLevel; activityLevel: ActivityLevel;
targetDate: Date | null; targetDate: string | null;
currentPhase: string; currentPhase: string;
} | null, } | null,
) { ) {
if (!profile) return null; if (!profile) return null;
const weightCurrentKg = profile.weightCurrentKg.toNumber(); const weightCurrentKg = Number(profile.weightCurrentKg);
const bmr = calculateBmr({ const bmr = calculateBmr({
weightKg: weightCurrentKg, weightKg: weightCurrentKg,
heightCm: profile.heightCm, heightCm: profile.heightCm,
@@ -36,11 +39,11 @@ function serialize(
age: profile.age, age: profile.age,
gender: profile.gender, gender: profile.gender,
heightCm: profile.heightCm, heightCm: profile.heightCm,
weightStartKg: profile.weightStartKg.toNumber(), weightStartKg: Number(profile.weightStartKg),
weightCurrentKg, weightCurrentKg,
weightGoalKg: profile.weightGoalKg.toNumber(), weightGoalKg: Number(profile.weightGoalKg),
activityLevel: profile.activityLevel, activityLevel: profile.activityLevel,
targetDate: profile.targetDate?.toISOString() ?? null, targetDate: profile.targetDate,
currentPhase: profile.currentPhase, currentPhase: profile.currentPhase,
derived: { derived: {
bmr: Math.round(bmr), bmr: Math.round(bmr),
@@ -67,6 +70,8 @@ export const profileRoutes: FastifyPluginAsync = async (fastify) => {
const data = parsed.data; const data = parsed.data;
const userId = request.user!.id; const userId = request.user!.id;
const targetDateStr = data.targetDate ? data.targetDate.toISOString().slice(0, 10) : null;
const profile = await fastify.prisma.profile.upsert({ const profile = await fastify.prisma.profile.upsert({
where: { userId }, where: { userId },
create: { create: {
@@ -74,21 +79,21 @@ export const profileRoutes: FastifyPluginAsync = async (fastify) => {
age: data.age, age: data.age,
gender: data.gender, gender: data.gender,
heightCm: data.heightCm, heightCm: data.heightCm,
weightStartKg: data.weightStartKg, weightStartKg: String(data.weightStartKg),
weightCurrentKg: data.weightCurrentKg, weightCurrentKg: String(data.weightCurrentKg),
weightGoalKg: data.weightGoalKg, weightGoalKg: String(data.weightGoalKg),
activityLevel: data.activityLevel, activityLevel: data.activityLevel,
targetDate: data.targetDate ?? null, targetDate: targetDateStr,
}, },
update: { update: {
age: data.age, age: data.age,
gender: data.gender, gender: data.gender,
heightCm: data.heightCm, heightCm: data.heightCm,
weightStartKg: data.weightStartKg, weightStartKg: String(data.weightStartKg),
weightCurrentKg: data.weightCurrentKg, weightCurrentKg: String(data.weightCurrentKg),
weightGoalKg: data.weightGoalKg, weightGoalKg: String(data.weightGoalKg),
activityLevel: data.activityLevel, activityLevel: data.activityLevel,
targetDate: data.targetDate ?? null, targetDate: targetDateStr,
}, },
}); });
+4
View File
@@ -12,6 +12,10 @@ BETTER_AUTH_URL=http://localhost:3000
# Database (Better Auth usa @ketopath/db, che legge DATABASE_URL) # Database (Better Auth usa @ketopath/db, che legge DATABASE_URL)
DATABASE_URL=postgresql://luciano:luciano%40@localhost:5432/ketopath?schema=public DATABASE_URL=postgresql://luciano:luciano%40@localhost:5432/ketopath?schema=public
# Cifratura at-rest dei campi sanitari (vedi ADR 0002).
# DEVE essere identica a apps/api/.env.
PRISMA_FIELD_ENCRYPTION_KEY=
# Google OAuth (configurato a fine progetto) # Google OAuth (configurato a fine progetto)
# GOOGLE_CLIENT_ID= # GOOGLE_CLIENT_ID=
# GOOGLE_CLIENT_SECRET= # GOOGLE_CLIENT_SECRET=
+3
View File
@@ -1 +1,4 @@
DATABASE_URL="postgresql://luciano:luciano%40@localhost:5432/ketopath?schema=public" DATABASE_URL="postgresql://luciano:luciano%40@localhost:5432/ketopath?schema=public"
# Cifratura at-rest (vedi ADR 0002). Stesso valore in apps/api/.env e apps/web/.env.
PRISMA_FIELD_ENCRYPTION_KEY=
+2 -1
View File
@@ -19,7 +19,8 @@
"db:seed": "tsx prisma/seed.ts" "db:seed": "tsx prisma/seed.ts"
}, },
"dependencies": { "dependencies": {
"@prisma/client": "^5.18.0" "@prisma/client": "^5.18.0",
"prisma-field-encryption": "^1.6.0"
}, },
"devDependencies": { "devDependencies": {
"@ketopath/eslint-config": "workspace:*", "@ketopath/eslint-config": "workspace:*",
+8 -4
View File
@@ -128,11 +128,15 @@ model Profile {
age Int age Int
gender Gender gender Gender
heightCm Int @map("height_cm") heightCm Int @map("height_cm")
weightStartKg Decimal @map("weight_start_kg") @db.Decimal(5, 2) /// @encrypted
weightCurrentKg Decimal @map("weight_current_kg") @db.Decimal(5, 2) weightStartKg String @map("weight_start_kg")
weightGoalKg Decimal @map("weight_goal_kg") @db.Decimal(5, 2) /// @encrypted
weightCurrentKg String @map("weight_current_kg")
/// @encrypted
weightGoalKg String @map("weight_goal_kg")
activityLevel ActivityLevel @map("activity_level") activityLevel ActivityLevel @map("activity_level")
targetDate DateTime? @map("target_date") @db.Date /// @encrypted
targetDate String? @map("target_date")
currentPhase Phase @default(INTENSIVE) @map("current_phase") currentPhase Phase @default(INTENSIVE) @map("current_phase")
createdAt DateTime @default(now()) @map("created_at") createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at") updatedAt DateTime @updatedAt @map("updated_at")
+8 -2
View File
@@ -1,13 +1,19 @@
import { PrismaClient } from '@prisma/client'; import { PrismaClient } from '@prisma/client';
import { fieldEncryptionExtension } from 'prisma-field-encryption';
// Singleton-friendly storage of the BASE client (so HMR doesn't open a new pool
// every time). The exported `prisma` is the EXTENDED client returned by
// $extends — it wraps the base client with the field-encryption middleware.
const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient }; const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };
export const prisma: PrismaClient = const baseClient =
globalForPrisma.prisma ?? globalForPrisma.prisma ??
new PrismaClient({ new PrismaClient({
log: process.env.NODE_ENV === 'development' ? ['warn', 'error'] : ['error'], log: process.env.NODE_ENV === 'development' ? ['warn', 'error'] : ['error'],
}); });
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
globalForPrisma.prisma = prisma; globalForPrisma.prisma = baseClient;
} }
export const prisma = baseClient.$extends(fieldEncryptionExtension());
BIN
View File
Binary file not shown.