Files
HealthLog/src/app/api/export/mood/route.ts
T
Marc-André Bombeck 4d3a02cc1a feat(security): add second-factor schema and encrypt free-text health notes at rest
Lay the account-security and data-sovereignty substrate for v1.23. No
user-facing behaviour yet — schema, crypto registry, redaction, and the
note-encryption data path only.

Schema + migrations:
- 0199 — User totp_secret_encrypted / totp_confirmed_at / mfa_enforced /
  passkey_upgrade_nudge_dismissed; Session mfa_verified_at / last_active_at;
  Passkey last_used_at. All additive, nullable / defaulted.
- 0200 — mfa_challenges (single-use step-up ticket; only the ticket hash is
  stored, so no session or token is ever minted before the second factor),
  mfa_recovery_codes (Argon2id at rest), webauthn_mfa_credentials (second-factor
  keys, kept separate from passkeys, which remain the passwordless-primary set).
- 0201 — mood_entries.note_encrypted + measurements.notes_encrypted (BYTEA),
  matching the existing free-text encrypted-note convention.

Free-text health notes:
- New writes encrypt the mood / measurement note into the *_encrypted column and
  null the legacy plaintext column; reads prefer the ciphertext and fall back to
  plaintext only for not-yet-migrated rows, via a single read/write helper.
- A boot-time job migrates existing plaintext rows in an idempotent,
  transactional, fail-closed pass (encrypt, then null the plaintext, per row in
  one transaction; safe to re-run; a row with content is never left both-null).
- The legacy plaintext columns are kept this release and dropped in a follow-up
  once the backfill reports zero remaining rows — the same boundary the
  key-rotation playbook uses before dropping a legacy key.

Crypto coverage:
- Register the three new encrypted columns and wire them into the key-rotation
  script so a rotation never orphans them.
- Extend the observability and log redaction denylists so TOTP secrets, MFA /
  recovery / backup codes, and export passphrases never reach a wide event.
2026-06-27 19:33:10 +02:00

101 lines
3.0 KiB
TypeScript

/**
* GET /api/export/mood
*
* v1.4.16 phase B7. Per-type CSV download for the consolidated
* `/settings/export` UI. Filterable by `since` / `until` (inclusive
* date strings parsed via the standard Date constructor — invalid
* values are silently dropped from the where-clause).
*
* Response is `text/csv` with an attachment filename ending in `.csv`.
*
* Auth: cookie session OR Bearer token (`requireAuth`).
* Rate-limit: shared `export:<userId>` bucket (10/h).
* Audit: `user.export.mood` with the resolved filter.
*/
import { prisma } from "@/lib/db";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import { apiError, getClientIp } from "@/lib/api-response";
import { checkRateLimit } from "@/lib/rate-limit";
import { toCSV, formatMoodEntriesForExport } from "@/lib/export";
import { shapeMoodNote } from "@/lib/crypto/note-cipher";
import { resolveUserTimezone } from "@/lib/tz/resolver";
import { NextRequest, NextResponse } from "next/server";
export const GET = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
annotate({ action: { name: "user.export.mood" } });
const rl = await checkRateLimit(`export:${user.id}`, 10, 60 * 60 * 1000);
if (!rl.allowed) {
return apiError("Maximum 10 exports per hour", 429);
}
const params = new URL(request.url).searchParams;
const since = params.get("since")
? safeDate(params.get("since")!)
: undefined;
const until = params.get("until")
? safeDate(params.get("until")!)
: undefined;
const where: {
userId: string;
deletedAt: null;
moodLoggedAt?: { gte?: Date; lte?: Date };
} = {
userId: user.id,
// v1.7.0 sync — exclude tombstoned rows from the export.
deletedAt: null,
};
if (since || until) {
where.moodLoggedAt = {};
if (since) where.moodLoggedAt.gte = since;
if (until) where.moodLoggedAt.lte = until;
}
const [entries, userTz] = await Promise.all([
prisma.moodEntry.findMany({
where,
orderBy: { moodLoggedAt: "desc" },
}),
resolveUserTimezone(user.id),
]);
const csv = toCSV(
formatMoodEntriesForExport(entries.map(shapeMoodNote), userTz),
);
await auditLog("user.export.mood", {
userId: user.id,
ipAddress: getClientIp(request),
details: {
count: entries.length,
since: since?.toISOString() ?? null,
until: until?.toISOString() ?? null,
},
});
annotate({
meta: {
export_count: entries.length,
},
});
const stamp = new Date().toISOString().slice(0, 10);
return new NextResponse(csv, {
status: 200,
headers: {
"Content-Type": "text/csv; charset=utf-8",
"Content-Disposition": `attachment; filename="healthlog-mood-${user.id}-${stamp}.csv"`,
"Cache-Control": "no-store",
},
});
});
function safeDate(value: string): Date | undefined {
const d = new Date(value);
return Number.isNaN(d.getTime()) ? undefined : d;
}